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