Began implementation of OpenID 2.0 relying party support.
[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  * 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 "ctdl_module.h"
46 #include "config.h"
47 #include "citserver.h"
48 #include "user_ops.h"
49
50 typedef struct _ctdl_openid {
51         StrBuf *claimed_id;
52         StrBuf *server;
53         int verified;
54         HashList *sreg_keys;
55 } ctdl_openid;
56
57 void Free_ctdl_openid(ctdl_openid **FreeMe)
58 {
59         if (*FreeMe == NULL)
60                 return;
61         FreeStrBuf(&(*FreeMe)->claimed_id);
62         FreeStrBuf(&(*FreeMe)->server);
63         DeleteHash(&(*FreeMe)->sreg_keys);
64         free(*FreeMe);
65         *FreeMe = NULL;
66 }
67
68
69 /*
70  * This cleanup function blows away the temporary memory used by this module.
71  */
72 void openid_cleanup_function(void) {
73         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
74
75         if (CCC->openid_data != NULL) {
76                 syslog(LOG_DEBUG, "Clearing OpenID session state");
77                 Free_ctdl_openid((ctdl_openid **) &CCC->openid_data);
78         }
79 }
80
81
82 /**************************************************************************/
83 /*                                                                        */
84 /* Functions in this section handle Citadel internal OpenID mapping stuff */
85 /*                                                                        */
86 /**************************************************************************/
87
88
89 /*
90  * The structure of an openid record *key* is:
91  *
92  * |--------------claimed_id-------------|
93  *     (actual length of claimed id)
94  *
95  *
96  * The structure of an openid record *value* is:
97  *
98  * |-----user_number----|------------claimed_id---------------|
99  *    (sizeof long)          (actual length of claimed id)
100  *
101  */
102
103
104
105 /*
106  * Attach an OpenID to a Citadel account
107  */
108 int attach_openid(struct ctdluser *who, StrBuf *claimed_id)
109 {
110         struct cdbdata *cdboi;
111         long fetched_usernum;
112         char *data;
113         int data_len;
114         char buf[2048];
115
116         if (!who) return(1);
117         if (StrLength(claimed_id)==0) return(1);
118
119         /* Check to see if this OpenID is already in the database */
120
121         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
122         if (cdboi != NULL) {
123                 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
124                 cdb_free(cdboi);
125
126                 if (fetched_usernum == who->usernum) {
127                         syslog(LOG_INFO, "%s already associated; no action is taken", ChrPtr(claimed_id));
128                         return(0);
129                 }
130                 else {
131                         syslog(LOG_INFO, "%s already belongs to another user", ChrPtr(claimed_id));
132                         return(3);
133                 }
134         }
135
136         /* Not already in the database, so attach it now */
137
138         data_len = sizeof(long) + StrLength(claimed_id) + 1;
139         data = malloc(data_len);
140
141         memcpy(data, &who->usernum, sizeof(long));
142         memcpy(&data[sizeof(long)], ChrPtr(claimed_id), StrLength(claimed_id) + 1);
143
144         cdb_store(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id), data, data_len);
145         free(data);
146
147         snprintf(buf, sizeof buf, "User <%s> (#%ld) has claimed the OpenID URL %s\n",
148                  who->fullname, who->usernum, ChrPtr(claimed_id));
149         CtdlAideMessage(buf, "OpenID claim");
150         syslog(LOG_INFO, "%s", buf);
151         return(0);
152 }
153
154
155
156 /*
157  * When a user is being deleted, we have to delete any OpenID associations
158  */
159 void openid_purge(struct ctdluser *usbuf) {
160         struct cdbdata *cdboi;
161         HashList *keys = NULL;
162         HashPos *HashPos;
163         char *deleteme = NULL;
164         long len;
165         void *Value;
166         const char *Key;
167         long usernum = 0L;
168
169         keys = NewHash(1, NULL);
170         if (!keys) return;
171
172         cdb_rewind(CDB_OPENID);
173         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
174                 if (cdboi->len > sizeof(long)) {
175                         memcpy(&usernum, cdboi->ptr, sizeof(long));
176                         if (usernum == usbuf->usernum) {
177                                 deleteme = strdup(cdboi->ptr + sizeof(long)),
178                                 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
179                         }
180                 }
181                 cdb_free(cdboi);
182         }
183
184         /* Go through the hash list, deleting keys we stored in it */
185
186         HashPos = GetNewHashPos(keys, 0);
187         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
188         {
189                 syslog(LOG_DEBUG, "Deleting associated OpenID <%s>", (char*)Value);
190                 cdb_delete(CDB_OPENID, Value, strlen(Value));
191                 /* note: don't free(Value) -- deleting the hash list will handle this for us */
192         }
193         DeleteHashPos(&HashPos);
194         DeleteHash(&keys);
195 }
196
197
198 /*
199  * List the OpenIDs associated with the currently logged in account
200  */
201 void cmd_oidl(char *argbuf) {
202         struct cdbdata *cdboi;
203         long usernum = 0L;
204
205         if (CtdlAccessCheck(ac_logged_in)) return;
206         cdb_rewind(CDB_OPENID);
207         cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
208
209         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
210                 if (cdboi->len > sizeof(long)) {
211                         memcpy(&usernum, cdboi->ptr, sizeof(long));
212                         if (usernum == CC->user.usernum) {
213                                 cprintf("%s\n", cdboi->ptr + sizeof(long));
214                         }
215                 }
216                 cdb_free(cdboi);
217         }
218         cprintf("000\n");
219 }
220
221
222 /*
223  * List ALL OpenIDs in the database
224  */
225 void cmd_oida(char *argbuf) {
226         struct cdbdata *cdboi;
227         long usernum;
228         struct ctdluser usbuf;
229
230         if (CtdlAccessCheck(ac_aide)) return;
231         cdb_rewind(CDB_OPENID);
232         cprintf("%d List of all OpenIDs in the database:\n", LISTING_FOLLOWS);
233
234         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
235                 if (cdboi->len > sizeof(long)) {
236                         memcpy(&usernum, cdboi->ptr, sizeof(long));
237                         if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
238                                 usbuf.fullname[0] = 0;
239                         } 
240                         cprintf("%s|%ld|%s\n",
241                                 cdboi->ptr + sizeof(long),
242                                 usernum,
243                                 usbuf.fullname
244                         );
245                 }
246                 cdb_free(cdboi);
247         }
248         cprintf("000\n");
249 }
250
251
252 /*
253  * Attempt to register (populate the vCard) the currently-logged-in user
254  * using the data from Simple Registration Extension, if present.
255  */
256 void populate_vcard_from_sreg(HashList *sreg_keys) {
257
258         struct vCard *v;
259         int pop = 0;                    /* number of fields populated */
260         char *data = NULL;
261         char *postcode = NULL;
262         char *country = NULL;
263
264         if (!sreg_keys) return;
265         v = vcard_new();
266         if (!v) return;
267
268         if (GetHash(sreg_keys, "identity", 8, (void *) &data)) {
269                 vcard_add_prop(v, "url;type=openid", data);
270                 ++pop;
271         }
272
273         if (GetHash(sreg_keys, "sreg.email", 10, (void *) &data)) {
274                 vcard_add_prop(v, "email;internet", data);
275                 ++pop;
276         }
277
278         if (GetHash(sreg_keys, "sreg.nickname", 13, (void *) &data)) {
279                 vcard_add_prop(v, "nickname", data);
280                 ++pop;
281         }
282
283         if (GetHash(sreg_keys, "sreg.fullname", 13, (void *) &data)) {
284                 char n[256];
285                 vcard_add_prop(v, "fn", data);
286                 vcard_fn_to_n(n, data, sizeof n);
287                 vcard_add_prop(v, "n", n);
288                 ++pop;
289         }
290
291         if (!GetHash(sreg_keys, "sreg.postcode", 13, (void *) &postcode)) {
292                 postcode = NULL;
293         }
294
295         if (!GetHash(sreg_keys, "sreg.country", 12, (void *) &country)) {
296                 country = NULL;
297         }
298
299         if (postcode || country) {
300                 char adr[256];
301                 snprintf(adr, sizeof adr, ";;;;;%s;%s",
302                         (postcode ? postcode : ""),
303                         (country ? country : "")
304                 );
305                 vcard_add_prop(v, "adr", adr);
306                 ++pop;
307         }
308
309         if (GetHash(sreg_keys, "sreg.dob", 8, (void *) &data)) {
310                 vcard_add_prop(v, "bday", data);
311                 ++pop;
312         }
313
314         if (GetHash(sreg_keys, "sreg.gender", 11, (void *) &data)) {
315                 vcard_add_prop(v, "x-funambol-gender", data);
316                 ++pop;
317         }
318
319         /* Only save the vCard if there is some useful data in it */
320         if (pop > 0) {
321                 char *ser;
322                 ser = vcard_serialize(v);
323                 if (ser) {
324                         CtdlWriteObject(USERCONFIGROOM, "text/x-vcard",
325                                 ser, strlen(ser)+1, &CC->user, 0, 0, 0
326                         );
327                         free(ser);
328                 }
329         }
330         vcard_free(v);
331 }
332
333
334 /*
335  * Create a new user account, manually specifying the name, after successfully
336  * verifying an OpenID (which will of course be attached to the account)
337  */
338 void cmd_oidc(char *argbuf) {
339         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
340
341         if (!oiddata) {
342                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
343                 return;
344         }
345
346         if (!oiddata->verified) {
347                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
348                 return;
349         }
350
351         /* We can make the semantics of OIDC exactly the same as NEWU, simply
352          * by _calling_ cmd_newu() and letting it run.  Very clever!
353          */
354         cmd_newu(argbuf);
355
356         /* Now, if this logged us in, we have to attach the OpenID */
357         if (CC->logged_in) {
358                 attach_openid(&CC->user, oiddata->claimed_id);
359                 if (oiddata->sreg_keys != NULL) {
360                         populate_vcard_from_sreg(oiddata->sreg_keys);
361                 }
362         }
363
364 }
365
366
367 /*
368  * Detach an OpenID from the currently logged in account
369  */
370 void cmd_oidd(char *argbuf) {
371         struct cdbdata *cdboi;
372         char id_to_detach[1024];
373         int this_is_mine = 0;
374         long usernum = 0L;
375
376         if (CtdlAccessCheck(ac_logged_in)) return;
377         extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
378         if (IsEmptyStr(id_to_detach)) {
379                 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
380         }
381
382         cdb_rewind(CDB_OPENID);
383         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
384                 if (cdboi->len > sizeof(long)) {
385                         memcpy(&usernum, cdboi->ptr, sizeof(long));
386                         if (usernum == CC->user.usernum) {
387                                 this_is_mine = 1;
388                         }
389                 }
390                 cdb_free(cdboi);
391         }
392
393         if (!this_is_mine) {
394                 cprintf("%d That OpenID was not found or not associated with your account.\n",
395                         ERROR + ILLEGAL_VALUE);
396                 return;
397         }
398
399         cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
400         cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
401 }
402
403
404
405 /*
406  * Attempt to auto-create a new Citadel account using the nickname from Simple Registration Extension
407  */
408 int openid_create_user_via_sreg(StrBuf *claimed_id, HashList *sreg_keys)
409 {
410         char *desired_name = NULL;
411         char new_password[32];
412         long len;
413
414         if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
415         if (config.c_disable_newu) return(2);
416         if (CC->logged_in) return(3);
417         if (!GetHash(sreg_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
418
419         syslog(LOG_DEBUG, "The desired account name is <%s>", desired_name);
420
421         len = cutuserkey(desired_name);
422         if (!CtdlGetUser(&CC->user, desired_name)) {
423                 syslog(LOG_DEBUG, "<%s> is already taken by another user.", desired_name);
424                 memset(&CC->user, 0, sizeof(struct ctdluser));
425                 return(5);
426         }
427
428         /* The desired account name is available.  Create the account and log it in! */
429         if (create_user(desired_name, len, 1)) return(6);
430
431         snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
432         CtdlSetPassword(new_password);
433         attach_openid(&CC->user, claimed_id);
434         populate_vcard_from_sreg(sreg_keys);
435         return(0);
436 }
437
438
439 /*
440  * If a user account exists which is associated with the Claimed ID, log it in and return zero.
441  * Otherwise it returns nonzero.
442  */
443 int login_via_openid(StrBuf *claimed_id)
444 {
445         struct cdbdata *cdboi;
446         long usernum = 0;
447
448         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
449         if (cdboi == NULL) {
450                 return(-1);
451         }
452
453         memcpy(&usernum, cdboi->ptr, sizeof(long));
454         cdb_free(cdboi);
455
456         if (!CtdlGetUserByNumber(&CC->user, usernum)) {
457                 /* Now become the user we just created */
458                 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
459                 do_login();
460                 return(0);
461         }
462         else {
463                 memset(&CC->user, 0, sizeof(struct ctdluser));
464                 return(-1);
465         }
466 }
467
468
469
470
471 /**************************************************************************/
472 /*                                                                        */
473 /* Functions in this section handle OpenID protocol                       */
474 /*                                                                        */
475 /**************************************************************************/
476
477
478 /* 
479  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
480  */
481 void extract_link(StrBuf *target_buf, const char *rel, long repllen, StrBuf *source_buf)
482 {
483         int i;
484         const char *ptr;
485         const char *href_start = NULL;
486         const char *href_end = NULL;
487         const char *link_tag_start = NULL;
488         const char *link_tag_end = NULL;
489         const char *rel_start = NULL;
490         const char *rel_end = NULL;
491
492         if (!target_buf) return;
493         if (!rel) return;
494         if (!source_buf) return;
495
496         ptr = ChrPtr(source_buf);
497
498         FlushStrBuf(target_buf);
499         while (ptr = cbmstrcasestr(ptr, "<link"), ptr != NULL) {
500
501                 link_tag_start = ptr;
502                 link_tag_end = strchr(ptr, '>');
503                 if (link_tag_end == NULL)
504                         break;
505                 for (i=0; i < 1; i++ ){
506                         rel_start = cbmstrcasestr(link_tag_start, "rel=");
507                         if ((rel_start == NULL) ||
508                             (rel_start > link_tag_end)) 
509                                 continue;
510
511                         rel_start = strchr(rel_start, '\"');
512                         if ((rel_start == NULL) ||
513                             (rel_start > link_tag_end)) 
514                                 continue;
515                         ++rel_start;
516                         rel_end = strchr(rel_start, '\"');
517                         if ((rel_end == NULL) ||
518                             (rel_end == rel_start) ||
519                             (rel_end >= link_tag_end) ) 
520                                 continue;
521                         if (strncasecmp(rel, rel_start, repllen)!= 0)
522                                 continue; /* didn't match? never mind... */
523                         
524                         href_start = cbmstrcasestr(link_tag_start, "href=");
525                         if ((href_start == NULL) || 
526                             (href_start >= link_tag_end)) 
527                                 continue;
528                         href_start = strchr(href_start, '\"');
529                         if ((href_start == NULL) |
530                             (href_start >= link_tag_end)) 
531                                 continue;
532                         ++href_start;
533                         href_end = strchr(href_start, '\"');
534                         if ((href_end == NULL) || 
535                             (href_end == href_start) ||
536                             (href_start >= link_tag_end)) 
537                                 continue;
538                         StrBufPlain(target_buf, href_start, href_end - href_start);
539                 }
540                 ptr = link_tag_end;     
541         }
542 }
543
544
545 /*
546  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
547  */
548 int fetch_http(StrBuf *url, StrBuf **target_buf)
549 {
550         StrBuf *ReplyBuf;
551         CURL *curl;
552         CURLcode res;
553         char errmsg[1024] = "";
554         char *effective_url = NULL;
555
556         if (StrLength(url) <=0 ) return(-1);
557         ReplyBuf = *target_buf = NewStrBuf ();
558         if (ReplyBuf == 0) return(-1);
559
560         curl = curl_easy_init();
561         if (!curl) {
562                 syslog(LOG_ALERT, "Unable to initialize libcurl.");
563                 return(-1);
564         }
565
566         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(url));
567         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
568         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
569
570         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
571         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
572
573         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
574         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
575 #ifdef CURLOPT_HTTP_CONTENT_DECODING
576         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
577         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
578 #endif
579         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
580         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
581         if (
582                 (!IsEmptyStr(config.c_ip_addr))
583                 && (strcmp(config.c_ip_addr, "*"))
584                 && (strcmp(config.c_ip_addr, "::"))
585                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
586         ) {
587                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
588         }
589         res = curl_easy_perform(curl);
590         if (res) {
591                 syslog(LOG_DEBUG, "libcurl error %d: %s", res, errmsg);
592         }
593         curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
594         StrBufPlain(url, effective_url, -1);
595         
596         curl_easy_cleanup(curl);
597         return StrLength(ReplyBuf);
598 }
599
600
601 /*
602  * Attempt to perform YADIS discovery.
603  * If successful, returns nonzero and fills the session's claimed ID blah FIXME this comment
604  * If YADIS fails, returns 0 and does nothing else.
605  */
606 int perform_yadis_discovery(StrBuf *YadisURL) {
607         int docbytes = (-1);
608         StrBuf *ReplyBuf = NULL;
609
610         docbytes = fetch_http(YadisURL, &ReplyBuf);
611         if (docbytes < 0) {
612                 return(0);
613         }
614         if (docbytes == 0) {
615                 FreeStrBuf(&ReplyBuf);
616                 return(0);
617         }
618
619         /* ok we have something here.  is it an XRDS document? */
620
621         /* FIXME finish this */
622
623         FreeStrBuf(&ReplyBuf);
624         return(0);
625 }
626
627
628 /*
629  * Setup an OpenID authentication
630  */
631 void cmd_oids(char *argbuf) {
632         const char *Pos = NULL;
633         StrBuf *ArgBuf = NULL;
634         StrBuf *ReplyBuf = NULL;
635         StrBuf *return_to = NULL;
636         StrBuf *trust_root = NULL;
637         StrBuf *openid_delegate = NULL;
638         StrBuf *RedirectUrl = NULL;
639         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
640         ctdl_openid *oiddata;
641
642         Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
643
644         CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
645         if (oiddata == NULL) {
646                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
647                 return;
648         }
649         memset(oiddata, 0, sizeof(ctdl_openid));
650         CCC->openid_data = (void *) oiddata;
651
652         ArgBuf = NewStrBufPlain(argbuf, -1);
653
654         oiddata->verified = 0;
655         oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
656         trust_root = NewStrBufPlain(NULL, StrLength(ArgBuf));
657         return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
658
659         StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
660         StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
661         StrBufExtract_NextToken(trust_root, ArgBuf, &Pos, '|');
662
663         syslog(LOG_DEBUG, "User-Supplied Identifier is: %s", ChrPtr(oiddata->claimed_id));
664
665
666         /********** OpenID 2.0 section 7.3 - Discovery **********/
667
668         /* First we're supposed to attempt XRI.  What the fuck is XRI and why do I care about it? */
669
670         /* Second we attempt YADIS.  Google uses this so we'd better do our best to implement it. */
671         int yadis_succeeded = perform_yadis_discovery(oiddata->claimed_id);
672
673         /* Third we attempt HTML-based discovery.  Here we go! */
674         if (    (yadis_succeeded == 0)
675                 && (fetch_http(oiddata->claimed_id, &ReplyBuf) > 0)
676                 && (StrLength(ReplyBuf) > 0)
677         ) {
678                 openid_delegate = NewStrBuf();
679                 oiddata->server = NewStrBuf();
680                 extract_link(oiddata->server, HKEY("openid.server"), ReplyBuf);
681                 extract_link(openid_delegate, HKEY("openid.delegate"), ReplyBuf);
682
683                 if (StrLength(oiddata->server) == 0) {
684                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
685                         FreeStrBuf(&ArgBuf);
686                         FreeStrBuf(&ReplyBuf);
687                         FreeStrBuf(&return_to);
688                         FreeStrBuf(&trust_root);
689                         FreeStrBuf(&openid_delegate);
690                         FreeStrBuf(&RedirectUrl);
691                         return;
692                 }
693
694                 /* Empty delegate is legal; we just use the openid_url instead */
695                 if (StrLength(openid_delegate) == 0) {
696                         StrBufPlain(openid_delegate, SKEY(oiddata->claimed_id));
697                 }
698
699                 /* Assemble a URL to which the user-agent will be redirected. */
700
701                 RedirectUrl = NewStrBufDup(oiddata->server);
702
703                 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.mode=checkid_setup"
704                                                        "&openid.identity="), 0);
705                 StrBufUrlescAppend(RedirectUrl, openid_delegate, NULL);
706
707                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
708                 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
709
710                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.trust_root="), 0);
711                 StrBufUrlescAppend(RedirectUrl, trust_root, NULL);
712
713                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.sreg.optional="), 0);
714                 StrBufUrlescAppend(RedirectUrl, NULL, "nickname,email,fullname,postcode,country,dob,gender");
715
716                 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
717                 
718                 FreeStrBuf(&ArgBuf);
719                 FreeStrBuf(&ReplyBuf);
720                 FreeStrBuf(&return_to);
721                 FreeStrBuf(&trust_root);
722                 FreeStrBuf(&openid_delegate);
723                 FreeStrBuf(&RedirectUrl);
724
725                 return;
726         }
727
728         FreeStrBuf(&ArgBuf);
729         FreeStrBuf(&ReplyBuf);
730         FreeStrBuf(&return_to);
731         FreeStrBuf(&trust_root);
732         FreeStrBuf(&openid_delegate);
733         FreeStrBuf(&RedirectUrl);
734
735         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
736 }
737
738
739
740
741
742 /*
743  * Finalize an OpenID authentication
744  */
745 void cmd_oidf(char *argbuf) {
746         long len;
747         char buf[2048];
748         char thiskey[1024];
749         char thisdata[1024];
750         HashList *keys = NULL;
751         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
752
753         if (oiddata == NULL) {
754                 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
755                 return;
756         }
757         if (StrLength(oiddata->server) == 0){
758                 cprintf("%d need a remote server to authenticate against\n", ERROR + ILLEGAL_VALUE);
759                 return;
760         }
761         keys = NewHash(1, NULL);
762         if (!keys) {
763                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
764                 return;
765         }
766         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
767
768         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
769                 len = extract_token(thiskey, buf, 0, '|', sizeof thiskey);
770                 if (len < 0)
771                         len = sizeof(thiskey) - 1;
772                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
773                 syslog(LOG_DEBUG, "%s: ["SIZE_T_FMT"] %s", thiskey, strlen(thisdata), thisdata);
774                 Put(keys, thiskey, len, strdup(thisdata), NULL);
775         }
776
777
778         /* Now that we have all of the parameters, we have to validate the signature against the server */
779         syslog(LOG_DEBUG, "About to validate the signature...");
780
781         CURL *curl;
782         CURLcode res;
783         struct curl_httppost *formpost = NULL;
784         struct curl_httppost *lastptr = NULL;
785         char errmsg[1024] = "";
786         char *o_assoc_handle = NULL;
787         char *o_sig = NULL;
788         char *o_signed = NULL;
789         int num_signed_values;
790         int i;
791         char k_keyname[128];
792         char k_o_keyname[128];
793         char *k_value = NULL;
794         StrBuf *ReplyBuf;
795
796         curl_formadd(&formpost, &lastptr,
797                 CURLFORM_COPYNAME,      "openid.mode",
798                 CURLFORM_COPYCONTENTS,  "check_authentication",
799                 CURLFORM_END);
800         syslog(LOG_DEBUG, "%25s : %s", "openid.mode", "check_authentication");
801
802         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
803                 curl_formadd(&formpost, &lastptr,
804                         CURLFORM_COPYNAME,      "openid.assoc_handle",
805                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
806                         CURLFORM_END);
807                 syslog(LOG_DEBUG, "%25s : %s", "openid.assoc_handle", o_assoc_handle);
808         }
809
810         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
811                 curl_formadd(&formpost, &lastptr,
812                         CURLFORM_COPYNAME,      "openid.sig",
813                         CURLFORM_COPYCONTENTS,  o_sig,
814                         CURLFORM_END);
815                         syslog(LOG_DEBUG, "%25s : %s", "openid.sig", o_sig);
816         }
817
818         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
819                 curl_formadd(&formpost, &lastptr,
820                         CURLFORM_COPYNAME,      "openid.signed",
821                         CURLFORM_COPYCONTENTS,  o_signed,
822                         CURLFORM_END);
823                 syslog(LOG_DEBUG, "%25s : %s", "openid.signed", o_signed);
824
825                 num_signed_values = num_tokens(o_signed, ',');
826                 for (i=0; i<num_signed_values; ++i) {
827                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
828                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
829                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
830                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
831                                         curl_formadd(&formpost, &lastptr,
832                                                 CURLFORM_COPYNAME,      k_o_keyname,
833                                                 CURLFORM_COPYCONTENTS,  k_value,
834                                                 CURLFORM_END);
835                                         syslog(LOG_DEBUG, "%25s : %s", k_o_keyname, k_value);
836                                 }
837                                 else {
838                                         syslog(LOG_INFO, "OpenID: signed field '%s' is missing",
839                                                 k_keyname);
840                                 }
841                         }
842                 }
843         }
844         
845         ReplyBuf = NewStrBuf();
846
847         curl = curl_easy_init();
848         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->server));
849         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
850         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
851
852         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
853         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
854         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
855         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
856         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
857 #ifdef CURLOPT_HTTP_CONTENT_DECODING
858         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
859         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
860 #endif
861         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
862         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
863         if (
864                 (!IsEmptyStr(config.c_ip_addr))
865                 && (strcmp(config.c_ip_addr, "*"))
866                 && (strcmp(config.c_ip_addr, "::"))
867                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
868         ) {
869                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
870         }
871
872         res = curl_easy_perform(curl);
873         if (res) {
874                 syslog(LOG_DEBUG, "cmd_oidf() libcurl error %d: %s", res, errmsg);
875         }
876         curl_easy_cleanup(curl);
877         curl_formfree(formpost);
878
879         if (cbmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true")) {
880                 oiddata->verified = 1;
881         }
882         FreeStrBuf(&ReplyBuf);
883
884         syslog(LOG_DEBUG, "Authentication %s.", (oiddata->verified ? "succeeded" : "failed") );
885
886         /* Respond to the client */
887
888         if (oiddata->verified) {
889
890                 /* If we were already logged in, attach the OpenID to the user's account */
891                 if (CC->logged_in) {
892                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
893                                 cprintf("attach\n");
894                                 syslog(LOG_DEBUG, "OpenID attach succeeded");
895                         }
896                         else {
897                                 cprintf("fail\n");
898                                 syslog(LOG_DEBUG, "OpenID attach failed");
899                         }
900                 }
901
902                 /* Otherwise, a user is attempting to log in using the verified OpenID */       
903                 else {
904                         /*
905                          * Existing user who has claimed this OpenID?
906                          *
907                          * Note: if you think that sending the password back over the wire is insecure,
908                          * check your assumptions.  If someone has successfully asserted an OpenID that
909                          * is associated with the account, they already have password equivalency and can
910                          * login, so they could just as easily change the password, etc.
911                          */
912                         if (login_via_openid(oiddata->claimed_id) == 0) {
913                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
914                                 logged_in_response();
915                                 syslog(LOG_DEBUG, "Logged in using previously claimed OpenID");
916                         }
917
918                         /*
919                          * If this system does not allow self-service new user registration, the
920                          * remaining modes do not apply, so fail here and now.
921                          */
922                         else if (config.c_disable_newu) {
923                                 cprintf("fail\n");
924                                 syslog(LOG_DEBUG, "Creating user failed due to local policy");
925                         }
926
927                         /*
928                          * New user whose OpenID is verified and Simple Registration Extension is in use?
929                          */
930                         else if (openid_create_user_via_sreg(oiddata->claimed_id, keys) == 0) {
931                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
932                                 logged_in_response();
933                                 syslog(LOG_DEBUG, "Successfully auto-created new user");
934                         }
935
936                         /*
937                          * OpenID is verified, but the desired username either was not specified or
938                          * conflicts with an existing user.  Manual account creation is required.
939                          */
940                         else {
941                                 char *desired_name = NULL;
942                                 cprintf("verify_only\n");
943                                 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
944                                 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
945                                         cprintf("%s\n", desired_name);
946                                 }
947                                 else {
948                                         cprintf("\n");
949                                 }
950                                 syslog(LOG_DEBUG, "The desired Simple Registration name is already taken.");
951                         }
952                 }
953         }
954         else {
955                 cprintf("fail\n");
956         }
957         cprintf("000\n");
958
959         if (oiddata->sreg_keys != NULL) {
960                 DeleteHash(&oiddata->sreg_keys);
961                 oiddata->sreg_keys = NULL;
962         }
963         oiddata->sreg_keys = keys;
964 }
965
966
967
968 /**************************************************************************/
969 /*                                                                        */
970 /* Functions in this section handle module initialization and shutdown    */
971 /*                                                                        */
972 /**************************************************************************/
973
974
975
976
977 CTDL_MODULE_INIT(openid_rp)
978 {
979         if (!threading) {
980                 curl_global_init(CURL_GLOBAL_ALL);
981
982                 /* Only enable the OpenID command set when native mode authentication is in use. */
983                 if (config.c_auth_mode == AUTHMODE_NATIVE) {
984                         CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
985                         CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
986                         CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
987                         CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
988                         CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
989                         CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
990                 }
991                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
992                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
993                 openid_level_supported = 1;     /* This module supports OpenID 1.0 only */
994         }
995
996         /* return our module name for the log */
997         return "openid_rp";
998 }