Success! We can now log in an existing user with OpenID.
[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  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <pwd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #include <sys/wait.h>
30 #include <string.h>
31 #include <limits.h>
32 #include <curl/curl.h>
33 #include "ctdl_module.h"
34 #include "config.h"
35 #include "citserver.h"
36 #include "user_ops.h"
37
38 struct ctdl_openid {
39         char claimed_id[1024];
40         char server[1024];
41         int validated;
42 };
43
44
45
46
47
48 /**************************************************************************/
49 /*                                                                        */
50 /* Functions in this section handle Citadel internal OpenID mapping stuff */
51 /*                                                                        */
52 /**************************************************************************/
53
54
55 /*
56  * The structure of an openid record *key* is:
57  *
58  * |--------------claimed_id-------------|
59  *     (auctual length of claimed id)
60  *
61  *
62  * The structure of an openid record *value* is:
63  *
64  * |-----user_number----|------------claimed_id---------------|
65  *    (sizeof long)          (actual length of claimed id)
66  *
67  */
68
69
70 /*
71  * Attach an OpenID to a Citadel account
72  */
73 int attach_openid(struct ctdluser *who, char *claimed_id)
74 {
75         struct cdbdata *cdboi;
76         long fetched_usernum;
77         char *data;
78         int data_len;
79
80         if (!who) return(1);
81         if (!claimed_id) return(1);
82         if (IsEmptyStr(claimed_id)) return(1);
83
84         /* Check to see if this OpenID is already in the database */
85
86         cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
87         if (cdboi != NULL) {
88                 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
89                 cdb_free(cdboi);
90
91                 if (fetched_usernum == who->usernum) {
92                         CtdlLogPrintf(CTDL_INFO, "%s already associated; no action is taken\n", claimed_id);
93                         return(0);
94                 }
95                 else {
96                         CtdlLogPrintf(CTDL_INFO, "%s already belongs to another user\n", claimed_id);
97                         return(3);
98                 }
99         }
100
101         /* Not already in the database, so attach it now */
102
103         data_len = sizeof(long) + strlen(claimed_id) + 1;
104         data = malloc(data_len);
105
106         memcpy(data, &who->usernum, sizeof(long));
107         memcpy(&data[sizeof(long)], claimed_id, strlen(claimed_id) + 1);
108
109         cdb_store(CDB_OPENID, claimed_id, strlen(claimed_id), data, data_len);
110         free(data);
111
112         CtdlLogPrintf(CTDL_INFO, "%s has been associated with %s (%ld)\n",
113                 claimed_id, who->fullname, who->usernum);
114         return(0);
115 }
116
117
118 /*
119  * When a user is being deleted, we have to delete any OpenID associations
120  */
121 void openid_purge(struct ctdluser *usbuf) {
122         /* FIXME finish this */
123 }
124
125
126
127 /*
128  * List the OpenIDs associated with the currently logged in account
129  */
130 void cmd_oidl(char *argbuf) {
131         struct cdbdata *cdboi;
132
133         if (CtdlAccessCheck(ac_logged_in)) return;
134         cdb_rewind(CDB_OPENID);
135         cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
136
137         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
138                 if (cdboi->len > sizeof(long)) {
139                 cprintf("%s\n", cdboi->ptr + sizeof(long));
140                 }
141         }
142         cprintf("000\n");
143 }
144
145
146
147 /*
148  * getuserbyopenid() works the same way as getuser() and getuserbynumber().
149  * If a user account exists which is associated with the Claimed ID, it fills usbuf and returns zero.
150  * Otherwise it returns nonzero.
151  */
152 int getuserbyopenid(struct ctdluser *usbuf, char *claimed_id)
153 {
154         struct cdbdata *cdboi;
155         long usernum = 0;
156
157         cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
158         if (cdboi == NULL) {
159                 return(-1);
160         }
161
162         memcpy(&usernum, cdboi->ptr, sizeof(long));
163         cdb_free(cdboi);
164
165         return(getuserbynumber(usbuf, usernum));
166 }
167
168
169
170 /**************************************************************************/
171 /*                                                                        */
172 /* Functions in this section handle OpenID protocol                       */
173 /*                                                                        */
174 /**************************************************************************/
175
176
177 /* 
178  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
179  */
180 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
181 {
182         char *ptr = source_buf;
183
184         if (!target_buf) return;
185         if (!rel) return;
186         if (!source_buf) return;
187
188         target_buf[0] = 0;
189
190         while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
191
192                 char work_buffer[2048];
193                 char *link_tag_start = NULL;
194                 char *link_tag_end = NULL;
195
196                 char rel_tag[2048];
197                 char href_tag[2048];
198
199                 link_tag_start = ptr;
200                 link_tag_end = strchr(ptr, '>');
201                 rel_tag[0] = 0;
202                 href_tag[0] = 0;
203
204                 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
205                         int len;
206                         len = link_tag_end - link_tag_start;
207                         if (len > sizeof work_buffer) len = sizeof work_buffer;
208                         memcpy(work_buffer, link_tag_start, len);
209                 
210                         char *rel_start = NULL;
211                         char *rel_end = NULL;
212                         rel_start = bmstrcasestr(work_buffer, "rel=");
213                         if (rel_start) {
214                                 rel_start = strchr(rel_start, '\"');
215                                 if (rel_start) {
216                                         ++rel_start;
217                                         rel_end = strchr(rel_start, '\"');
218                                         if ((rel_end) && (rel_end > rel_start)) {
219                                                 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
220                                         }
221                                 }
222                         }
223
224                         char *href_start = NULL;
225                         char *href_end = NULL;
226                         href_start = bmstrcasestr(work_buffer, "href=");
227                         if (href_start) {
228                                 href_start = strchr(href_start, '\"');
229                                 if (href_start) {
230                                         ++href_start;
231                                         href_end = strchr(href_start, '\"');
232                                         if ((href_end) && (href_end > href_start)) {
233                                                 safestrncpy(href_tag, href_start, href_end - href_start + 1);
234                                         }
235                                 }
236                         }
237
238                         if (!strcasecmp(rel, rel_tag)) {
239                                 safestrncpy(target_buf, href_tag, target_size);
240                                 return;
241                         }
242
243                 }
244
245         ++ptr;
246         }
247
248
249 }
250
251
252
253 struct fh_data {
254         char *buf;
255         int total_bytes_received;
256         int maxbytes;
257 };
258
259
260 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
261 {
262         struct fh_data *fh = (struct fh_data *) stream;
263         int got_bytes = (size * nmemb);
264
265         if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
266                 got_bytes = fh->maxbytes - fh->total_bytes_received;
267         }
268         if (got_bytes > 0) {
269                 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
270                 fh->total_bytes_received += got_bytes;
271         }
272
273         return (size * nmemb);  /* always succeed; libcurl doesn't need to know if we truncated it */
274 }
275
276
277
278 /*
279  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
280  *
281  * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
282  * requesting that the effective (normalized) URL be copied back to it.
283  */
284 int fetch_http(char *url, char *target_buf, int maxbytes, int normalize_len)
285 {
286         CURL *curl;
287         CURLcode res;
288         char errmsg[1024] = "";
289         struct fh_data fh = {
290                 target_buf,
291                 0,
292                 maxbytes
293         };
294         char *effective_url = NULL;
295
296         if (!url) return(-1);
297         if (!target_buf) return(-1);
298         memset(target_buf, 0, maxbytes);
299
300         curl = curl_easy_init();
301         if (!curl) {
302                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
303                 return(-1);
304         }
305
306         curl_easy_setopt(curl, CURLOPT_URL, url);
307         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
308         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
309         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
310         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
311         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
312         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
313         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
314         if (!IsEmptyStr(config.c_ip_addr)) {
315                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
316         }
317         res = curl_easy_perform(curl);
318         if (res) {
319                 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
320         }
321         if (normalize_len > 0) {
322                 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
323                 safestrncpy(url, effective_url, normalize_len);
324         }
325         curl_easy_cleanup(curl);
326         return fh.total_bytes_received;
327 }
328
329
330 /*
331  * Setup an OpenID authentication
332  */
333 void cmd_oids(char *argbuf) {
334         char return_to[1024];
335         char trust_root[1024];
336         int i;
337         char buf[SIZ];
338         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
339         struct ctdl_openid *oiddata;
340
341         /* commented out because we may be attempting to attach an OpenID to
342          * an existing account that is logged in
343          *
344         if (CCC->logged_in) {
345                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
346                 return;
347         }
348          */
349
350         if (CCC->openid_data != NULL) {
351                 free(CCC->openid_data);
352         }
353         oiddata = malloc(sizeof(struct ctdl_openid));
354         if (oiddata == NULL) {
355                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
356                 return;
357         }
358         memset(oiddata, 0, sizeof(struct ctdl_openid));
359         CCC->openid_data = (void *) oiddata;
360
361         extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
362         extract_token(return_to, argbuf, 1, '|', sizeof return_to);
363         extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
364         oiddata->validated = 0;
365
366         i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1, sizeof oiddata->claimed_id);
367         CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", oiddata->claimed_id);
368         buf[sizeof buf - 1] = 0;
369         if (i > 0) {
370                 char openid_delegate[1024];
371
372                 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
373                 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
374
375                 if (IsEmptyStr(oiddata->server)) {
376                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
377                         return;
378                 }
379
380                 /* Empty delegate is legal; we just use the openid_url instead */
381                 if (IsEmptyStr(openid_delegate)) {
382                         safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
383                 }
384
385                 /* Assemble a URL to which the user-agent will be redirected. */
386                 char redirect_string[4096];
387                 char escaped_identity[512];
388                 char escaped_return_to[2048];
389                 char escaped_trust_root[1024];
390                 char escaped_sreg_optional[256];
391
392                 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
393                 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
394                 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
395                 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
396                         "nickname,email,fullname,postcode,country");
397
398                 snprintf(redirect_string, sizeof redirect_string,
399                         "%s"
400                         "?openid.mode=checkid_setup"
401                         "&openid.identity=%s"
402                         "&openid.return_to=%s"
403                         "&openid.trust_root=%s"
404                         "&openid.sreg.optional=%s"
405                         ,
406                         oiddata->server,
407                         escaped_identity,
408                         escaped_return_to,
409                         escaped_trust_root,
410                         escaped_sreg_optional
411                 );
412                 cprintf("%d %s\n", CIT_OK, redirect_string);
413                 return;
414         }
415
416         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
417 }
418
419
420
421 /*
422  * Callback function to free a pointer (used below in the hash list)
423  */
424 void free_oid_key(void *ptr) {
425         free(ptr);
426 }
427
428
429 /*
430  * Finalize an OpenID authentication
431  */
432 void cmd_oidf(char *argbuf) {
433         char buf[2048];
434         char thiskey[1024];
435         char thisdata[1024];
436         HashList *keys = NULL;
437         HashPos *HashPos;
438         struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
439
440         keys = NewHash(1, NULL);
441         if (!keys) {
442                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
443                 return;
444         }
445         
446         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
447
448         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
449                 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
450                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
451                 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
452                 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), free_oid_key);
453         }
454
455
456         /* Now that we have all of the parameters, we have to validate the signature against the server */
457         CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
458
459         CURL *curl;
460         CURLcode res;
461         struct curl_httppost *formpost = NULL;
462         struct curl_httppost *lastptr = NULL;
463         char errmsg[1024] = "";
464         char *o_assoc_handle = NULL;
465         char *o_sig = NULL;
466         char *o_signed = NULL;
467         int num_signed_values;
468         int i;
469         char k_keyname[128];
470         char k_o_keyname[128];
471         char *k_value = NULL;
472         char valbuf[1024];
473
474         struct fh_data fh = {
475                 valbuf,
476                 0,
477                 sizeof valbuf
478         };
479
480         curl_formadd(&formpost, &lastptr,
481                 CURLFORM_COPYNAME,      "openid.mode",
482                 CURLFORM_COPYCONTENTS,  "check_authentication",
483                 CURLFORM_END);
484         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
485
486         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
487                 curl_formadd(&formpost, &lastptr,
488                         CURLFORM_COPYNAME,      "openid.assoc_handle",
489                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
490                         CURLFORM_END);
491                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
492         }
493
494         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
495                 curl_formadd(&formpost, &lastptr,
496                         CURLFORM_COPYNAME,      "openid.sig",
497                         CURLFORM_COPYCONTENTS,  o_sig,
498                         CURLFORM_END);
499                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
500         }
501
502         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
503                 curl_formadd(&formpost, &lastptr,
504                         CURLFORM_COPYNAME,      "openid.signed",
505                         CURLFORM_COPYCONTENTS,  o_signed,
506                         CURLFORM_END);
507                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
508
509                 num_signed_values = num_tokens(o_signed, ',');
510                 for (i=0; i<num_signed_values; ++i) {
511                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
512                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
513                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
514                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
515                                         curl_formadd(&formpost, &lastptr,
516                                                 CURLFORM_COPYNAME,      k_o_keyname,
517                                                 CURLFORM_COPYCONTENTS,  k_value,
518                                                 CURLFORM_END);
519                                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
520                                 }
521                                 else {
522                                         CtdlLogPrintf(CTDL_INFO, "OpenID: signed field '%s' is missing\n",
523                                                 k_keyname);
524                                 }
525                         }
526                 }
527         }
528
529         curl = curl_easy_init();
530         curl_easy_setopt(curl, CURLOPT_URL, oiddata->server);
531         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
532         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
533         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
534         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
535         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
536         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
537         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
538         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
539         if (!IsEmptyStr(config.c_ip_addr)) {
540                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
541         }
542
543         res = curl_easy_perform(curl);
544         if (res) {
545                 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
546         }
547         curl_easy_cleanup(curl);
548         curl_formfree(formpost);
549
550         valbuf[fh.total_bytes_received] = 0;
551
552         if (bmstrcasestr(valbuf, "is_valid:true")) {
553                 oiddata->validated = 1;
554         }
555
556         CtdlLogPrintf(CTDL_DEBUG, "Authentication %s.\n", (oiddata->validated ? "succeeded" : "failed") );
557
558         /* Respond to the client */
559
560         if (oiddata->validated) {
561
562                 /* If we were already logged in, attach the OpenID to the user's account */
563                 if (CC->logged_in) {
564                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
565                                 cprintf("attach\n");
566                         }
567                         else {
568                                 cprintf("fail\n");
569                         }
570                 }
571
572                 /* Otherwise, a user is attempting to log in using the validated OpenID */      
573                 else {
574                         struct ctdluser usbuf;
575
576                         /*
577                          * Existing user who has claimed this OpenID?
578                          *
579                          * Note: if you think that sending the password back over the wire is insecure,
580                          * check your assumptions.  If someone has successfully asserted an OpenID that
581                          * is associated with the account, they already have password equivalency and can
582                          * login, so they could just as easily change the password, etc.
583                          */
584                         if (getuserbyopenid(&usbuf, oiddata->claimed_id) == 0) {
585                                 cprintf("authenticate\n%s\n%s\n", usbuf.fullname, usbuf.password);
586                         }
587
588                         else {
589                                 cprintf("fail\n");              // FIXME do the login here!!
590                         }
591                 }
592         }
593         else {
594                 cprintf("fail\n");
595         }
596         cprintf("000\n");
597
598         /* Free the hash list */
599         long len;
600         void *Value;
601         char *Key;
602
603         HashPos = GetNewHashPos();
604         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
605         {
606                 free(Value);
607         }
608         DeleteHashPos(&HashPos);
609 }
610
611
612 // mode = [6]  id_res
613 // identity = [50]  http://uncensored.citadel.org/~ajc/MyID.config.php
614 // assoc_handle = [26]  6ekac3ju181tgepk7v4h9r7ui7
615 // return_to = [42]  http://jemcaterers.net/finish_openid_login
616 // sreg.nickname = [17]  IGnatius T Foobar
617 // sreg.email = [26]  ajc@uncensored.citadel.org
618 // sreg.fullname = [10]  Art Cancro
619 // sreg.postcode = [5]  10549
620 // sreg.country = [2]  US
621 // signed = [102]  mode,identity,assoc_handle,return_to,sreg.nickname,sreg.email,sreg.fullname,sreg.postcode,sreg.country
622 // sig = [28]  vixxxU4MAqWfxxxxCfrHv3TxxxhEw=
623
624
625
626
627 /**************************************************************************/
628 /*                                                                        */
629 /* Functions in this section handle module initialization and shutdown    */
630 /*                                                                        */
631 /**************************************************************************/
632
633
634 /*
635  * This cleanup function blows away the temporary memory used by this module.
636  */
637 void openid_cleanup_function(void) {
638
639         if (CC->openid_data != NULL) {
640                 free(CC->openid_data);
641         }
642 }
643
644
645 CTDL_MODULE_INIT(openid_rp)
646 {
647         if (!threading)
648         {
649                 curl_global_init(CURL_GLOBAL_ALL);
650                 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
651                 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
652                 CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
653                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_STOP);
654                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
655         }
656
657         /* return our Subversion id for the Log */
658         return "$Id$";
659 }
660
661
662 /* FIXME ... we have to add the new openid database to serv_vandelay.c */
663