4 * This is an implementation of OpenID 1.1 Relying Party support, in stateless mode.
16 #include <sys/types.h>
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
23 # include <sys/time.h>
32 #include <curl/curl.h>
33 #include "ctdl_module.h"
35 #include "citserver.h"
39 char claimed_id[1024];
48 /**************************************************************************/
50 /* Functions in this section handle Citadel internal OpenID mapping stuff */
52 /**************************************************************************/
56 * The structure of an openid record *key* is:
58 * |--------------claimed_id-------------|
59 * (auctual length of claimed id)
62 * The structure of an openid record *value* is:
64 * |-----user_number----|------------claimed_id---------------|
65 * (sizeof long) (actual length of claimed id)
71 * Attach an OpenID to a Citadel account
73 int attach_openid(struct ctdluser *who, char *claimed_id)
75 struct cdbdata *cdboi;
81 if (!claimed_id) return(1);
82 if (IsEmptyStr(claimed_id)) return(1);
84 /* Check to see if this OpenID is already in the database */
86 cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
88 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
91 if (fetched_usernum == who->usernum) {
92 CtdlLogPrintf(CTDL_INFO, "%s already associated; no action is taken\n", claimed_id);
96 CtdlLogPrintf(CTDL_INFO, "%s already belongs to another user\n", claimed_id);
101 /* Not already in the database, so attach it now */
103 data_len = sizeof(long) + strlen(claimed_id) + 1;
104 data = malloc(data_len);
106 memcpy(data, &who->usernum, sizeof(long));
107 memcpy(&data[sizeof(long)], claimed_id, strlen(claimed_id) + 1);
109 cdb_store(CDB_OPENID, claimed_id, strlen(claimed_id), data, data_len);
112 CtdlLogPrintf(CTDL_INFO, "%s has been associated with %s (%ld)\n",
113 claimed_id, who->fullname, who->usernum);
119 * When a user is being deleted, we have to delete any OpenID associations
121 void openid_purge(struct ctdluser *usbuf) {
122 /* FIXME finish this */
128 * List the OpenIDs associated with the currently logged in account
130 void cmd_oidl(char *argbuf) {
131 struct cdbdata *cdboi;
133 if (CtdlAccessCheck(ac_logged_in)) return;
134 cdb_rewind(CDB_OPENID);
135 cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
137 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
138 if (cdboi->len > sizeof(long)) {
139 if (((long)*(cdboi->ptr)) == CC->user.usernum) {
140 cprintf("%s\n", cdboi->ptr + sizeof(long));
150 * Detach an OpenID from the currently logged in account
152 void cmd_oidd(char *argbuf) {
153 struct cdbdata *cdboi;
154 char id_to_detach[1024];
155 int this_is_mine = 0;
157 if (CtdlAccessCheck(ac_logged_in)) return;
158 extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
159 if (IsEmptyStr(id_to_detach)) {
160 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
163 cdb_rewind(CDB_OPENID);
164 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
165 if (cdboi->len > sizeof(long)) {
166 if (((long)*(cdboi->ptr)) == CC->user.usernum) {
173 cprintf("%d That OpenID was not found or not associated with your account.\n",
174 ERROR + ILLEGAL_VALUE);
178 cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
179 cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
185 * getuserbyopenid() works the same way as getuser() and getuserbynumber().
186 * If a user account exists which is associated with the Claimed ID, it fills usbuf and returns zero.
187 * Otherwise it returns nonzero.
189 int getuserbyopenid(struct ctdluser *usbuf, char *claimed_id)
191 struct cdbdata *cdboi;
194 cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
199 memcpy(&usernum, cdboi->ptr, sizeof(long));
202 return(getuserbynumber(usbuf, usernum));
207 /**************************************************************************/
209 /* Functions in this section handle OpenID protocol */
211 /**************************************************************************/
215 * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
217 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
219 char *ptr = source_buf;
221 if (!target_buf) return;
223 if (!source_buf) return;
227 while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
229 char work_buffer[2048];
230 char *link_tag_start = NULL;
231 char *link_tag_end = NULL;
236 link_tag_start = ptr;
237 link_tag_end = strchr(ptr, '>');
241 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
243 len = link_tag_end - link_tag_start;
244 if (len > sizeof work_buffer) len = sizeof work_buffer;
245 memcpy(work_buffer, link_tag_start, len);
247 char *rel_start = NULL;
248 char *rel_end = NULL;
249 rel_start = bmstrcasestr(work_buffer, "rel=");
251 rel_start = strchr(rel_start, '\"');
254 rel_end = strchr(rel_start, '\"');
255 if ((rel_end) && (rel_end > rel_start)) {
256 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
261 char *href_start = NULL;
262 char *href_end = NULL;
263 href_start = bmstrcasestr(work_buffer, "href=");
265 href_start = strchr(href_start, '\"');
268 href_end = strchr(href_start, '\"');
269 if ((href_end) && (href_end > href_start)) {
270 safestrncpy(href_tag, href_start, href_end - href_start + 1);
275 if (!strcasecmp(rel, rel_tag)) {
276 safestrncpy(target_buf, href_tag, target_size);
292 int total_bytes_received;
297 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
299 struct fh_data *fh = (struct fh_data *) stream;
300 int got_bytes = (size * nmemb);
302 if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
303 got_bytes = fh->maxbytes - fh->total_bytes_received;
306 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
307 fh->total_bytes_received += got_bytes;
310 return (size * nmemb); /* always succeed; libcurl doesn't need to know if we truncated it */
316 * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
318 * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
319 * requesting that the effective (normalized) URL be copied back to it.
321 int fetch_http(char *url, char *target_buf, int maxbytes, int normalize_len)
325 char errmsg[1024] = "";
326 struct fh_data fh = {
331 char *effective_url = NULL;
333 if (!url) return(-1);
334 if (!target_buf) return(-1);
335 memset(target_buf, 0, maxbytes);
337 curl = curl_easy_init();
339 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
343 curl_easy_setopt(curl, CURLOPT_URL, url);
344 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
345 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
346 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
347 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
348 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
349 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
350 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
351 if (!IsEmptyStr(config.c_ip_addr)) {
352 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
354 res = curl_easy_perform(curl);
356 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
358 if (normalize_len > 0) {
359 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
360 safestrncpy(url, effective_url, normalize_len);
362 curl_easy_cleanup(curl);
363 return fh.total_bytes_received;
368 * Setup an OpenID authentication
370 void cmd_oids(char *argbuf) {
371 char return_to[1024];
372 char trust_root[1024];
375 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
376 struct ctdl_openid *oiddata;
378 /* commented out because we may be attempting to attach an OpenID to
379 * an existing account that is logged in
381 if (CCC->logged_in) {
382 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
387 if (CCC->openid_data != NULL) {
388 free(CCC->openid_data);
390 oiddata = malloc(sizeof(struct ctdl_openid));
391 if (oiddata == NULL) {
392 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
395 memset(oiddata, 0, sizeof(struct ctdl_openid));
396 CCC->openid_data = (void *) oiddata;
398 extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
399 extract_token(return_to, argbuf, 1, '|', sizeof return_to);
400 extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
401 oiddata->validated = 0;
403 i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1, sizeof oiddata->claimed_id);
404 CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", oiddata->claimed_id);
405 buf[sizeof buf - 1] = 0;
407 char openid_delegate[1024];
409 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
410 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
412 if (IsEmptyStr(oiddata->server)) {
413 cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
417 /* Empty delegate is legal; we just use the openid_url instead */
418 if (IsEmptyStr(openid_delegate)) {
419 safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
422 /* Assemble a URL to which the user-agent will be redirected. */
423 char redirect_string[4096];
424 char escaped_identity[512];
425 char escaped_return_to[2048];
426 char escaped_trust_root[1024];
427 char escaped_sreg_optional[256];
429 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
430 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
431 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
432 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
433 "nickname,email,fullname,postcode,country");
435 snprintf(redirect_string, sizeof redirect_string,
437 "?openid.mode=checkid_setup"
438 "&openid.identity=%s"
439 "&openid.return_to=%s"
440 "&openid.trust_root=%s"
441 "&openid.sreg.optional=%s"
447 escaped_sreg_optional
449 cprintf("%d %s\n", CIT_OK, redirect_string);
453 cprintf("%d Unable to fetch OpenID URL\n", ERROR);
459 * Callback function to free a pointer (used below in the hash list)
461 void free_oid_key(void *ptr) {
467 * Finalize an OpenID authentication
469 void cmd_oidf(char *argbuf) {
473 HashList *keys = NULL;
475 struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
477 keys = NewHash(1, NULL);
479 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
483 cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
485 while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
486 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
487 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
488 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
489 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), free_oid_key);
493 /* Now that we have all of the parameters, we have to validate the signature against the server */
494 CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
498 struct curl_httppost *formpost = NULL;
499 struct curl_httppost *lastptr = NULL;
500 char errmsg[1024] = "";
501 char *o_assoc_handle = NULL;
503 char *o_signed = NULL;
504 int num_signed_values;
507 char k_o_keyname[128];
508 char *k_value = NULL;
511 struct fh_data fh = {
517 curl_formadd(&formpost, &lastptr,
518 CURLFORM_COPYNAME, "openid.mode",
519 CURLFORM_COPYCONTENTS, "check_authentication",
521 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
523 if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
524 curl_formadd(&formpost, &lastptr,
525 CURLFORM_COPYNAME, "openid.assoc_handle",
526 CURLFORM_COPYCONTENTS, o_assoc_handle,
528 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
531 if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
532 curl_formadd(&formpost, &lastptr,
533 CURLFORM_COPYNAME, "openid.sig",
534 CURLFORM_COPYCONTENTS, o_sig,
536 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
539 if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
540 curl_formadd(&formpost, &lastptr,
541 CURLFORM_COPYNAME, "openid.signed",
542 CURLFORM_COPYCONTENTS, o_signed,
544 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
546 num_signed_values = num_tokens(o_signed, ',');
547 for (i=0; i<num_signed_values; ++i) {
548 extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
549 if (strcasecmp(k_keyname, "mode")) { // work around phpMyID bug
550 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
551 snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
552 curl_formadd(&formpost, &lastptr,
553 CURLFORM_COPYNAME, k_o_keyname,
554 CURLFORM_COPYCONTENTS, k_value,
556 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
559 CtdlLogPrintf(CTDL_INFO, "OpenID: signed field '%s' is missing\n",
566 curl = curl_easy_init();
567 curl_easy_setopt(curl, CURLOPT_URL, oiddata->server);
568 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
569 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
570 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
571 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
572 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
573 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
574 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
575 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
576 if (!IsEmptyStr(config.c_ip_addr)) {
577 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
580 res = curl_easy_perform(curl);
582 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
584 curl_easy_cleanup(curl);
585 curl_formfree(formpost);
587 valbuf[fh.total_bytes_received] = 0;
589 if (bmstrcasestr(valbuf, "is_valid:true")) {
590 oiddata->validated = 1;
593 CtdlLogPrintf(CTDL_DEBUG, "Authentication %s.\n", (oiddata->validated ? "succeeded" : "failed") );
595 /* Respond to the client */
597 if (oiddata->validated) {
599 /* If we were already logged in, attach the OpenID to the user's account */
601 if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
609 /* Otherwise, a user is attempting to log in using the validated OpenID */
611 struct ctdluser usbuf;
614 * Existing user who has claimed this OpenID?
616 * Note: if you think that sending the password back over the wire is insecure,
617 * check your assumptions. If someone has successfully asserted an OpenID that
618 * is associated with the account, they already have password equivalency and can
619 * login, so they could just as easily change the password, etc.
621 if (getuserbyopenid(&usbuf, oiddata->claimed_id) == 0) {
622 cprintf("authenticate\n%s\n%s\n", usbuf.fullname, usbuf.password);
626 cprintf("fail\n"); // FIXME do the login here!!
635 /* Free the hash list */
640 HashPos = GetNewHashPos();
641 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
645 DeleteHashPos(&HashPos);
650 // identity = [50] http://uncensored.citadel.org/~ajc/MyID.config.php
651 // assoc_handle = [26] 6ekac3ju181tgepk7v4h9r7ui7
652 // return_to = [42] http://jemcaterers.net/finish_openid_login
653 // sreg.nickname = [17] IGnatius T Foobar
654 // sreg.email = [26] ajc@uncensored.citadel.org
655 // sreg.fullname = [10] Art Cancro
656 // sreg.postcode = [5] 10549
657 // sreg.country = [2] US
658 // signed = [102] mode,identity,assoc_handle,return_to,sreg.nickname,sreg.email,sreg.fullname,sreg.postcode,sreg.country
659 // sig = [28] vixxxU4MAqWfxxxxCfrHv3TxxxhEw=
664 /**************************************************************************/
666 /* Functions in this section handle module initialization and shutdown */
668 /**************************************************************************/
672 * This cleanup function blows away the temporary memory used by this module.
674 void openid_cleanup_function(void) {
676 if (CC->openid_data != NULL) {
677 free(CC->openid_data);
682 CTDL_MODULE_INIT(openid_rp)
686 curl_global_init(CURL_GLOBAL_ALL);
687 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
688 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
689 CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
690 CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
691 CtdlRegisterSessionHook(openid_cleanup_function, EVT_STOP);
692 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
695 /* return our Subversion id for the Log */
700 /* FIXME ... we have to add the new openid database to serv_vandelay.c */