2 * This is an implementation of OpenID 2.0 relying party support in stateless mode.
4 * Copyright (c) 2007-2020 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>
33 #include <curl/curl.h>
35 #include "ctdl_module.h"
37 #include "citserver.h"
40 typedef struct _ctdl_openid {
41 StrBuf *op_url; /* OpenID Provider Endpoint URL */
42 StrBuf *claimed_id; /* Claimed Identifier */
54 void Free_ctdl_openid(ctdl_openid **FreeMe)
56 if (*FreeMe == NULL) {
59 FreeStrBuf(&(*FreeMe)->op_url);
60 FreeStrBuf(&(*FreeMe)->claimed_id);
61 DeleteHash(&(*FreeMe)->sreg_keys);
68 * This cleanup function blows away the temporary memory used by this module.
70 void openid_cleanup_function(void) {
71 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
73 if (CCC->openid_data != NULL) {
74 syslog(LOG_DEBUG, "openid: Clearing OpenID session state");
75 Free_ctdl_openid((ctdl_openid **) &CCC->openid_data);
80 /**************************************************************************/
82 /* Functions in this section handle Citadel internal OpenID mapping stuff */
84 /**************************************************************************/
88 * The structure of an openid record *key* is:
90 * |--------------claimed_id-------------|
91 * (actual length of claimed id)
94 * The structure of an openid record *value* is:
96 * |-----user_number----|------------claimed_id---------------|
97 * (sizeof long) (actual length of claimed id)
104 * Attach an external authenticator (such as an OpenID) to a Citadel account
106 int attach_extauth(struct ctdluser *who, StrBuf *claimed_id)
108 struct cdbdata *cdboi;
109 long fetched_usernum;
115 if (StrLength(claimed_id)==0) return(1);
117 /* Check to see if this authenticator is already in the database */
119 cdboi = cdb_fetch(CDB_EXTAUTH, ChrPtr(claimed_id), StrLength(claimed_id));
121 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
124 if (fetched_usernum == who->usernum) {
125 syslog(LOG_INFO, "openid: %s already associated; no action is taken", ChrPtr(claimed_id));
129 syslog(LOG_INFO, "openid: %s already belongs to another user", ChrPtr(claimed_id));
134 /* Not already in the database, so attach it now */
136 data_len = sizeof(long) + StrLength(claimed_id) + 1;
137 data = malloc(data_len);
139 memcpy(data, &who->usernum, sizeof(long));
140 memcpy(&data[sizeof(long)], ChrPtr(claimed_id), StrLength(claimed_id) + 1);
142 cdb_store(CDB_EXTAUTH, ChrPtr(claimed_id), StrLength(claimed_id), data, data_len);
145 snprintf(buf, sizeof buf, "User <%s> (#%ld) is now associated with %s\n", who->fullname, who->usernum, ChrPtr(claimed_id));
146 CtdlAideMessage(buf, "External authenticator claim");
147 syslog(LOG_INFO, "openid: %s", buf);
153 * When a user is being deleted, we have to delete any OpenID associations
155 void extauth_purge(struct ctdluser *usbuf) {
156 struct cdbdata *cdboi;
157 HashList *keys = NULL;
159 char *deleteme = NULL;
165 keys = NewHash(1, NULL);
168 cdb_rewind(CDB_EXTAUTH);
169 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
170 if (cdboi->len > sizeof(long)) {
171 memcpy(&usernum, cdboi->ptr, sizeof(long));
172 if (usernum == usbuf->usernum) {
173 deleteme = strdup(cdboi->ptr + sizeof(long)),
174 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
180 /* Go through the hash list, deleting keys we stored in it */
182 HashPos = GetNewHashPos(keys, 0);
183 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
185 syslog(LOG_DEBUG, "openid: deleting associated external authenticator <%s>", (char*)Value);
186 cdb_delete(CDB_EXTAUTH, Value, strlen(Value));
187 /* note: don't free(Value) -- deleting the hash list will handle this for us */
189 DeleteHashPos(&HashPos);
195 * List the OpenIDs associated with the currently logged in account
197 void cmd_oidl(char *argbuf) {
198 struct cdbdata *cdboi;
201 if (CtdlGetConfigInt("c_disable_newu"))
203 cprintf("%d this system does not support openid.\n", ERROR + CMD_NOT_SUPPORTED);
206 if (CtdlAccessCheck(ac_logged_in)) return;
208 cdb_rewind(CDB_EXTAUTH);
209 cprintf("%d Associated external authenticators:\n", LISTING_FOLLOWS);
211 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
212 if (cdboi->len > sizeof(long)) {
213 memcpy(&usernum, cdboi->ptr, sizeof(long));
214 if (usernum == CC->user.usernum) {
215 cprintf("%s\n", cdboi->ptr + sizeof(long));
225 * List ALL OpenIDs in the database
227 void cmd_oida(char *argbuf) {
228 struct cdbdata *cdboi;
230 struct ctdluser usbuf;
232 if (CtdlGetConfigInt("c_disable_newu"))
234 cprintf("%d this system does not support openid.\n",
235 ERROR + CMD_NOT_SUPPORTED);
238 if (CtdlAccessCheck(ac_aide)) return;
239 cdb_rewind(CDB_EXTAUTH);
240 cprintf("%d List of all OpenIDs in the database:\n", LISTING_FOLLOWS);
242 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
243 if (cdboi->len > sizeof(long)) {
244 memcpy(&usernum, cdboi->ptr, sizeof(long));
245 if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
246 usbuf.fullname[0] = 0;
248 cprintf("%s|%ld|%s\n",
249 cdboi->ptr + sizeof(long),
261 * Create a new user account, manually specifying the name, after successfully
262 * verifying an OpenID (which will of course be attached to the account)
264 void cmd_oidc(char *argbuf) {
265 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
267 if (CtdlGetConfigInt("c_disable_newu"))
269 cprintf("%d this system does not support openid.\n",
270 ERROR + CMD_NOT_SUPPORTED);
273 if ( (!oiddata) || (!oiddata->verified) ) {
274 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
278 /* We can make the semantics of OIDC exactly the same as NEWU, simply
279 * by _calling_ cmd_newu() and letting it run. Very clever!
283 /* Now, if this logged us in, we have to attach the OpenID */
285 attach_extauth(&CC->user, oiddata->claimed_id);
292 * Detach an OpenID from the currently logged in account
294 void cmd_oidd(char *argbuf) {
295 struct cdbdata *cdboi;
296 char id_to_detach[1024];
297 int this_is_mine = 0;
300 if (CtdlGetConfigInt("c_disable_newu"))
302 cprintf("%d this system does not support openid.\n",
303 ERROR + CMD_NOT_SUPPORTED);
306 if (CtdlAccessCheck(ac_logged_in)) return;
307 extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
308 if (IsEmptyStr(id_to_detach)) {
309 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
312 cdb_rewind(CDB_EXTAUTH);
313 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
314 if (cdboi->len > sizeof(long)) {
315 memcpy(&usernum, cdboi->ptr, sizeof(long));
316 if (usernum == CC->user.usernum) {
324 cprintf("%d That OpenID was not found or not associated with your account.\n",
325 ERROR + ILLEGAL_VALUE);
329 cdb_delete(CDB_EXTAUTH, id_to_detach, strlen(id_to_detach));
330 cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
335 * Attempt to auto-create a new Citadel account using the nickname from Attribute Exchange
337 int openid_create_user_via_ax(StrBuf *claimed_id, HashList *sreg_keys)
339 char *nickname = NULL;
340 char *firstname = NULL;
341 char *lastname = NULL;
342 char new_password[32];
347 if (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_NATIVE) return(1);
348 if (CtdlGetConfigInt("c_disable_newu")) return(2);
349 if (CC->logged_in) return(3);
351 HashPos *HashPos = GetNewHashPos(sreg_keys, 0);
352 while (GetNextHashPos(sreg_keys, HashPos, &len, &Key, &Value) != 0) {
353 syslog(LOG_DEBUG, "openid: %s = %s", Key, (char *)Value);
355 if (cbmstrcasestr(Key, "value.nickname") != NULL) {
356 nickname = (char *)Value;
358 else if ( (nickname == NULL) && (cbmstrcasestr(Key, "value.nickname") != NULL)) {
359 nickname = (char *)Value;
361 else if (cbmstrcasestr(Key, "value.firstname") != NULL) {
362 firstname = (char *)Value;
364 else if (cbmstrcasestr(Key, "value.lastname") != NULL) {
365 lastname = (char *)Value;
369 DeleteHashPos(&HashPos);
371 if (nickname == NULL) {
372 if ((firstname != NULL) || (lastname != NULL)) {
373 char fullname[1024] = "";
374 if (firstname) strcpy(fullname, firstname);
375 if (firstname && lastname) strcat(fullname, " ");
376 if (lastname) strcat(fullname, lastname);
381 if (nickname == NULL) {
384 syslog(LOG_DEBUG, "openid: the desired account name is <%s>", nickname);
386 if (!CtdlGetUser(&CC->user, nickname)) {
387 syslog(LOG_DEBUG, "openid: <%s> is already taken by another user.", nickname);
388 memset(&CC->user, 0, sizeof(struct ctdluser));
392 /* The desired account name is available. Create the account and log it in! */
393 if (create_user(nickname, CREATE_USER_BECOME_USER, NATIVE_AUTH_UID)) return(6);
395 /* Generate a random password.
396 * The user doesn't care what the password is since he is using OpenID.
398 snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
399 CtdlSetPassword(new_password);
401 /* Now attach the verified OpenID to this account. */
402 attach_extauth(&CC->user, claimed_id);
409 * If a user account exists which is associated with the Claimed ID, log it in and return zero.
410 * Otherwise it returns nonzero.
412 int login_via_extauth(StrBuf *claimed_id)
414 struct cdbdata *cdboi;
417 cdboi = cdb_fetch(CDB_EXTAUTH, ChrPtr(claimed_id), StrLength(claimed_id));
422 memcpy(&usernum, cdboi->ptr, sizeof(long));
425 if (!CtdlGetUserByNumber(&CC->user, usernum)) {
426 /* Now become the user we just created */
427 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
432 memset(&CC->user, 0, sizeof(struct ctdluser));
440 /**************************************************************************/
442 /* Functions in this section handle OpenID protocol */
444 /**************************************************************************/
448 * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
450 void extract_link(StrBuf *target_buf, const char *rel, long repllen, StrBuf *source_buf)
454 const char *href_start = NULL;
455 const char *href_end = NULL;
456 const char *link_tag_start = NULL;
457 const char *link_tag_end = NULL;
458 const char *rel_start = NULL;
459 const char *rel_end = NULL;
461 if (!target_buf) return;
463 if (!source_buf) return;
465 ptr = ChrPtr(source_buf);
467 FlushStrBuf(target_buf);
468 while (ptr = cbmstrcasestr(ptr, "<link"), ptr != NULL) {
470 link_tag_start = ptr;
471 link_tag_end = strchr(ptr, '>');
472 if (link_tag_end == NULL)
474 for (i=0; i < 1; i++ ){
475 rel_start = cbmstrcasestr(link_tag_start, "rel=");
476 if ((rel_start == NULL) ||
477 (rel_start > link_tag_end))
480 rel_start = strchr(rel_start, '\"');
481 if ((rel_start == NULL) ||
482 (rel_start > link_tag_end))
485 rel_end = strchr(rel_start, '\"');
486 if ((rel_end == NULL) ||
487 (rel_end == rel_start) ||
488 (rel_end >= link_tag_end) )
490 if (strncasecmp(rel, rel_start, repllen)!= 0)
491 continue; /* didn't match? never mind... */
493 href_start = cbmstrcasestr(link_tag_start, "href=");
494 if ((href_start == NULL) ||
495 (href_start >= link_tag_end))
497 href_start = strchr(href_start, '\"');
498 if ((href_start == NULL) |
499 (href_start >= link_tag_end))
502 href_end = strchr(href_start, '\"');
503 if ((href_end == NULL) ||
504 (href_end == href_start) ||
505 (href_start >= link_tag_end))
507 StrBufPlain(target_buf, href_start, href_end - href_start);
515 * Wrapper for curl_easy_init() that includes the options common to all calls
516 * used in this module.
518 CURL *ctdl_openid_curl_easy_init(char *errmsg) {
521 curl = curl_easy_init();
526 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
527 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
530 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
532 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
533 #ifdef CURLOPT_HTTP_CONTENT_DECODING
534 curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
535 curl_easy_setopt(curl, CURLOPT_ENCODING, "");
537 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
538 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30); /* die after 30 seconds */
541 (!IsEmptyStr(CtdlGetConfigStr("c_ip_addr")))
542 && (strcmp(CtdlGetConfigStr("c_ip_addr"), "*"))
543 && (strcmp(CtdlGetConfigStr("c_ip_addr"), "::"))
544 && (strcmp(CtdlGetConfigStr("c_ip_addr"), "0.0.0.0"))
546 curl_easy_setopt(curl, CURLOPT_INTERFACE, CtdlGetConfigStr("c_ip_addr"));
557 int current_service_priority;
558 int selected_service_priority;
559 StrBuf *current_service_uri;
560 StrBuf *selected_service_uri;
561 int current_service_is_oid2auth;
565 void xrds_xml_start(void *data, const char *supplied_el, const char **attr) {
566 struct xrds *xrds = (struct xrds *) data;
569 ++xrds->nesting_level;
571 if (!strcasecmp(supplied_el, "XRD")) {
575 else if (!strcasecmp(supplied_el, "service")) {
576 xrds->current_service_priority = 0;
577 xrds->current_service_is_oid2auth = 0;
578 for (i=0; attr[i] != NULL; i+=2) {
579 if (!strcasecmp(attr[i], "priority")) {
580 xrds->current_service_priority = atoi(attr[i+1]);
585 FlushStrBuf(xrds->CharData);
589 void xrds_xml_end(void *data, const char *supplied_el) {
590 struct xrds *xrds = (struct xrds *) data;
592 --xrds->nesting_level;
594 if (!strcasecmp(supplied_el, "XRD")) {
598 else if (!strcasecmp(supplied_el, "type")) {
600 && (!strcasecmp(ChrPtr(xrds->CharData), "http://specs.openid.net/auth/2.0/server"))
602 xrds->current_service_is_oid2auth = 1;
605 && (!strcasecmp(ChrPtr(xrds->CharData), "http://specs.openid.net/auth/2.0/signon"))
607 xrds->current_service_is_oid2auth = 1;
608 /* FIXME in this case, the Claimed ID should be considered immutable */
612 else if (!strcasecmp(supplied_el, "uri")) {
614 FlushStrBuf(xrds->current_service_uri);
615 StrBufAppendBuf(xrds->current_service_uri, xrds->CharData, 0);
619 else if (!strcasecmp(supplied_el, "service")) {
621 && (xrds->current_service_priority < xrds->selected_service_priority)
622 && (xrds->current_service_is_oid2auth)
624 xrds->selected_service_priority = xrds->current_service_priority;
625 FlushStrBuf(xrds->selected_service_uri);
626 StrBufAppendBuf(xrds->selected_service_uri, xrds->current_service_uri, 0);
631 FlushStrBuf(xrds->CharData);
635 void xrds_xml_chardata(void *data, const XML_Char *s, int len) {
636 struct xrds *xrds = (struct xrds *) data;
638 StrBufAppendBufPlain (xrds->CharData, s, len, 0);
643 * Parse an XRDS document.
644 * If an OpenID Provider URL is discovered, op_url to that value and return nonzero.
645 * If nothing useful happened, return 0.
647 int parse_xrds_document(StrBuf *ReplyBuf) {
648 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
650 int return_value = 0;
652 memset(&xrds, 0, sizeof (struct xrds));
653 xrds.selected_service_priority = INT_MAX;
654 xrds.CharData = NewStrBuf();
655 xrds.current_service_uri = NewStrBuf();
656 xrds.selected_service_uri = NewStrBuf();
657 XML_Parser xp = XML_ParserCreate(NULL);
659 XML_SetUserData(xp, &xrds);
660 XML_SetElementHandler(xp, xrds_xml_start, xrds_xml_end);
661 XML_SetCharacterDataHandler(xp, xrds_xml_chardata);
662 XML_Parse(xp, ChrPtr(ReplyBuf), StrLength(ReplyBuf), 0);
663 XML_Parse(xp, "", 0, 1);
667 syslog(LOG_ERR, "openid: cannot create XML parser");
670 if (xrds.selected_service_priority < INT_MAX) {
671 if (oiddata->op_url == NULL) {
672 oiddata->op_url = NewStrBuf();
674 FlushStrBuf(oiddata->op_url);
675 StrBufAppendBuf(oiddata->op_url, xrds.selected_service_uri, 0);
676 return_value = openid_disco_xrds;
679 FreeStrBuf(&xrds.CharData);
680 FreeStrBuf(&xrds.current_service_uri);
681 FreeStrBuf(&xrds.selected_service_uri);
683 return(return_value);
688 * Callback function for perform_openid2_discovery()
689 * We're interested in the X-XRDS-Location: header.
691 size_t yadis_headerfunction(void *ptr, size_t size, size_t nmemb, void *userdata) {
693 StrBuf **x_xrds_location = (StrBuf **) userdata;
695 memcpy(hdr, ptr, (size*nmemb));
698 if (!strncasecmp(hdr, "X-XRDS-Location:", 16)) {
699 *x_xrds_location = NewStrBufPlain(&hdr[16], ((size*nmemb)-16));
700 StrBufTrim(*x_xrds_location);
703 return(size * nmemb);
707 /* Attempt to perform Yadis discovery as specified in Yadis 1.0 section 6.2.5.
709 * If Yadis fails, we then attempt HTML discovery using the same document.
711 * If successful, returns nonzero and calls parse_xrds_document() to act upon the received data.
712 * If fails, returns 0 and does nothing else.
714 int perform_openid2_discovery(StrBuf *SuppliedURL) {
715 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
717 StrBuf *ReplyBuf = NULL;
718 int return_value = 0;
721 char errmsg[1024] = "";
722 struct curl_slist *my_headers = NULL;
723 StrBuf *x_xrds_location = NULL;
725 if (!SuppliedURL) return(0);
726 syslog(LOG_DEBUG, "openid: perform_openid2_discovery(%s)", ChrPtr(SuppliedURL));
727 if (StrLength(SuppliedURL) == 0) return(0);
729 ReplyBuf = NewStrBuf();
730 if (!ReplyBuf) return(0);
732 curl = ctdl_openid_curl_easy_init(errmsg);
733 if (!curl) return(0);
735 curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(SuppliedURL));
736 curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
737 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
739 my_headers = curl_slist_append(my_headers, "Accept:"); /* disable the default Accept: header */
740 my_headers = curl_slist_append(my_headers, "Accept: application/xrds+xml");
741 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, my_headers);
743 curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &x_xrds_location);
744 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, yadis_headerfunction);
746 result = curl_easy_perform(curl);
748 syslog(LOG_DEBUG, "openid: libcurl error %d: %s", result, errmsg);
750 curl_slist_free_all(my_headers);
751 curl_easy_cleanup(curl);
752 docbytes = StrLength(ReplyBuf);
755 * The response from the server will be one of:
757 * Option 1: An HTML document with a <head> element that includes a <meta> element with http-equiv
758 * attribute, X-XRDS-Location,
760 * Does any provider actually do this? If so then we will implement it in the future.
764 * Option 2: HTTP response-headers that include an X-XRDS-Location response-header,
765 * together with a document.
766 * Option 3: HTTP response-headers only, which MAY include an X-XRDS-Location response-header,
767 * a contenttype response-header specifying MIME media type,
768 * application/xrds+xml, or both.
770 * If the X-XRDS-Location header was delivered, we know about it at this point...
772 if ( (x_xrds_location)
773 && (strcmp(ChrPtr(x_xrds_location), ChrPtr(SuppliedURL)))
775 syslog(LOG_DEBUG, "openid: X-XRDS-Location: %s ... recursing!", ChrPtr(x_xrds_location));
776 return_value = perform_openid2_discovery(x_xrds_location);
777 FreeStrBuf(&x_xrds_location);
781 * Option 4: the returned web page may *be* an XRDS document. Try to parse it.
783 if ( (return_value == 0) && (docbytes >= 0)) {
784 return_value = parse_xrds_document(ReplyBuf);
788 * Option 5: if all else fails, attempt HTML based discovery.
790 if ( (return_value == 0) && (docbytes >= 0)) {
791 if (oiddata->op_url == NULL) {
792 oiddata->op_url = NewStrBuf();
794 extract_link(oiddata->op_url, HKEY("openid2.provider"), ReplyBuf);
795 if (StrLength(oiddata->op_url) > 0) {
796 return_value = openid_disco_html;
800 if (ReplyBuf != NULL) {
801 FreeStrBuf(&ReplyBuf);
803 return(return_value);
808 * Setup an OpenID authentication
810 void cmd_oids(char *argbuf) {
811 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
812 const char *Pos = NULL;
813 StrBuf *ArgBuf = NULL;
814 StrBuf *ReplyBuf = NULL;
815 StrBuf *return_to = NULL;
816 StrBuf *RedirectUrl = NULL;
817 ctdl_openid *oiddata;
818 int discovery_succeeded = 0;
820 if (CtdlGetConfigInt("c_disable_newu"))
822 cprintf("%d this system does not support openid.\n",
823 ERROR + CMD_NOT_SUPPORTED);
826 Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
828 CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
829 if (oiddata == NULL) {
830 syslog(LOG_ERR, "openid: malloc() failed: %m");
831 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
834 memset(oiddata, 0, sizeof(ctdl_openid));
836 ArgBuf = NewStrBufPlain(argbuf, -1);
838 oiddata->verified = 0;
839 oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
840 return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
842 StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
843 StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
845 syslog(LOG_DEBUG, "openid: user-Supplied Identifier is: %s", ChrPtr(oiddata->claimed_id));
847 /********** OpenID 2.0 section 7.3 - Discovery **********/
849 /* Section 7.3.1 says we have to attempt XRI based discovery.
850 * No one is using this, no one is asking for it, no one wants it.
851 * So we're not even going to bother attempting this mode.
854 /* Attempt section 7.3.2 (Yadis discovery) and section 7.3.3 (HTML discovery);
856 discovery_succeeded = perform_openid2_discovery(oiddata->claimed_id);
858 if (discovery_succeeded == 0) {
859 cprintf("%d There is no OpenID identity provider at this location.\n", ERROR);
864 * If we get to this point we are in possession of a valid OpenID Provider URL.
866 syslog(LOG_DEBUG, "openid: OP URI '%s' discovered using method %d",
867 ChrPtr(oiddata->op_url),
871 /* We have to "normalize" our Claimed ID otherwise it will cause some OP's to barf */
872 if (cbmstrcasestr(ChrPtr(oiddata->claimed_id), "://") == NULL) {
873 StrBuf *cid = oiddata->claimed_id;
874 oiddata->claimed_id = NewStrBufPlain(HKEY("http://"));
875 StrBufAppendBuf(oiddata->claimed_id, cid, 0);
880 * OpenID 2.0 section 9: request authentication
881 * Assemble a URL to which the user-agent will be redirected.
884 RedirectUrl = NewStrBufDup(oiddata->op_url);
886 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.ns="), 0);
887 StrBufUrlescAppend(RedirectUrl, NULL, "http://specs.openid.net/auth/2.0");
889 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.mode=checkid_setup"), 0);
891 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.claimed_id="), 0);
892 StrBufUrlescAppend(RedirectUrl, oiddata->claimed_id, NULL);
894 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.identity="), 0);
895 StrBufUrlescAppend(RedirectUrl, oiddata->claimed_id, NULL);
897 /* return_to tells the provider how to complete the round trip back to our site */
898 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
899 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
901 /* Attribute Exchange
903 * http://openid.net/specs/openid-attribute-exchange-1_0.html
904 * http://code.google.com/apis/accounts/docs/OpenID.html#endpoint
905 * http://test-id.net/OP/AXFetch.aspx
908 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ns.ax="), 0);
909 StrBufUrlescAppend(RedirectUrl, NULL, "http://openid.net/srv/ax/1.0");
911 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.mode=fetch_request"), 0);
913 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.required=firstname,lastname,friendly,nickname"), 0);
915 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.firstname="), 0);
916 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/first");
918 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.lastname="), 0);
919 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/last");
921 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.friendly="), 0);
922 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/friendly");
924 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.nickname="), 0);
925 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/nickname");
927 syslog(LOG_DEBUG, "openid: redirecting client to %s", ChrPtr(RedirectUrl));
928 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
932 FreeStrBuf(&ReplyBuf);
933 FreeStrBuf(&return_to);
934 FreeStrBuf(&RedirectUrl);
939 * Finalize an OpenID authentication
941 void cmd_oidf(char *argbuf) {
946 HashList *keys = NULL;
949 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
951 if (CtdlGetConfigInt("c_disable_newu"))
953 cprintf("%d this system does not support openid.\n",
954 ERROR + CMD_NOT_SUPPORTED);
957 if (oiddata == NULL) {
958 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
961 if (StrLength(oiddata->op_url) == 0){
962 cprintf("%d No OpenID Endpoint URL has been obtained.\n", ERROR + ILLEGAL_VALUE);
965 keys = NewHash(1, NULL);
967 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
970 cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
972 while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
973 len = extract_token(thiskey, buf, 0, '|', sizeof thiskey);
975 len = sizeof(thiskey) - 1;
977 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
978 Put(keys, thiskey, len, strdup(thisdata), NULL);
981 /* Check to see if this is a correct response.
982 * Start with verified=1 but then set it to 0 if anything looks wrong.
984 oiddata->verified = 1;
986 char *openid_ns = NULL;
987 if ( (!GetHash(keys, "ns", 2, (void *) &openid_ns))
988 || (strcasecmp(openid_ns, "http://specs.openid.net/auth/2.0"))
990 syslog(LOG_DEBUG, "openid: this is not an an OpenID assertion");
991 oiddata->verified = 0;
994 char *openid_mode = NULL;
995 if ( (!GetHash(keys, "mode", 4, (void *) &openid_mode))
996 || (strcasecmp(openid_mode, "id_res"))
998 oiddata->verified = 0;
1001 char *openid_claimed_id = NULL;
1002 if (GetHash(keys, "claimed_id", 10, (void *) &openid_claimed_id)) {
1003 FreeStrBuf(&oiddata->claimed_id);
1004 oiddata->claimed_id = NewStrBufPlain(openid_claimed_id, -1);
1005 syslog(LOG_DEBUG, "openid: provider is asserting the Claimed ID '%s'", ChrPtr(oiddata->claimed_id));
1008 /* Validate the assertion against the server */
1009 syslog(LOG_DEBUG, "openid: validating...");
1013 struct curl_httppost *formpost = NULL;
1014 struct curl_httppost *lastptr = NULL;
1015 char errmsg[1024] = "";
1016 StrBuf *ReplyBuf = NewStrBuf();
1018 curl_formadd(&formpost, &lastptr,
1019 CURLFORM_COPYNAME, "openid.mode",
1020 CURLFORM_COPYCONTENTS, "check_authentication",
1024 HashPos *HashPos = GetNewHashPos(keys, 0);
1025 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value) != 0) {
1026 if (strcasecmp(Key, "mode")) {
1027 char k_o_keyname[1024];
1028 snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", (const char *)Key);
1029 curl_formadd(&formpost, &lastptr,
1030 CURLFORM_COPYNAME, k_o_keyname,
1031 CURLFORM_COPYCONTENTS, (char *)Value,
1036 DeleteHashPos(&HashPos);
1038 curl = ctdl_openid_curl_easy_init(errmsg);
1039 curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->op_url));
1040 curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
1041 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
1042 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
1044 res = curl_easy_perform(curl);
1046 syslog(LOG_DEBUG, "openid: cmd_oidf() libcurl error %d: %s", res, errmsg);
1047 oiddata->verified = 0;
1049 curl_easy_cleanup(curl);
1050 curl_formfree(formpost);
1052 if (cbmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true") == NULL) {
1053 oiddata->verified = 0;
1055 FreeStrBuf(&ReplyBuf);
1057 syslog(LOG_DEBUG, "openid: authentication %s", (oiddata->verified ? "succeeded" : "failed") );
1059 /* Respond to the client */
1061 if (oiddata->verified) {
1063 /* If we were already logged in, attach the OpenID to the user's account */
1064 if (CC->logged_in) {
1065 if (attach_extauth(&CC->user, oiddata->claimed_id) == 0) {
1066 cprintf("attach\n");
1067 syslog(LOG_DEBUG, "openid: attach succeeded");
1071 syslog(LOG_DEBUG, "openid: attach failed");
1075 /* Otherwise, a user is attempting to log in using the verified OpenID */
1078 * Existing user who has claimed this OpenID?
1080 * Note: if you think that sending the password back over the wire is insecure,
1081 * check your assumptions. If someone has successfully asserted an OpenID that
1082 * is associated with the account, they already have password equivalency and can
1083 * login, so they could just as easily change the password, etc.
1085 if (login_via_extauth(oiddata->claimed_id) == 0) {
1086 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1087 logged_in_response();
1088 syslog(LOG_DEBUG, "openid: logged in using previously claimed OpenID");
1092 * If this system does not allow self-service new user registration, the
1093 * remaining modes do not apply, so fail here and now.
1095 else if (CtdlGetConfigInt("c_disable_newu")) {
1097 syslog(LOG_DEBUG, "openid: creating user failed due to local policy");
1101 * New user whose OpenID is verified and Attribute Exchange gave us a name?
1103 else if (openid_create_user_via_ax(oiddata->claimed_id, keys) == 0) {
1104 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1105 logged_in_response();
1106 syslog(LOG_DEBUG, "openid: successfully auto-created new user");
1110 * OpenID is verified, but the desired username either was not specified or
1111 * conflicts with an existing user. Manual account creation is required.
1114 char *desired_name = NULL;
1115 cprintf("verify_only\n");
1116 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
1117 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
1118 cprintf("%s\n", desired_name);
1123 syslog(LOG_DEBUG, "openid: the desired display name is already taken.");
1132 if (oiddata->sreg_keys != NULL) {
1133 DeleteHash(&oiddata->sreg_keys);
1134 oiddata->sreg_keys = NULL;
1136 oiddata->sreg_keys = keys;
1141 /**************************************************************************/
1143 /* Functions in this section handle module initialization and shutdown */
1145 /**************************************************************************/
1150 CTDL_MODULE_INIT(openid_rp)
1154 /* Only enable the OpenID command set when native mode authentication is in use. */
1155 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_NATIVE) {
1156 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
1157 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
1158 CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
1159 CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
1160 CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
1161 CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
1163 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT, PRIO_LOGOUT + 10);
1164 CtdlRegisterUserHook(extauth_purge, EVT_PURGEUSER);
1165 openid_level_supported = 1; /* This module supports OpenID 1.0 only */
1168 /* return our module name for the log */