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