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 * (actual 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)
72 * Attach an OpenID to a Citadel account
74 int attach_openid(struct ctdluser *who, char *claimed_id)
76 struct cdbdata *cdboi;
82 if (!claimed_id) return(1);
83 if (IsEmptyStr(claimed_id)) return(1);
85 /* Check to see if this OpenID is already in the database */
87 cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
89 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
92 if (fetched_usernum == who->usernum) {
93 CtdlLogPrintf(CTDL_INFO, "%s already associated; no action is taken\n", claimed_id);
97 CtdlLogPrintf(CTDL_INFO, "%s already belongs to another user\n", claimed_id);
102 /* Not already in the database, so attach it now */
104 data_len = sizeof(long) + strlen(claimed_id) + 1;
105 data = malloc(data_len);
107 memcpy(data, &who->usernum, sizeof(long));
108 memcpy(&data[sizeof(long)], claimed_id, strlen(claimed_id) + 1);
110 cdb_store(CDB_OPENID, claimed_id, strlen(claimed_id), data, data_len);
113 CtdlLogPrintf(CTDL_INFO, "%s has been attached to %s (%ld)\n",
114 claimed_id, who->fullname, who->usernum);
121 * When a user is being deleted, we have to delete any OpenID associations
123 void openid_purge(struct ctdluser *usbuf) {
124 struct cdbdata *cdboi;
125 HashList *keys = NULL;
127 char *deleteme = NULL;
132 keys = NewHash(1, NULL);
136 cdb_rewind(CDB_OPENID);
137 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
138 if (cdboi->len > sizeof(long)) {
139 if (((long)*(cdboi->ptr)) == usbuf->usernum) {
140 deleteme = strdup(cdboi->ptr + sizeof(long)),
141 Put(keys, deleteme, strlen(deleteme), deleteme, generic_free_handler);
147 /* Go through the hash list, deleting keys we stored in it */
149 HashPos = GetNewHashPos();
150 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
152 CtdlLogPrintf(CTDL_DEBUG, "Deleting associated OpenID <%s>\n", Value);
153 cdb_delete(CDB_OPENID, Value, strlen(Value));
154 /* note: don't free(Value) -- deleting the hash list will handle this for us */
156 DeleteHashPos(&HashPos);
163 * List the OpenIDs associated with the currently logged in account
165 void cmd_oidl(char *argbuf) {
166 struct cdbdata *cdboi;
168 if (CtdlAccessCheck(ac_logged_in)) return;
169 cdb_rewind(CDB_OPENID);
170 cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
172 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
173 if (cdboi->len > sizeof(long)) {
174 if (((long)*(cdboi->ptr)) == CC->user.usernum) {
175 cprintf("%s\n", cdboi->ptr + sizeof(long));
186 * Detach an OpenID from the currently logged in account
188 void cmd_oidd(char *argbuf) {
189 struct cdbdata *cdboi;
190 char id_to_detach[1024];
191 int this_is_mine = 0;
193 if (CtdlAccessCheck(ac_logged_in)) return;
194 extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
195 if (IsEmptyStr(id_to_detach)) {
196 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
199 cdb_rewind(CDB_OPENID);
200 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
201 if (cdboi->len > sizeof(long)) {
202 if (((long)*(cdboi->ptr)) == CC->user.usernum) {
210 cprintf("%d That OpenID was not found or not associated with your account.\n",
211 ERROR + ILLEGAL_VALUE);
215 cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
216 cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
222 * Attempt to auto-create a new Citadel account using the nickname from Simple Registration Extension
224 int openid_create_user_via_sri(char *claimed_id, HashList *sri_keys)
226 char *desired_name = NULL;
227 char new_password[32];
229 if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
230 if (config.c_disable_newu) return(2);
231 if (CC->logged_in) return(3);
232 if (!GetHash(sri_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
234 CtdlLogPrintf(CTDL_DEBUG, "The desired account name is <%s>\n", desired_name);
236 if (!getuser(&CC->user, desired_name)) {
237 CtdlLogPrintf(CTDL_DEBUG, "<%s> is already taken by another user.\n", desired_name);
238 memset(&CC->user, 0, sizeof(struct ctdluser));
242 /* The desired account name is available. Create the account and log it in! */
243 if (create_user(desired_name, 1)) return(6);
245 snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
246 CtdlSetPassword(new_password);
247 attach_openid(&CC->user, claimed_id);
251 // FIXME we still have to set up the vCard
253 // identity = [50] http://uncensored.citadel.org/~ajc/MyID.config.php
254 // sreg.nickname = [17] IGnatius T Foobar
255 // sreg.email = [26] ajc@uncensored.citadel.org
256 // sreg.fullname = [10] Art Cancro
257 // sreg.postcode = [5] 10549
258 // sreg.country = [2] US
263 * If a user account exists which is associated with the Claimed ID, log it in and return zero.
264 * Otherwise it returns nonzero.
266 int login_via_openid(char *claimed_id)
268 struct cdbdata *cdboi;
271 cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
276 memcpy(&usernum, cdboi->ptr, sizeof(long));
279 if (!getuserbynumber(&CC->user, usernum)) {
280 /* Now become the user we just created */
281 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
286 memset(&CC->user, 0, sizeof(struct ctdluser));
294 /**************************************************************************/
296 /* Functions in this section handle OpenID protocol */
298 /**************************************************************************/
302 * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
304 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
306 char *ptr = source_buf;
308 if (!target_buf) return;
310 if (!source_buf) return;
314 while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
316 char work_buffer[2048];
317 char *link_tag_start = NULL;
318 char *link_tag_end = NULL;
323 link_tag_start = ptr;
324 link_tag_end = strchr(ptr, '>');
328 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
330 len = link_tag_end - link_tag_start;
331 if (len > sizeof work_buffer) len = sizeof work_buffer;
332 memcpy(work_buffer, link_tag_start, len);
334 char *rel_start = NULL;
335 char *rel_end = NULL;
336 rel_start = bmstrcasestr(work_buffer, "rel=");
338 rel_start = strchr(rel_start, '\"');
341 rel_end = strchr(rel_start, '\"');
342 if ((rel_end) && (rel_end > rel_start)) {
343 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
348 char *href_start = NULL;
349 char *href_end = NULL;
350 href_start = bmstrcasestr(work_buffer, "href=");
352 href_start = strchr(href_start, '\"');
355 href_end = strchr(href_start, '\"');
356 if ((href_end) && (href_end > href_start)) {
357 safestrncpy(href_tag, href_start, href_end - href_start + 1);
362 if (!strcasecmp(rel, rel_tag)) {
363 safestrncpy(target_buf, href_tag, target_size);
379 int total_bytes_received;
384 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
386 struct fh_data *fh = (struct fh_data *) stream;
387 int got_bytes = (size * nmemb);
389 if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
390 got_bytes = fh->maxbytes - fh->total_bytes_received;
393 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
394 fh->total_bytes_received += got_bytes;
397 return (size * nmemb); /* always succeed; libcurl doesn't need to know if we truncated it */
403 * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
405 * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
406 * requesting that the effective (normalized) URL be copied back to it.
408 int fetch_http(char *url, char *target_buf, int maxbytes, int normalize_len)
412 char errmsg[1024] = "";
413 struct fh_data fh = {
418 char *effective_url = NULL;
420 if (!url) return(-1);
421 if (!target_buf) return(-1);
422 memset(target_buf, 0, maxbytes);
424 curl = curl_easy_init();
426 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
430 curl_easy_setopt(curl, CURLOPT_URL, url);
431 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
432 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
433 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
434 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
435 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
436 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
437 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
438 if (!IsEmptyStr(config.c_ip_addr)) {
439 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
441 res = curl_easy_perform(curl);
443 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
445 if (normalize_len > 0) {
446 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
447 safestrncpy(url, effective_url, normalize_len);
449 curl_easy_cleanup(curl);
450 return fh.total_bytes_received;
455 * Setup an OpenID authentication
457 void cmd_oids(char *argbuf) {
458 char return_to[1024];
459 char trust_root[1024];
462 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
463 struct ctdl_openid *oiddata;
465 /* commented out because we may be attempting to attach an OpenID to
466 * an existing account that is logged in
468 if (CCC->logged_in) {
469 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
474 if (CCC->openid_data != NULL) {
475 free(CCC->openid_data);
477 oiddata = malloc(sizeof(struct ctdl_openid));
478 if (oiddata == NULL) {
479 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
482 memset(oiddata, 0, sizeof(struct ctdl_openid));
483 CCC->openid_data = (void *) oiddata;
485 extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
486 extract_token(return_to, argbuf, 1, '|', sizeof return_to);
487 extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
488 oiddata->verified = 0;
490 i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1, sizeof oiddata->claimed_id);
491 CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", oiddata->claimed_id);
492 buf[sizeof buf - 1] = 0;
494 char openid_delegate[1024];
496 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
497 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
499 if (IsEmptyStr(oiddata->server)) {
500 cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
504 /* Empty delegate is legal; we just use the openid_url instead */
505 if (IsEmptyStr(openid_delegate)) {
506 safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
509 /* Assemble a URL to which the user-agent will be redirected. */
510 char redirect_string[4096];
511 char escaped_identity[512];
512 char escaped_return_to[2048];
513 char escaped_trust_root[1024];
514 char escaped_sreg_optional[256];
516 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
517 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
518 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
519 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
520 "nickname,email,fullname,postcode,country");
522 snprintf(redirect_string, sizeof redirect_string,
524 "?openid.mode=checkid_setup"
525 "&openid.identity=%s"
526 "&openid.return_to=%s"
527 "&openid.trust_root=%s"
528 "&openid.sreg.optional=%s"
534 escaped_sreg_optional
536 cprintf("%d %s\n", CIT_OK, redirect_string);
540 cprintf("%d Unable to fetch OpenID URL\n", ERROR);
548 * Finalize an OpenID authentication
550 void cmd_oidf(char *argbuf) {
554 HashList *keys = NULL;
555 struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
557 keys = NewHash(1, NULL);
559 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
563 cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
565 while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
566 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
567 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
568 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
569 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), generic_free_handler);
573 /* Now that we have all of the parameters, we have to validate the signature against the server */
574 CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
578 struct curl_httppost *formpost = NULL;
579 struct curl_httppost *lastptr = NULL;
580 char errmsg[1024] = "";
581 char *o_assoc_handle = NULL;
583 char *o_signed = NULL;
584 int num_signed_values;
587 char k_o_keyname[128];
588 char *k_value = NULL;
591 struct fh_data fh = {
597 curl_formadd(&formpost, &lastptr,
598 CURLFORM_COPYNAME, "openid.mode",
599 CURLFORM_COPYCONTENTS, "check_authentication",
601 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
603 if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
604 curl_formadd(&formpost, &lastptr,
605 CURLFORM_COPYNAME, "openid.assoc_handle",
606 CURLFORM_COPYCONTENTS, o_assoc_handle,
608 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
611 if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
612 curl_formadd(&formpost, &lastptr,
613 CURLFORM_COPYNAME, "openid.sig",
614 CURLFORM_COPYCONTENTS, o_sig,
616 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
619 if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
620 curl_formadd(&formpost, &lastptr,
621 CURLFORM_COPYNAME, "openid.signed",
622 CURLFORM_COPYCONTENTS, o_signed,
624 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
626 num_signed_values = num_tokens(o_signed, ',');
627 for (i=0; i<num_signed_values; ++i) {
628 extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
629 if (strcasecmp(k_keyname, "mode")) { // work around phpMyID bug
630 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
631 snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
632 curl_formadd(&formpost, &lastptr,
633 CURLFORM_COPYNAME, k_o_keyname,
634 CURLFORM_COPYCONTENTS, k_value,
636 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
639 CtdlLogPrintf(CTDL_INFO, "OpenID: signed field '%s' is missing\n",
646 curl = curl_easy_init();
647 curl_easy_setopt(curl, CURLOPT_URL, oiddata->server);
648 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
649 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
650 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
651 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
652 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
653 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
654 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
655 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
656 if (!IsEmptyStr(config.c_ip_addr)) {
657 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
660 res = curl_easy_perform(curl);
662 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
664 curl_easy_cleanup(curl);
665 curl_formfree(formpost);
667 valbuf[fh.total_bytes_received] = 0;
669 if (bmstrcasestr(valbuf, "is_valid:true")) {
670 oiddata->verified = 1;
673 CtdlLogPrintf(CTDL_DEBUG, "Authentication %s.\n", (oiddata->verified ? "succeeded" : "failed") );
675 /* Respond to the client */
677 if (oiddata->verified) {
679 /* If we were already logged in, attach the OpenID to the user's account */
681 if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
689 /* Otherwise, a user is attempting to log in using the verified OpenID */
692 * Existing user who has claimed this OpenID?
694 * Note: if you think that sending the password back over the wire is insecure,
695 * check your assumptions. If someone has successfully asserted an OpenID that
696 * is associated with the account, they already have password equivalency and can
697 * login, so they could just as easily change the password, etc.
699 if (login_via_openid(oiddata->claimed_id) == 0) {
700 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
701 logged_in_response();
705 * New user whose OpenID is verified and Simple Registration Extension is in use?
707 else if (openid_create_user_via_sri(oiddata->claimed_id, keys) == 0) {
708 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
709 logged_in_response();
713 * OpenID is verified, but the desired username either was not specified or
714 * conflicts with an existing user. Manual account creation is required.
717 char *desired_name = NULL;
718 cprintf("verify_only\n");
719 cprintf("%s\n", oiddata->claimed_id);
720 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
721 cprintf("%s\n", desired_name);
735 * We will eventually do something with the data in the hash list.
741 HashPos = GetNewHashPos();
742 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
745 DeleteHashPos(&HashPos);
748 DeleteHash(&keys); /* This will free() all the key data for us */
753 /**************************************************************************/
755 /* Functions in this section handle module initialization and shutdown */
757 /**************************************************************************/
761 * This cleanup function blows away the temporary memory used by this module.
763 void openid_cleanup_function(void) {
765 if (CC->openid_data != NULL) {
766 CtdlLogPrintf(CTDL_DEBUG, "Clearing OpenID session state\n");
767 free(CC->openid_data);
772 CTDL_MODULE_INIT(openid_rp)
776 curl_global_init(CURL_GLOBAL_ALL);
777 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
778 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
779 CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
780 CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
781 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
782 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
785 /* return our Subversion id for the Log */
790 /* FIXME ... we have to add the new openid database to serv_vandelay.c */