Fix warnings all over citserver; handle function replies; remove unused code.
[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 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                         rel_start = cbmstrcasestr(link_tag_start, "rel=");
512                         if ((rel_start == NULL) ||
513                             (rel_start > link_tag_end)) 
514                                 continue;
515
516                         rel_start = strchr(rel_start, '\"');
517                         if ((rel_start == NULL) ||
518                             (rel_start > link_tag_end)) 
519                                 continue;
520                         ++rel_start;
521                         rel_end = strchr(rel_start, '\"');
522                         if ((rel_end == NULL) ||
523                             (rel_end == rel_start) ||
524                             (rel_end >= link_tag_end) ) 
525                                 continue;
526                         if (strncasecmp(rel, rel_start, repllen)!= 0)
527                                 continue; /* didn't match? never mind... */
528                         
529                         href_start = cbmstrcasestr(link_tag_start, "href=");
530                         if ((href_start == NULL) || 
531                             (href_start >= link_tag_end)) 
532                                 continue;
533                         href_start = strchr(href_start, '\"');
534                         if ((href_start == NULL) |
535                             (href_start >= link_tag_end)) 
536                                 continue;
537                         ++href_start;
538                         href_end = strchr(href_start, '\"');
539                         if ((href_end == NULL) || 
540                             (href_end == href_start) ||
541                             (href_start >= link_tag_end)) 
542                                 continue;
543                         StrBufPlain(target_buf, href_start, href_end - href_start);
544                 }
545                 ptr = link_tag_end;     
546         }
547 }
548
549
550 /*
551  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
552  *
553  * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
554  * requesting that the effective (normalized) URL be copied back to it.
555  */
556 int fetch_http(StrBuf *url, StrBuf **target_buf)
557 {
558         StrBuf *ReplyBuf;
559         CURL *curl;
560         CURLcode res;
561         char errmsg[1024] = "";
562         char *effective_url = NULL;
563
564         if (StrLength(url) <=0 ) return(-1);
565         ReplyBuf = *target_buf = NewStrBuf ();
566         if (ReplyBuf == 0) return(-1);
567
568         curl = curl_easy_init();
569         if (!curl) {
570                 syslog(LOG_ALERT, "Unable to initialize libcurl.\n");
571                 return(-1);
572         }
573
574         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(url));
575         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
576         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
577
578         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
579         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
580
581         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
582         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
583 #ifdef CURLOPT_HTTP_CONTENT_DECODING
584         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
585         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
586 #endif
587         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
588         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
589         if (
590                 (!IsEmptyStr(config.c_ip_addr))
591                 && (strcmp(config.c_ip_addr, "*"))
592                 && (strcmp(config.c_ip_addr, "::"))
593                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
594         ) {
595                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
596         }
597         res = curl_easy_perform(curl);
598         if (res) {
599                 syslog(LOG_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
600         }
601         curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
602         StrBufPlain(url, effective_url, -1);
603         
604         curl_easy_cleanup(curl);
605         return StrLength(ReplyBuf);
606 }
607
608
609 /*
610  * Setup an OpenID authentication
611  */
612 void cmd_oids(char *argbuf) {
613         const char *Pos = NULL;
614         StrBuf *ArgBuf = NULL;
615         StrBuf *ReplyBuf = NULL;
616         StrBuf *return_to = NULL;
617         StrBuf *trust_root = NULL;
618         StrBuf *openid_delegate = NULL;
619         StrBuf *RedirectUrl = NULL;
620         int i;
621         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
622         ctdl_openid *oiddata;
623
624         Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
625
626         CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
627         if (oiddata == NULL) {
628                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
629                 return;
630         }
631         memset(oiddata, 0, sizeof(ctdl_openid));
632         CCC->openid_data = (void *) oiddata;
633
634         ArgBuf = NewStrBufPlain(argbuf, -1);
635
636         oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
637         trust_root = NewStrBufPlain(NULL, StrLength(ArgBuf));
638         return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
639
640         StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
641         StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
642         StrBufExtract_NextToken(trust_root, ArgBuf, &Pos, '|');
643         
644         oiddata->verified = 0;
645
646         i = fetch_http(oiddata->claimed_id, &ReplyBuf);
647         syslog(LOG_DEBUG, "Normalized URL and Claimed ID is: %s\n", 
648                       ChrPtr(oiddata->claimed_id));
649         if ((StrLength(ReplyBuf) > 0) && (i > 0)) {
650
651                 openid_delegate = NewStrBuf();
652                 oiddata->server = NewStrBuf();
653                 extract_link(oiddata->server, HKEY("openid.server"), ReplyBuf);
654                 extract_link(openid_delegate, HKEY("openid.delegate"), ReplyBuf);
655
656                 if (StrLength(oiddata->server) == 0) {
657                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
658                         FreeStrBuf(&ArgBuf);
659                         FreeStrBuf(&ReplyBuf);
660                         FreeStrBuf(&return_to);
661                         FreeStrBuf(&trust_root);
662                         FreeStrBuf(&openid_delegate);
663                         FreeStrBuf(&RedirectUrl);
664                         return;
665                 }
666
667                 /* Empty delegate is legal; we just use the openid_url instead */
668                 if (StrLength(openid_delegate) == 0) {
669                         StrBufPlain(openid_delegate, SKEY(oiddata->claimed_id));
670                 }
671
672                 /* Assemble a URL to which the user-agent will be redirected. */
673
674                 RedirectUrl = NewStrBufDup(oiddata->server);
675
676                 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.mode=checkid_setup"
677                                                        "&openid.identity="), 0);
678                 StrBufUrlescAppend(RedirectUrl, openid_delegate, NULL);
679
680                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
681                 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
682
683                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.trust_root="), 0);
684                 StrBufUrlescAppend(RedirectUrl, trust_root, NULL);
685
686                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.sreg.optional="), 0);
687                 StrBufUrlescAppend(RedirectUrl, NULL, "nickname,email,fullname,postcode,country,dob,gender");
688
689                 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
690                 
691                 FreeStrBuf(&ArgBuf);
692                 FreeStrBuf(&ReplyBuf);
693                 FreeStrBuf(&return_to);
694                 FreeStrBuf(&trust_root);
695                 FreeStrBuf(&openid_delegate);
696                 FreeStrBuf(&RedirectUrl);
697
698                 return;
699         }
700         FreeStrBuf(&ArgBuf);
701         FreeStrBuf(&ReplyBuf);
702         FreeStrBuf(&return_to);
703         FreeStrBuf(&trust_root);
704         FreeStrBuf(&openid_delegate);
705         FreeStrBuf(&RedirectUrl);
706
707         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
708 }
709
710
711
712
713
714 /*
715  * Finalize an OpenID authentication
716  */
717 void cmd_oidf(char *argbuf) {
718         long len;
719         char buf[2048];
720         char thiskey[1024];
721         char thisdata[1024];
722         HashList *keys = NULL;
723         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
724
725         if (oiddata == NULL) {
726                 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
727                 return;
728         }
729         if (StrLength(oiddata->server) == 0){
730                 cprintf("%d need a remote server to authenticate against\n", ERROR + ILLEGAL_VALUE);
731                 return;
732         }
733         keys = NewHash(1, NULL);
734         if (!keys) {
735                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
736                 return;
737         }
738         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
739
740         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
741                 len = extract_token(thiskey, buf, 0, '|', sizeof thiskey);
742                 if (len < 0)
743                         len = sizeof(thiskey) - 1;
744                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
745                 syslog(LOG_DEBUG, "%s: ["SIZE_T_FMT"] %s\n", thiskey, strlen(thisdata), thisdata);
746                 Put(keys, thiskey, len, strdup(thisdata), NULL);
747         }
748
749
750         /* Now that we have all of the parameters, we have to validate the signature against the server */
751         syslog(LOG_DEBUG, "About to validate the signature...\n");
752
753         CURL *curl;
754         CURLcode res;
755         struct curl_httppost *formpost = NULL;
756         struct curl_httppost *lastptr = NULL;
757         char errmsg[1024] = "";
758         char *o_assoc_handle = NULL;
759         char *o_sig = NULL;
760         char *o_signed = NULL;
761         int num_signed_values;
762         int i;
763         char k_keyname[128];
764         char k_o_keyname[128];
765         char *k_value = NULL;
766         StrBuf *ReplyBuf;
767
768         curl_formadd(&formpost, &lastptr,
769                 CURLFORM_COPYNAME,      "openid.mode",
770                 CURLFORM_COPYCONTENTS,  "check_authentication",
771                 CURLFORM_END);
772         syslog(LOG_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
773
774         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
775                 curl_formadd(&formpost, &lastptr,
776                         CURLFORM_COPYNAME,      "openid.assoc_handle",
777                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
778                         CURLFORM_END);
779                 syslog(LOG_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
780         }
781
782         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
783                 curl_formadd(&formpost, &lastptr,
784                         CURLFORM_COPYNAME,      "openid.sig",
785                         CURLFORM_COPYCONTENTS,  o_sig,
786                         CURLFORM_END);
787                         syslog(LOG_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
788         }
789
790         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
791                 curl_formadd(&formpost, &lastptr,
792                         CURLFORM_COPYNAME,      "openid.signed",
793                         CURLFORM_COPYCONTENTS,  o_signed,
794                         CURLFORM_END);
795                 syslog(LOG_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
796
797                 num_signed_values = num_tokens(o_signed, ',');
798                 for (i=0; i<num_signed_values; ++i) {
799                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
800                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
801                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
802                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
803                                         curl_formadd(&formpost, &lastptr,
804                                                 CURLFORM_COPYNAME,      k_o_keyname,
805                                                 CURLFORM_COPYCONTENTS,  k_value,
806                                                 CURLFORM_END);
807                                         syslog(LOG_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
808                                 }
809                                 else {
810                                         syslog(LOG_INFO, "OpenID: signed field '%s' is missing\n",
811                                                 k_keyname);
812                                 }
813                         }
814                 }
815         }
816         
817         ReplyBuf = NewStrBuf();
818
819         curl = curl_easy_init();
820         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->server));
821         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
822         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
823
824         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
825         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
826         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
827         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
828         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
829 #ifdef CURLOPT_HTTP_CONTENT_DECODING
830         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
831         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
832 #endif
833         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
834         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
835         if (
836                 (!IsEmptyStr(config.c_ip_addr))
837                 && (strcmp(config.c_ip_addr, "*"))
838                 && (strcmp(config.c_ip_addr, "::"))
839                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
840         ) {
841                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
842         }
843
844         res = curl_easy_perform(curl);
845         if (res) {
846                 syslog(LOG_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
847         }
848         curl_easy_cleanup(curl);
849         curl_formfree(formpost);
850
851         if (cbmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true")) {
852                 oiddata->verified = 1;
853         }
854         FreeStrBuf(&ReplyBuf);
855
856         syslog(LOG_DEBUG, "Authentication %s.\n", (oiddata->verified ? "succeeded" : "failed") );
857
858         /* Respond to the client */
859
860         if (oiddata->verified) {
861
862                 /* If we were already logged in, attach the OpenID to the user's account */
863                 if (CC->logged_in) {
864                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
865                                 cprintf("attach\n");
866                                 syslog(LOG_DEBUG, "OpenID attach succeeded\n");
867                         }
868                         else {
869                                 cprintf("fail\n");
870                                 syslog(LOG_DEBUG, "OpenID attach failed\n");
871                         }
872                 }
873
874                 /* Otherwise, a user is attempting to log in using the verified OpenID */       
875                 else {
876                         /*
877                          * Existing user who has claimed this OpenID?
878                          *
879                          * Note: if you think that sending the password back over the wire is insecure,
880                          * check your assumptions.  If someone has successfully asserted an OpenID that
881                          * is associated with the account, they already have password equivalency and can
882                          * login, so they could just as easily change the password, etc.
883                          */
884                         if (login_via_openid(oiddata->claimed_id) == 0) {
885                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
886                                 logged_in_response();
887                                 syslog(LOG_DEBUG, "Logged in using previously claimed OpenID\n");
888                         }
889
890                         /*
891                          * If this system does not allow self-service new user registration, the
892                          * remaining modes do not apply, so fail here and now.
893                          */
894                         else if (config.c_disable_newu) {
895                                 cprintf("fail\n");
896                                 syslog(LOG_DEBUG, "Creating user failed due to local policy\n");
897                         }
898
899                         /*
900                          * New user whose OpenID is verified and Simple Registration Extension is in use?
901                          */
902                         else if (openid_create_user_via_sreg(oiddata->claimed_id, keys) == 0) {
903                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
904                                 logged_in_response();
905                                 syslog(LOG_DEBUG, "Successfully auto-created new user\n");
906                         }
907
908                         /*
909                          * OpenID is verified, but the desired username either was not specified or
910                          * conflicts with an existing user.  Manual account creation is required.
911                          */
912                         else {
913                                 char *desired_name = NULL;
914                                 cprintf("verify_only\n");
915                                 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
916                                 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
917                                         cprintf("%s\n", desired_name);
918                                 }
919                                 else {
920                                         cprintf("\n");
921                                 }
922                                 syslog(LOG_DEBUG, "The desired Simple Registration name is already taken.\n");
923                         }
924                 }
925         }
926         else {
927                 cprintf("fail\n");
928         }
929         cprintf("000\n");
930
931         if (oiddata->sreg_keys != NULL) {
932                 DeleteHash(&oiddata->sreg_keys);
933                 oiddata->sreg_keys = NULL;
934         }
935         oiddata->sreg_keys = keys;
936 }
937
938
939
940 /**************************************************************************/
941 /*                                                                        */
942 /* Functions in this section handle module initialization and shutdown    */
943 /*                                                                        */
944 /**************************************************************************/
945
946
947
948
949 CTDL_MODULE_INIT(openid_rp)
950 {
951         if (!threading) {
952                 curl_global_init(CURL_GLOBAL_ALL);
953
954                 /* Only enable the OpenID command set when native mode authentication is in use. */
955                 if (config.c_auth_mode == AUTHMODE_NATIVE) {
956                         CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
957                         CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
958                         CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
959                         CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
960                         CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
961                         CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
962                 }
963                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
964                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
965                 openid_level_supported = 1;     /* This module supports OpenID 1.0 only */
966         }
967
968         /* return our module name for the log */
969         return "openid_rp";
970 }