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