2 * This is an implementation of OpenID 2.0 relying party support in stateless mode.
4 * Copyright (c) 2007-2011 by the citadel.org team
6 * This program is open source software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
28 #include <sys/types.h>
30 #if TIME_WITH_SYS_TIME
31 # include <sys/time.h>
35 # include <sys/time.h>
44 #include <curl/curl.h>
46 #include "ctdl_module.h"
48 #include "citserver.h"
51 typedef struct _ctdl_openid {
52 StrBuf *op_url; /* OpenID Provider Endpoint URL */
53 StrBuf *claimed_id; /* Claimed Identifier */
65 void Free_ctdl_openid(ctdl_openid **FreeMe)
67 if (*FreeMe == NULL) {
70 FreeStrBuf(&(*FreeMe)->op_url);
71 FreeStrBuf(&(*FreeMe)->claimed_id);
72 DeleteHash(&(*FreeMe)->sreg_keys);
79 * This cleanup function blows away the temporary memory used by this module.
81 void openid_cleanup_function(void) {
82 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
84 if (CCC->openid_data != NULL) {
85 syslog(LOG_DEBUG, "Clearing OpenID session state");
86 Free_ctdl_openid((ctdl_openid **) &CCC->openid_data);
91 /**************************************************************************/
93 /* Functions in this section handle Citadel internal OpenID mapping stuff */
95 /**************************************************************************/
99 * The structure of an openid record *key* is:
101 * |--------------claimed_id-------------|
102 * (actual length of claimed id)
105 * The structure of an openid record *value* is:
107 * |-----user_number----|------------claimed_id---------------|
108 * (sizeof long) (actual length of claimed id)
115 * Attach an OpenID to a Citadel account
117 int attach_openid(struct ctdluser *who, StrBuf *claimed_id)
119 struct cdbdata *cdboi;
120 long fetched_usernum;
126 if (StrLength(claimed_id)==0) return(1);
128 /* Check to see if this OpenID is already in the database */
130 cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
132 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
135 if (fetched_usernum == who->usernum) {
136 syslog(LOG_INFO, "%s already associated; no action is taken", ChrPtr(claimed_id));
140 syslog(LOG_INFO, "%s already belongs to another user", ChrPtr(claimed_id));
145 /* Not already in the database, so attach it now */
147 data_len = sizeof(long) + StrLength(claimed_id) + 1;
148 data = malloc(data_len);
150 memcpy(data, &who->usernum, sizeof(long));
151 memcpy(&data[sizeof(long)], ChrPtr(claimed_id), StrLength(claimed_id) + 1);
153 cdb_store(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id), data, data_len);
156 snprintf(buf, sizeof buf, "User <%s> (#%ld) has claimed the OpenID URL %s\n",
157 who->fullname, who->usernum, ChrPtr(claimed_id));
158 CtdlAideMessage(buf, "OpenID claim");
159 syslog(LOG_INFO, "%s", buf);
166 * When a user is being deleted, we have to delete any OpenID associations
168 void openid_purge(struct ctdluser *usbuf) {
169 struct cdbdata *cdboi;
170 HashList *keys = NULL;
172 char *deleteme = NULL;
178 keys = NewHash(1, NULL);
181 cdb_rewind(CDB_OPENID);
182 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
183 if (cdboi->len > sizeof(long)) {
184 memcpy(&usernum, cdboi->ptr, sizeof(long));
185 if (usernum == usbuf->usernum) {
186 deleteme = strdup(cdboi->ptr + sizeof(long)),
187 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
193 /* Go through the hash list, deleting keys we stored in it */
195 HashPos = GetNewHashPos(keys, 0);
196 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
198 syslog(LOG_DEBUG, "Deleting associated OpenID <%s>", (char*)Value);
199 cdb_delete(CDB_OPENID, Value, strlen(Value));
200 /* note: don't free(Value) -- deleting the hash list will handle this for us */
202 DeleteHashPos(&HashPos);
208 * List the OpenIDs associated with the currently logged in account
210 void cmd_oidl(char *argbuf) {
211 struct cdbdata *cdboi;
214 if (CtdlAccessCheck(ac_logged_in)) return;
215 cdb_rewind(CDB_OPENID);
216 cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
218 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
219 if (cdboi->len > sizeof(long)) {
220 memcpy(&usernum, cdboi->ptr, sizeof(long));
221 if (usernum == CC->user.usernum) {
222 cprintf("%s\n", cdboi->ptr + sizeof(long));
232 * List ALL OpenIDs in the database
234 void cmd_oida(char *argbuf) {
235 struct cdbdata *cdboi;
237 struct ctdluser usbuf;
239 if (CtdlAccessCheck(ac_aide)) return;
240 cdb_rewind(CDB_OPENID);
241 cprintf("%d List of all OpenIDs in the database:\n", LISTING_FOLLOWS);
243 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
244 if (cdboi->len > sizeof(long)) {
245 memcpy(&usernum, cdboi->ptr, sizeof(long));
246 if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
247 usbuf.fullname[0] = 0;
249 cprintf("%s|%ld|%s\n",
250 cdboi->ptr + sizeof(long),
262 * Create a new user account, manually specifying the name, after successfully
263 * verifying an OpenID (which will of course be attached to the account)
265 void cmd_oidc(char *argbuf) {
266 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
268 if ( (!oiddata) || (!oiddata->verified) ) {
269 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
273 /* We can make the semantics of OIDC exactly the same as NEWU, simply
274 * by _calling_ cmd_newu() and letting it run. Very clever!
278 /* Now, if this logged us in, we have to attach the OpenID */
280 attach_openid(&CC->user, oiddata->claimed_id);
287 * Detach an OpenID from the currently logged in account
289 void cmd_oidd(char *argbuf) {
290 struct cdbdata *cdboi;
291 char id_to_detach[1024];
292 int this_is_mine = 0;
295 if (CtdlAccessCheck(ac_logged_in)) return;
296 extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
297 if (IsEmptyStr(id_to_detach)) {
298 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
301 cdb_rewind(CDB_OPENID);
302 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
303 if (cdboi->len > sizeof(long)) {
304 memcpy(&usernum, cdboi->ptr, sizeof(long));
305 if (usernum == CC->user.usernum) {
313 cprintf("%d That OpenID was not found or not associated with your account.\n",
314 ERROR + ILLEGAL_VALUE);
318 cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
319 cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
324 * Attempt to auto-create a new Citadel account using the nickname from Attribute Exchange
326 int openid_create_user_via_ax(StrBuf *claimed_id, HashList *sreg_keys)
328 char *desired_name = NULL;
329 char new_password[32];
332 if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
333 if (config.c_disable_newu) return(2);
334 if (CC->logged_in) return(3);
335 if (!GetHash(sreg_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
337 syslog(LOG_DEBUG, "The desired account name is <%s>", desired_name);
339 len = cutuserkey(desired_name);
340 if (!CtdlGetUser(&CC->user, desired_name)) {
341 syslog(LOG_DEBUG, "<%s> is already taken by another user.", desired_name);
342 memset(&CC->user, 0, sizeof(struct ctdluser));
346 /* The desired account name is available. Create the account and log it in! */
347 if (create_user(desired_name, len, 1)) return(6);
349 /* Generate a random password.
350 * The user doesn't care what the password is since he's using OpenID.
352 snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
353 CtdlSetPassword(new_password);
355 /* Now attach the verified OpenID to this account. */
356 attach_openid(&CC->user, claimed_id);
363 * If a user account exists which is associated with the Claimed ID, log it in and return zero.
364 * Otherwise it returns nonzero.
366 int login_via_openid(StrBuf *claimed_id)
368 struct cdbdata *cdboi;
371 cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
376 memcpy(&usernum, cdboi->ptr, sizeof(long));
379 if (!CtdlGetUserByNumber(&CC->user, usernum)) {
380 /* Now become the user we just created */
381 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
386 memset(&CC->user, 0, sizeof(struct ctdluser));
394 /**************************************************************************/
396 /* Functions in this section handle OpenID protocol */
398 /**************************************************************************/
402 * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
404 void extract_link(StrBuf *target_buf, const char *rel, long repllen, StrBuf *source_buf)
408 const char *href_start = NULL;
409 const char *href_end = NULL;
410 const char *link_tag_start = NULL;
411 const char *link_tag_end = NULL;
412 const char *rel_start = NULL;
413 const char *rel_end = NULL;
415 if (!target_buf) return;
417 if (!source_buf) return;
419 ptr = ChrPtr(source_buf);
421 FlushStrBuf(target_buf);
422 while (ptr = cbmstrcasestr(ptr, "<link"), ptr != NULL) {
424 link_tag_start = ptr;
425 link_tag_end = strchr(ptr, '>');
426 if (link_tag_end == NULL)
428 for (i=0; i < 1; i++ ){
429 rel_start = cbmstrcasestr(link_tag_start, "rel=");
430 if ((rel_start == NULL) ||
431 (rel_start > link_tag_end))
434 rel_start = strchr(rel_start, '\"');
435 if ((rel_start == NULL) ||
436 (rel_start > link_tag_end))
439 rel_end = strchr(rel_start, '\"');
440 if ((rel_end == NULL) ||
441 (rel_end == rel_start) ||
442 (rel_end >= link_tag_end) )
444 if (strncasecmp(rel, rel_start, repllen)!= 0)
445 continue; /* didn't match? never mind... */
447 href_start = cbmstrcasestr(link_tag_start, "href=");
448 if ((href_start == NULL) ||
449 (href_start >= link_tag_end))
451 href_start = strchr(href_start, '\"');
452 if ((href_start == NULL) |
453 (href_start >= link_tag_end))
456 href_end = strchr(href_start, '\"');
457 if ((href_end == NULL) ||
458 (href_end == href_start) ||
459 (href_start >= link_tag_end))
461 StrBufPlain(target_buf, href_start, href_end - href_start);
469 * Wrapper for curl_easy_init() that includes the options common to all calls
470 * used in this module.
472 CURL *ctdl_openid_curl_easy_init(char *errmsg) {
475 curl = curl_easy_init();
480 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
481 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
484 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
486 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
487 #ifdef CURLOPT_HTTP_CONTENT_DECODING
488 curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
489 curl_easy_setopt(curl, CURLOPT_ENCODING, "");
491 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
492 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30); /* die after 30 seconds */
495 (!IsEmptyStr(config.c_ip_addr))
496 && (strcmp(config.c_ip_addr, "*"))
497 && (strcmp(config.c_ip_addr, "::"))
498 && (strcmp(config.c_ip_addr, "0.0.0.0"))
500 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
511 int current_service_priority;
512 int selected_service_priority;
513 StrBuf *current_service_uri;
514 StrBuf *selected_service_uri;
515 int current_service_is_oid2auth;
519 void xrds_xml_start(void *data, const char *supplied_el, const char **attr) {
520 struct xrds *xrds = (struct xrds *) data;
523 ++xrds->nesting_level;
525 if (!strcasecmp(supplied_el, "XRD")) {
529 else if (!strcasecmp(supplied_el, "service")) {
530 xrds->current_service_priority = 0;
531 xrds->current_service_is_oid2auth = 0;
532 for (i=0; attr[i] != NULL; i+=2) {
533 if (!strcasecmp(attr[i], "priority")) {
534 xrds->current_service_priority = atoi(attr[i+1]);
539 FlushStrBuf(xrds->CharData);
543 void xrds_xml_end(void *data, const char *supplied_el) {
544 struct xrds *xrds = (struct xrds *) data;
546 --xrds->nesting_level;
548 if (!strcasecmp(supplied_el, "XRD")) {
552 else if (!strcasecmp(supplied_el, "type")) {
554 && (!strcasecmp(ChrPtr(xrds->CharData), "http://specs.openid.net/auth/2.0/server"))
556 xrds->current_service_is_oid2auth = 1;
559 && (!strcasecmp(ChrPtr(xrds->CharData), "http://specs.openid.net/auth/2.0/signon"))
561 xrds->current_service_is_oid2auth = 1;
562 /* FIXME in this case, the Claimed ID should be considered immutable */
566 else if (!strcasecmp(supplied_el, "uri")) {
568 FlushStrBuf(xrds->current_service_uri);
569 StrBufAppendBuf(xrds->current_service_uri, xrds->CharData, 0);
573 else if (!strcasecmp(supplied_el, "service")) {
575 && (xrds->current_service_priority < xrds->selected_service_priority)
576 && (xrds->current_service_is_oid2auth)
578 xrds->selected_service_priority = xrds->current_service_priority;
579 FlushStrBuf(xrds->selected_service_uri);
580 StrBufAppendBuf(xrds->selected_service_uri, xrds->current_service_uri, 0);
585 FlushStrBuf(xrds->CharData);
589 void xrds_xml_chardata(void *data, const XML_Char *s, int len) {
590 struct xrds *xrds = (struct xrds *) data;
592 StrBufAppendBufPlain (xrds->CharData, s, len, 0);
597 * Parse an XRDS document.
598 * If an OpenID Provider URL is discovered, op_url to that value and return nonzero.
599 * If nothing useful happened, return 0.
601 int parse_xrds_document(StrBuf *ReplyBuf) {
602 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
604 int return_value = 0;
606 memset(&xrds, 0, sizeof (struct xrds));
607 xrds.selected_service_priority = INT_MAX;
608 xrds.CharData = NewStrBuf();
609 xrds.current_service_uri = NewStrBuf();
610 xrds.selected_service_uri = NewStrBuf();
611 XML_Parser xp = XML_ParserCreate(NULL);
613 XML_SetUserData(xp, &xrds);
614 XML_SetElementHandler(xp, xrds_xml_start, xrds_xml_end);
615 XML_SetCharacterDataHandler(xp, xrds_xml_chardata);
616 XML_Parse(xp, ChrPtr(ReplyBuf), StrLength(ReplyBuf), 0);
617 XML_Parse(xp, "", 0, 1);
621 syslog(LOG_ALERT, "Cannot create XML parser");
624 if (xrds.selected_service_priority < INT_MAX) {
625 if (oiddata->op_url == NULL) {
626 oiddata->op_url = NewStrBuf();
628 FlushStrBuf(oiddata->op_url);
629 StrBufAppendBuf(oiddata->op_url, xrds.selected_service_uri, 0);
630 return_value = openid_disco_xrds;
633 FreeStrBuf(&xrds.CharData);
634 FreeStrBuf(&xrds.current_service_uri);
635 FreeStrBuf(&xrds.selected_service_uri);
637 return(return_value);
642 * Callback function for perform_openid2_discovery()
643 * We're interested in the X-XRDS-Location: header.
645 size_t yadis_headerfunction(void *ptr, size_t size, size_t nmemb, void *userdata) {
647 StrBuf **x_xrds_location = (StrBuf **) userdata;
649 memcpy(hdr, ptr, (size*nmemb));
652 if (!strncasecmp(hdr, "X-XRDS-Location:", 16)) {
653 *x_xrds_location = NewStrBufPlain(&hdr[16], ((size*nmemb)-16));
654 StrBufTrim(*x_xrds_location);
657 return(size * nmemb);
661 /* Attempt to perform Yadis discovery as specified in Yadis 1.0 section 6.2.5.
663 * If Yadis fails, we then attempt HTML discovery using the same document.
665 * If successful, returns nonzero and calls parse_xrds_document() to act upon the received data.
666 * If fails, returns 0 and does nothing else.
668 int perform_openid2_discovery(StrBuf *SuppliedURL) {
669 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
671 StrBuf *ReplyBuf = NULL;
672 int return_value = 0;
675 char errmsg[1024] = "";
676 struct curl_slist *my_headers = NULL;
677 StrBuf *x_xrds_location = NULL;
679 if (!SuppliedURL) return(0);
680 syslog(LOG_DEBUG, "perform_openid2_discovery(%s)", ChrPtr(SuppliedURL));
681 if (StrLength(SuppliedURL) == 0) return(0);
683 ReplyBuf = NewStrBuf();
684 if (!ReplyBuf) return(0);
686 curl = ctdl_openid_curl_easy_init(errmsg);
687 if (!curl) return(0);
689 curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(SuppliedURL));
690 curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
691 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
693 my_headers = curl_slist_append(my_headers, "Accept:"); /* disable the default Accept: header */
694 my_headers = curl_slist_append(my_headers, "Accept: application/xrds+xml");
695 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, my_headers);
697 curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &x_xrds_location);
698 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, yadis_headerfunction);
700 result = curl_easy_perform(curl);
702 syslog(LOG_DEBUG, "libcurl error %d: %s", result, errmsg);
704 curl_slist_free_all(my_headers);
705 curl_easy_cleanup(curl);
706 docbytes = StrLength(ReplyBuf);
709 * The response from the server will be one of:
711 * Option 1: An HTML document with a <head> element that includes a <meta> element with http-equiv
712 * attribute, X-XRDS-Location,
714 * Does any provider actually do this? If so then we will implement it in the future.
718 * Option 2: HTTP response-headers that include an X-XRDS-Location response-header,
719 * together with a document.
720 * Option 3: HTTP response-headers only, which MAY include an X-XRDS-Location response-header,
721 * a contenttype response-header specifying MIME media type,
722 * application/xrds+xml, or both.
724 * If the X-XRDS-Location header was delivered, we know about it at this point...
726 if ( (x_xrds_location)
727 && (strcmp(ChrPtr(x_xrds_location), ChrPtr(SuppliedURL)))
729 syslog(LOG_DEBUG, "X-XRDS-Location: %s ... recursing!", ChrPtr(x_xrds_location));
730 return_value = perform_openid2_discovery(x_xrds_location);
731 FreeStrBuf(&x_xrds_location);
735 * Option 4: the returned web page may *be* an XRDS document. Try to parse it.
737 if ( (return_value == 0) && (docbytes >= 0)) {
738 return_value = parse_xrds_document(ReplyBuf);
742 * Option 5: if all else fails, attempt HTML based discovery.
744 if ( (return_value == 0) && (docbytes >= 0)) {
745 if (oiddata->op_url == NULL) {
746 oiddata->op_url = NewStrBuf();
748 extract_link(oiddata->op_url, HKEY("openid2.provider"), ReplyBuf);
749 if (StrLength(oiddata->op_url) > 0) {
750 return_value = openid_disco_html;
754 if (ReplyBuf != NULL) {
755 FreeStrBuf(&ReplyBuf);
757 return(return_value);
762 * Setup an OpenID authentication
764 void cmd_oids(char *argbuf) {
765 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
766 const char *Pos = NULL;
767 StrBuf *ArgBuf = NULL;
768 StrBuf *ReplyBuf = NULL;
769 StrBuf *return_to = NULL;
770 StrBuf *RedirectUrl = NULL;
771 ctdl_openid *oiddata;
772 int discovery_succeeded = 0;
774 Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
776 CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
777 if (oiddata == NULL) {
778 syslog(LOG_ALERT, "malloc() failed: %s", strerror(errno));
779 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
782 memset(oiddata, 0, sizeof(ctdl_openid));
783 CCC->openid_data = (void *) oiddata;
785 ArgBuf = NewStrBufPlain(argbuf, -1);
787 oiddata->verified = 0;
788 oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
789 return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
791 StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
792 StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
794 syslog(LOG_DEBUG, "User-Supplied Identifier is: %s", ChrPtr(oiddata->claimed_id));
796 /********** OpenID 2.0 section 7.3 - Discovery **********/
798 /* Section 7.3.1 says we have to attempt XRI based discovery.
799 * No one is using this, no one is asking for it, no one wants it.
800 * So we're not even going to bother attempting this mode.
803 /* Attempt section 7.3.2 (Yadis discovery) and section 7.3.3 (HTML discovery);
805 discovery_succeeded = perform_openid2_discovery(oiddata->claimed_id);
807 if (discovery_succeeded == 0) {
808 cprintf("%d There is no OpenID identity provider at this location.\n", ERROR);
813 * If we get to this point we are in possession of a valid OpenID Provider URL.
815 syslog(LOG_DEBUG, "OP URI '%s' discovered using method %d",
816 ChrPtr(oiddata->op_url),
820 /* We have to "normalize" our Claimed ID otherwise it will cause some OP's to barf */
821 if (cbmstrcasestr(ChrPtr(oiddata->claimed_id), "://") == NULL) {
822 StrBuf *cid = oiddata->claimed_id;
823 oiddata->claimed_id = NewStrBufPlain(HKEY("http://"));
824 StrBufAppendBuf(oiddata->claimed_id, cid, 0);
829 * OpenID 2.0 section 9: request authentication
830 * Assemble a URL to which the user-agent will be redirected.
833 RedirectUrl = NewStrBufDup(oiddata->op_url);
835 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.ns="), 0);
836 StrBufUrlescAppend(RedirectUrl, NULL, "http://specs.openid.net/auth/2.0");
838 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.mode=checkid_setup"), 0);
840 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.claimed_id="), 0);
841 StrBufUrlescAppend(RedirectUrl, oiddata->claimed_id, NULL);
843 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.identity="), 0);
844 StrBufUrlescAppend(RedirectUrl, oiddata->claimed_id, NULL);
846 /* return_to tells the provider how to complete the round trip back to our site */
847 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
848 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
850 /* Attribute Exchange
852 * http://openid.net/specs/openid-attribute-exchange-1_0.html
853 * http://code.google.com/apis/accounts/docs/OpenID.html#endpoint
854 * http://test-id.net/OP/AXFetch.aspx
857 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ns.ax="), 0);
858 StrBufUrlescAppend(RedirectUrl, NULL, "http://openid.net/srv/ax/1.0");
860 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.mode=fetch_request"), 0);
862 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.required=firstname,lastname,friendly,nickname"), 0);
864 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.firstname="), 0);
865 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/first");
867 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.lastname="), 0);
868 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/last");
870 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.friendly="), 0);
871 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/friendly");
873 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.nickname="), 0);
874 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/nickname");
876 syslog(LOG_DEBUG, "OpenID: redirecting client to %s", ChrPtr(RedirectUrl));
877 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
881 FreeStrBuf(&ReplyBuf);
882 FreeStrBuf(&return_to);
883 FreeStrBuf(&RedirectUrl);
888 * Finalize an OpenID authentication
890 void cmd_oidf(char *argbuf) {
895 HashList *keys = NULL;
898 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
900 if (oiddata == NULL) {
901 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
904 if (StrLength(oiddata->op_url) == 0){
905 cprintf("%d No OpenID Endpoint URL has been obtained.\n", ERROR + ILLEGAL_VALUE);
908 keys = NewHash(1, NULL);
910 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
913 cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
915 while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
916 len = extract_token(thiskey, buf, 0, '|', sizeof thiskey);
918 len = sizeof(thiskey) - 1;
920 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
921 Put(keys, thiskey, len, strdup(thisdata), NULL);
924 /* Check to see if this is a correct response.
925 * Start with verified=1 but then set it to 0 if anything looks wrong.
927 oiddata->verified = 1;
929 char *openid_ns = NULL;
930 if ( (!GetHash(keys, "ns", 2, (void *) &openid_ns))
931 || (strcasecmp(openid_ns, "http://specs.openid.net/auth/2.0"))
933 syslog(LOG_DEBUG, "This is not an an OpenID assertion");
934 oiddata->verified = 0;
937 char *openid_mode = NULL;
938 if ( (!GetHash(keys, "mode", 4, (void *) &openid_mode))
939 || (strcasecmp(openid_mode, "id_res"))
941 oiddata->verified = 0;
944 char *openid_claimed_id = NULL;
945 if (GetHash(keys, "claimed_id", 10, (void *) &openid_claimed_id)) {
946 FreeStrBuf(&oiddata->claimed_id);
947 oiddata->claimed_id = NewStrBufPlain(openid_claimed_id, -1);
948 syslog(LOG_DEBUG, "Provider is asserting the Claimed ID '%s'", ChrPtr(oiddata->claimed_id));
951 /* Validate the assertion against the server */
952 syslog(LOG_DEBUG, "Validating...");
956 struct curl_httppost *formpost = NULL;
957 struct curl_httppost *lastptr = NULL;
958 char errmsg[1024] = "";
959 StrBuf *ReplyBuf = NewStrBuf();
961 curl_formadd(&formpost, &lastptr,
962 CURLFORM_COPYNAME, "openid.mode",
963 CURLFORM_COPYCONTENTS, "check_authentication",
967 HashPos *HashPos = GetNewHashPos(keys, 0);
968 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value) != 0) {
969 syslog(LOG_DEBUG, "%s = %s", Key, (char *)Value);
970 if (strcasecmp(Key, "mode")) {
971 char k_o_keyname[1024];
972 snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", (const char *)Key);
973 curl_formadd(&formpost, &lastptr,
974 CURLFORM_COPYNAME, k_o_keyname,
975 CURLFORM_COPYCONTENTS, (char *)Value,
981 curl = ctdl_openid_curl_easy_init(errmsg);
982 curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->op_url));
983 curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
984 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
985 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
987 res = curl_easy_perform(curl);
989 syslog(LOG_DEBUG, "cmd_oidf() libcurl error %d: %s", res, errmsg);
990 oiddata->verified = 0;
992 curl_easy_cleanup(curl);
993 curl_formfree(formpost);
995 /* syslog(LOG_DEBUG, "Validation reply: \n%s", ChrPtr(ReplyBuf)); */
996 if (cbmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true") == NULL) {
997 oiddata->verified = 0;
999 FreeStrBuf(&ReplyBuf);
1001 syslog(LOG_DEBUG, "OpenID authentication %s", (oiddata->verified ? "succeeded" : "failed") );
1003 /* Respond to the client */
1005 if (oiddata->verified) {
1007 /* If we were already logged in, attach the OpenID to the user's account */
1008 if (CC->logged_in) {
1009 if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
1010 cprintf("attach\n");
1011 syslog(LOG_DEBUG, "OpenID attach succeeded");
1015 syslog(LOG_DEBUG, "OpenID attach failed");
1019 /* Otherwise, a user is attempting to log in using the verified OpenID */
1022 * Existing user who has claimed this OpenID?
1024 * Note: if you think that sending the password back over the wire is insecure,
1025 * check your assumptions. If someone has successfully asserted an OpenID that
1026 * is associated with the account, they already have password equivalency and can
1027 * login, so they could just as easily change the password, etc.
1029 if (login_via_openid(oiddata->claimed_id) == 0) {
1030 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1031 logged_in_response();
1032 syslog(LOG_DEBUG, "Logged in using previously claimed OpenID");
1036 * If this system does not allow self-service new user registration, the
1037 * remaining modes do not apply, so fail here and now.
1039 else if (config.c_disable_newu) {
1041 syslog(LOG_DEBUG, "Creating user failed due to local policy");
1045 * New user whose OpenID is verified and Attribute Exchange gave us a name?
1047 else if (openid_create_user_via_ax(oiddata->claimed_id, keys) == 0) {
1048 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1049 logged_in_response();
1050 syslog(LOG_DEBUG, "Successfully auto-created new user");
1054 * OpenID is verified, but the desired username either was not specified or
1055 * conflicts with an existing user. Manual account creation is required.
1058 char *desired_name = NULL;
1059 cprintf("verify_only\n");
1060 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
1061 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
1062 cprintf("%s\n", desired_name);
1067 syslog(LOG_DEBUG, "The desired display name is already taken.");
1076 if (oiddata->sreg_keys != NULL) {
1077 DeleteHash(&oiddata->sreg_keys);
1078 oiddata->sreg_keys = NULL;
1080 oiddata->sreg_keys = keys;
1085 /**************************************************************************/
1087 /* Functions in this section handle module initialization and shutdown */
1089 /**************************************************************************/
1094 CTDL_MODULE_INIT(openid_rp)
1097 curl_global_init(CURL_GLOBAL_ALL);
1099 /* Only enable the OpenID command set when native mode authentication is in use. */
1100 if (config.c_auth_mode == AUTHMODE_NATIVE) {
1101 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
1102 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
1103 CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
1104 CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
1105 CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
1106 CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
1108 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
1109 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
1110 openid_level_supported = 1; /* This module supports OpenID 1.0 only */
1113 /* return our module name for the log */