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