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