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