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