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