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 associated with %s (%ld)\n",
114 claimed_id, who->fullname, who->usernum);
120 * When a user is being deleted, we have to delete any OpenID associations
122 void openid_purge(struct ctdluser *usbuf) {
123 struct cdbdata *cdboi;
124 HashList *keys = NULL;
126 char *deleteme = NULL;
131 keys = NewHash(1, NULL);
135 cdb_rewind(CDB_OPENID);
136 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
137 if (cdboi->len > sizeof(long)) {
138 if (((long)*(cdboi->ptr)) == usbuf->usernum) {
139 deleteme = strdup(cdboi->ptr + sizeof(long)),
140 Put(keys, deleteme, strlen(deleteme), deleteme, generic_free_handler);
146 /* Go through the hash list, deleting keys we stored in it */
148 HashPos = GetNewHashPos();
149 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
151 CtdlLogPrintf(CTDL_DEBUG, "Deleting associated OpenID <%s>\n", Value);
152 cdb_delete(CDB_OPENID, Value, strlen(Value));
153 /* note: don't free(Value) -- deleting the hash list will handle this for us */
155 DeleteHashPos(&HashPos);
162 * List the OpenIDs associated with the currently logged in account
164 void cmd_oidl(char *argbuf) {
165 struct cdbdata *cdboi;
167 if (CtdlAccessCheck(ac_logged_in)) return;
168 cdb_rewind(CDB_OPENID);
169 cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
171 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
172 if (cdboi->len > sizeof(long)) {
173 if (((long)*(cdboi->ptr)) == CC->user.usernum) {
174 cprintf("%s\n", cdboi->ptr + sizeof(long));
185 * Detach an OpenID from the currently logged in account
187 void cmd_oidd(char *argbuf) {
188 struct cdbdata *cdboi;
189 char id_to_detach[1024];
190 int this_is_mine = 0;
192 if (CtdlAccessCheck(ac_logged_in)) return;
193 extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
194 if (IsEmptyStr(id_to_detach)) {
195 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
198 cdb_rewind(CDB_OPENID);
199 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
200 if (cdboi->len > sizeof(long)) {
201 if (((long)*(cdboi->ptr)) == CC->user.usernum) {
209 cprintf("%d That OpenID was not found or not associated with your account.\n",
210 ERROR + ILLEGAL_VALUE);
214 cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
215 cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
221 * getuserbyopenid() works the same way as getuser() and getuserbynumber().
222 * If a user account exists which is associated with the Claimed ID, it fills usbuf and returns zero.
223 * Otherwise it returns nonzero.
225 int getuserbyopenid(struct ctdluser *usbuf, char *claimed_id)
227 struct cdbdata *cdboi;
230 cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
235 memcpy(&usernum, cdboi->ptr, sizeof(long));
238 return(getuserbynumber(usbuf, usernum));
243 int openid_create_user_via_sri(struct ctdluser *usbuf, char *claimed_id, HashList *sri_keys)
245 if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
246 if (config.c_disable_newu) return(2);
248 /* FIXME do something */
254 /**************************************************************************/
256 /* Functions in this section handle OpenID protocol */
258 /**************************************************************************/
262 * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
264 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
266 char *ptr = source_buf;
268 if (!target_buf) return;
270 if (!source_buf) return;
274 while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
276 char work_buffer[2048];
277 char *link_tag_start = NULL;
278 char *link_tag_end = NULL;
283 link_tag_start = ptr;
284 link_tag_end = strchr(ptr, '>');
288 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
290 len = link_tag_end - link_tag_start;
291 if (len > sizeof work_buffer) len = sizeof work_buffer;
292 memcpy(work_buffer, link_tag_start, len);
294 char *rel_start = NULL;
295 char *rel_end = NULL;
296 rel_start = bmstrcasestr(work_buffer, "rel=");
298 rel_start = strchr(rel_start, '\"');
301 rel_end = strchr(rel_start, '\"');
302 if ((rel_end) && (rel_end > rel_start)) {
303 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
308 char *href_start = NULL;
309 char *href_end = NULL;
310 href_start = bmstrcasestr(work_buffer, "href=");
312 href_start = strchr(href_start, '\"');
315 href_end = strchr(href_start, '\"');
316 if ((href_end) && (href_end > href_start)) {
317 safestrncpy(href_tag, href_start, href_end - href_start + 1);
322 if (!strcasecmp(rel, rel_tag)) {
323 safestrncpy(target_buf, href_tag, target_size);
339 int total_bytes_received;
344 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
346 struct fh_data *fh = (struct fh_data *) stream;
347 int got_bytes = (size * nmemb);
349 if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
350 got_bytes = fh->maxbytes - fh->total_bytes_received;
353 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
354 fh->total_bytes_received += got_bytes;
357 return (size * nmemb); /* always succeed; libcurl doesn't need to know if we truncated it */
363 * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
365 * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
366 * requesting that the effective (normalized) URL be copied back to it.
368 int fetch_http(char *url, char *target_buf, int maxbytes, int normalize_len)
372 char errmsg[1024] = "";
373 struct fh_data fh = {
378 char *effective_url = NULL;
380 if (!url) return(-1);
381 if (!target_buf) return(-1);
382 memset(target_buf, 0, maxbytes);
384 curl = curl_easy_init();
386 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
390 curl_easy_setopt(curl, CURLOPT_URL, url);
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_ERRORBUFFER, errmsg);
396 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
397 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
398 if (!IsEmptyStr(config.c_ip_addr)) {
399 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
401 res = curl_easy_perform(curl);
403 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
405 if (normalize_len > 0) {
406 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
407 safestrncpy(url, effective_url, normalize_len);
409 curl_easy_cleanup(curl);
410 return fh.total_bytes_received;
415 * Setup an OpenID authentication
417 void cmd_oids(char *argbuf) {
418 char return_to[1024];
419 char trust_root[1024];
422 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
423 struct ctdl_openid *oiddata;
425 /* commented out because we may be attempting to attach an OpenID to
426 * an existing account that is logged in
428 if (CCC->logged_in) {
429 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
434 if (CCC->openid_data != NULL) {
435 free(CCC->openid_data);
437 oiddata = malloc(sizeof(struct ctdl_openid));
438 if (oiddata == NULL) {
439 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
442 memset(oiddata, 0, sizeof(struct ctdl_openid));
443 CCC->openid_data = (void *) oiddata;
445 extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
446 extract_token(return_to, argbuf, 1, '|', sizeof return_to);
447 extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
448 oiddata->validated = 0;
450 i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1, sizeof oiddata->claimed_id);
451 CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", oiddata->claimed_id);
452 buf[sizeof buf - 1] = 0;
454 char openid_delegate[1024];
456 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
457 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
459 if (IsEmptyStr(oiddata->server)) {
460 cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
464 /* Empty delegate is legal; we just use the openid_url instead */
465 if (IsEmptyStr(openid_delegate)) {
466 safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
469 /* Assemble a URL to which the user-agent will be redirected. */
470 char redirect_string[4096];
471 char escaped_identity[512];
472 char escaped_return_to[2048];
473 char escaped_trust_root[1024];
474 char escaped_sreg_optional[256];
476 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
477 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
478 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
479 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
480 "nickname,email,fullname,postcode,country");
482 snprintf(redirect_string, sizeof redirect_string,
484 "?openid.mode=checkid_setup"
485 "&openid.identity=%s"
486 "&openid.return_to=%s"
487 "&openid.trust_root=%s"
488 "&openid.sreg.optional=%s"
494 escaped_sreg_optional
496 cprintf("%d %s\n", CIT_OK, redirect_string);
500 cprintf("%d Unable to fetch OpenID URL\n", ERROR);
508 * Finalize an OpenID authentication
510 void cmd_oidf(char *argbuf) {
514 HashList *keys = NULL;
515 struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
517 keys = NewHash(1, NULL);
519 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
523 cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
525 while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
526 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
527 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
528 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
529 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), generic_free_handler);
533 /* Now that we have all of the parameters, we have to validate the signature against the server */
534 CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
538 struct curl_httppost *formpost = NULL;
539 struct curl_httppost *lastptr = NULL;
540 char errmsg[1024] = "";
541 char *o_assoc_handle = NULL;
543 char *o_signed = NULL;
544 int num_signed_values;
547 char k_o_keyname[128];
548 char *k_value = NULL;
551 struct fh_data fh = {
557 curl_formadd(&formpost, &lastptr,
558 CURLFORM_COPYNAME, "openid.mode",
559 CURLFORM_COPYCONTENTS, "check_authentication",
561 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
563 if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
564 curl_formadd(&formpost, &lastptr,
565 CURLFORM_COPYNAME, "openid.assoc_handle",
566 CURLFORM_COPYCONTENTS, o_assoc_handle,
568 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
571 if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
572 curl_formadd(&formpost, &lastptr,
573 CURLFORM_COPYNAME, "openid.sig",
574 CURLFORM_COPYCONTENTS, o_sig,
576 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
579 if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
580 curl_formadd(&formpost, &lastptr,
581 CURLFORM_COPYNAME, "openid.signed",
582 CURLFORM_COPYCONTENTS, o_signed,
584 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
586 num_signed_values = num_tokens(o_signed, ',');
587 for (i=0; i<num_signed_values; ++i) {
588 extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
589 if (strcasecmp(k_keyname, "mode")) { // work around phpMyID bug
590 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
591 snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
592 curl_formadd(&formpost, &lastptr,
593 CURLFORM_COPYNAME, k_o_keyname,
594 CURLFORM_COPYCONTENTS, k_value,
596 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
599 CtdlLogPrintf(CTDL_INFO, "OpenID: signed field '%s' is missing\n",
606 curl = curl_easy_init();
607 curl_easy_setopt(curl, CURLOPT_URL, oiddata->server);
608 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
609 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
610 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
611 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
612 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
613 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
614 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
615 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
616 if (!IsEmptyStr(config.c_ip_addr)) {
617 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
620 res = curl_easy_perform(curl);
622 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
624 curl_easy_cleanup(curl);
625 curl_formfree(formpost);
627 valbuf[fh.total_bytes_received] = 0;
629 if (bmstrcasestr(valbuf, "is_valid:true")) {
630 oiddata->validated = 1;
633 CtdlLogPrintf(CTDL_DEBUG, "Authentication %s.\n", (oiddata->validated ? "succeeded" : "failed") );
635 /* Respond to the client */
637 if (oiddata->validated) {
639 /* If we were already logged in, attach the OpenID to the user's account */
641 if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
649 /* Otherwise, a user is attempting to log in using the validated OpenID */
651 struct ctdluser usbuf;
654 * Existing user who has claimed this OpenID?
656 * Note: if you think that sending the password back over the wire is insecure,
657 * check your assumptions. If someone has successfully asserted an OpenID that
658 * is associated with the account, they already have password equivalency and can
659 * login, so they could just as easily change the password, etc.
661 if (getuserbyopenid(&usbuf, oiddata->claimed_id) == 0) {
662 cprintf("authenticate\n%s\n%s\n", usbuf.fullname, usbuf.password);
666 * New user whose OpenID is verified and Simple Registration Extension is in use?
668 else if (openid_create_user_via_sri(&usbuf, oiddata->claimed_id, keys) == 0) {
669 cprintf("authenticate\n%s\n%s\n", usbuf.fullname, usbuf.password);
672 /* FIXME right here we have to handle manual account creation */
685 * We will eventually do something with the data in the hash list.
691 HashPos = GetNewHashPos();
692 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
695 DeleteHashPos(&HashPos);
698 DeleteHash(&keys); /* This will free() all the key data for us */
703 // identity = [50] http://uncensored.citadel.org/~ajc/MyID.config.php
704 // assoc_handle = [26] 6ekac3ju181tgepk7v4h9r7ui7
705 // return_to = [42] http://jemcaterers.net/finish_openid_login
706 // sreg.nickname = [17] IGnatius T Foobar
707 // sreg.email = [26] ajc@uncensored.citadel.org
708 // sreg.fullname = [10] Art Cancro
709 // sreg.postcode = [5] 10549
710 // sreg.country = [2] US
711 // signed = [102] mode,identity,assoc_handle,return_to,sreg.nickname,sreg.email,sreg.fullname,sreg.postcode,sreg.country
712 // sig = [28] vixxxU4MAqWfxxxxCfrHv3TxxxhEw=
717 /**************************************************************************/
719 /* Functions in this section handle module initialization and shutdown */
721 /**************************************************************************/
725 * This cleanup function blows away the temporary memory used by this module.
727 void openid_cleanup_function(void) {
729 if (CC->openid_data != NULL) {
730 free(CC->openid_data);
735 CTDL_MODULE_INIT(openid_rp)
739 curl_global_init(CURL_GLOBAL_ALL);
740 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
741 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
742 CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
743 CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
744 CtdlRegisterSessionHook(openid_cleanup_function, EVT_STOP);
745 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
748 /* return our Subversion id for the Log */
753 /* FIXME ... we have to add the new openid database to serv_vandelay.c */