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 * Attempt to register (populate the vCard) the currently-logged-in user
263 * using the data from Simple Registration Extension, if present.
265 void populate_vcard_from_sreg(HashList *sreg_keys) {
268 int pop = 0; /* number of fields populated */
270 char *postcode = NULL;
271 char *country = NULL;
273 if (!sreg_keys) return;
277 if (GetHash(sreg_keys, "identity", 8, (void *) &data)) {
278 vcard_add_prop(v, "url;type=openid", data);
282 if (GetHash(sreg_keys, "sreg.email", 10, (void *) &data)) {
283 vcard_add_prop(v, "email;internet", data);
287 if (GetHash(sreg_keys, "sreg.nickname", 13, (void *) &data)) {
288 vcard_add_prop(v, "nickname", data);
292 if (GetHash(sreg_keys, "sreg.fullname", 13, (void *) &data)) {
294 vcard_add_prop(v, "fn", data);
295 vcard_fn_to_n(n, data, sizeof n);
296 vcard_add_prop(v, "n", n);
300 if (!GetHash(sreg_keys, "sreg.postcode", 13, (void *) &postcode)) {
304 if (!GetHash(sreg_keys, "sreg.country", 12, (void *) &country)) {
308 if (postcode || country) {
310 snprintf(adr, sizeof adr, ";;;;;%s;%s",
311 (postcode ? postcode : ""),
312 (country ? country : "")
314 vcard_add_prop(v, "adr", adr);
318 if (GetHash(sreg_keys, "sreg.dob", 8, (void *) &data)) {
319 vcard_add_prop(v, "bday", data);
323 if (GetHash(sreg_keys, "sreg.gender", 11, (void *) &data)) {
324 vcard_add_prop(v, "x-funambol-gender", data);
328 /* Only save the vCard if there is some useful data in it */
331 ser = vcard_serialize(v);
333 CtdlWriteObject(USERCONFIGROOM, "text/x-vcard",
334 ser, strlen(ser)+1, &CC->user, 0, 0, 0
344 * Create a new user account, manually specifying the name, after successfully
345 * verifying an OpenID (which will of course be attached to the account)
347 void cmd_oidc(char *argbuf) {
348 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
350 if ( (!oiddata) || (!oiddata->verified) ) {
351 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
355 /* We can make the semantics of OIDC exactly the same as NEWU, simply
356 * by _calling_ cmd_newu() and letting it run. Very clever!
360 /* Now, if this logged us in, we have to attach the OpenID */
362 attach_openid(&CC->user, oiddata->claimed_id);
363 if (oiddata->sreg_keys != NULL) {
364 populate_vcard_from_sreg(oiddata->sreg_keys);
372 * Detach an OpenID from the currently logged in account
374 void cmd_oidd(char *argbuf) {
375 struct cdbdata *cdboi;
376 char id_to_detach[1024];
377 int this_is_mine = 0;
380 if (CtdlAccessCheck(ac_logged_in)) return;
381 extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
382 if (IsEmptyStr(id_to_detach)) {
383 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
386 cdb_rewind(CDB_OPENID);
387 while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
388 if (cdboi->len > sizeof(long)) {
389 memcpy(&usernum, cdboi->ptr, sizeof(long));
390 if (usernum == CC->user.usernum) {
398 cprintf("%d That OpenID was not found or not associated with your account.\n",
399 ERROR + ILLEGAL_VALUE);
403 cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
404 cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
409 * Attempt to auto-create a new Citadel account using the nickname from Simple Registration Extension
411 int openid_create_user_via_sreg(StrBuf *claimed_id, HashList *sreg_keys)
413 char *desired_name = NULL;
414 char new_password[32];
417 if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
418 if (config.c_disable_newu) return(2);
419 if (CC->logged_in) return(3);
420 if (!GetHash(sreg_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
422 syslog(LOG_DEBUG, "The desired account name is <%s>", desired_name);
424 len = cutuserkey(desired_name);
425 if (!CtdlGetUser(&CC->user, desired_name)) {
426 syslog(LOG_DEBUG, "<%s> is already taken by another user.", desired_name);
427 memset(&CC->user, 0, sizeof(struct ctdluser));
431 /* The desired account name is available. Create the account and log it in! */
432 if (create_user(desired_name, len, 1)) return(6);
434 snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
435 CtdlSetPassword(new_password);
436 attach_openid(&CC->user, claimed_id);
437 populate_vcard_from_sreg(sreg_keys);
443 * If a user account exists which is associated with the Claimed ID, log it in and return zero.
444 * Otherwise it returns nonzero.
446 int login_via_openid(StrBuf *claimed_id)
448 struct cdbdata *cdboi;
451 cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
456 memcpy(&usernum, cdboi->ptr, sizeof(long));
459 if (!CtdlGetUserByNumber(&CC->user, usernum)) {
460 /* Now become the user we just created */
461 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
466 memset(&CC->user, 0, sizeof(struct ctdluser));
474 /**************************************************************************/
476 /* Functions in this section handle OpenID protocol */
478 /**************************************************************************/
482 * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
484 void extract_link(StrBuf *target_buf, const char *rel, long repllen, StrBuf *source_buf)
488 const char *href_start = NULL;
489 const char *href_end = NULL;
490 const char *link_tag_start = NULL;
491 const char *link_tag_end = NULL;
492 const char *rel_start = NULL;
493 const char *rel_end = NULL;
495 if (!target_buf) return;
497 if (!source_buf) return;
499 ptr = ChrPtr(source_buf);
501 FlushStrBuf(target_buf);
502 while (ptr = cbmstrcasestr(ptr, "<link"), ptr != NULL) {
504 link_tag_start = ptr;
505 link_tag_end = strchr(ptr, '>');
506 if (link_tag_end == NULL)
508 for (i=0; i < 1; i++ ){
509 rel_start = cbmstrcasestr(link_tag_start, "rel=");
510 if ((rel_start == NULL) ||
511 (rel_start > link_tag_end))
514 rel_start = strchr(rel_start, '\"');
515 if ((rel_start == NULL) ||
516 (rel_start > link_tag_end))
519 rel_end = strchr(rel_start, '\"');
520 if ((rel_end == NULL) ||
521 (rel_end == rel_start) ||
522 (rel_end >= link_tag_end) )
524 if (strncasecmp(rel, rel_start, repllen)!= 0)
525 continue; /* didn't match? never mind... */
527 href_start = cbmstrcasestr(link_tag_start, "href=");
528 if ((href_start == NULL) ||
529 (href_start >= link_tag_end))
531 href_start = strchr(href_start, '\"');
532 if ((href_start == NULL) |
533 (href_start >= link_tag_end))
536 href_end = strchr(href_start, '\"');
537 if ((href_end == NULL) ||
538 (href_end == href_start) ||
539 (href_start >= link_tag_end))
541 StrBufPlain(target_buf, href_start, href_end - href_start);
549 * Wrapper for curl_easy_init() that includes the options common to all calls
550 * used in this module.
552 CURL *ctdl_openid_curl_easy_init(char *errmsg) {
555 curl = curl_easy_init();
560 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
561 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
564 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
566 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
567 #ifdef CURLOPT_HTTP_CONTENT_DECODING
568 curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
569 curl_easy_setopt(curl, CURLOPT_ENCODING, "");
571 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
572 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30); /* die after 30 seconds */
575 (!IsEmptyStr(config.c_ip_addr))
576 && (strcmp(config.c_ip_addr, "*"))
577 && (strcmp(config.c_ip_addr, "::"))
578 && (strcmp(config.c_ip_addr, "0.0.0.0"))
580 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
591 int current_service_priority;
592 int selected_service_priority;
593 StrBuf *current_service_uri;
594 StrBuf *selected_service_uri;
595 int current_service_is_oid2auth;
599 void xrds_xml_start(void *data, const char *supplied_el, const char **attr) {
600 struct xrds *xrds = (struct xrds *) data;
603 ++xrds->nesting_level;
605 if (!strcasecmp(supplied_el, "XRD")) {
609 else if (!strcasecmp(supplied_el, "service")) {
610 xrds->current_service_priority = 0;
611 xrds->current_service_is_oid2auth = 0;
612 for (i=0; attr[i] != NULL; i+=2) {
613 if (!strcasecmp(attr[i], "priority")) {
614 xrds->current_service_priority = atoi(attr[i+1]);
619 FlushStrBuf(xrds->CharData);
623 void xrds_xml_end(void *data, const char *supplied_el) {
624 struct xrds *xrds = (struct xrds *) data;
626 --xrds->nesting_level;
628 if (!strcasecmp(supplied_el, "XRD")) {
632 else if (!strcasecmp(supplied_el, "type")) {
634 && (!strcasecmp(ChrPtr(xrds->CharData), "http://specs.openid.net/auth/2.0/server"))
636 xrds->current_service_is_oid2auth = 1;
639 && (!strcasecmp(ChrPtr(xrds->CharData), "http://specs.openid.net/auth/2.0/signon"))
641 xrds->current_service_is_oid2auth = 1;
642 /* FIXME in this case, the Claimed ID should be considered immutable */
646 else if (!strcasecmp(supplied_el, "uri")) {
648 FlushStrBuf(xrds->current_service_uri);
649 StrBufAppendBuf(xrds->current_service_uri, xrds->CharData, 0);
653 else if (!strcasecmp(supplied_el, "service")) {
655 && (xrds->current_service_priority < xrds->selected_service_priority)
656 && (xrds->current_service_is_oid2auth)
658 xrds->selected_service_priority = xrds->current_service_priority;
659 FlushStrBuf(xrds->selected_service_uri);
660 StrBufAppendBuf(xrds->selected_service_uri, xrds->current_service_uri, 0);
665 FlushStrBuf(xrds->CharData);
669 void xrds_xml_chardata(void *data, const XML_Char *s, int len) {
670 struct xrds *xrds = (struct xrds *) data;
672 StrBufAppendBufPlain (xrds->CharData, s, len, 0);
677 * Parse an XRDS document.
678 * If an OpenID Provider URL is discovered, op_url to that value and return nonzero.
679 * If nothing useful happened, return 0.
681 int parse_xrds_document(StrBuf *ReplyBuf) {
682 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
684 int return_value = 0;
686 /* syslog(LOG_DEBUG, "XRDS document:\n%s\n", ChrPtr(ReplyBuf)); */
688 memset(&xrds, 0, sizeof (struct xrds));
689 xrds.selected_service_priority = INT_MAX;
690 xrds.CharData = NewStrBuf();
691 xrds.current_service_uri = NewStrBuf();
692 xrds.selected_service_uri = NewStrBuf();
693 XML_Parser xp = XML_ParserCreate(NULL);
695 XML_SetUserData(xp, &xrds);
696 XML_SetElementHandler(xp, xrds_xml_start, xrds_xml_end);
697 XML_SetCharacterDataHandler(xp, xrds_xml_chardata);
698 XML_Parse(xp, ChrPtr(ReplyBuf), StrLength(ReplyBuf), 0);
699 XML_Parse(xp, "", 0, 1);
703 syslog(LOG_ALERT, "Cannot create XML parser");
706 if (xrds.selected_service_priority < INT_MAX) {
707 if (oiddata->op_url == NULL) {
708 oiddata->op_url = NewStrBuf();
710 FlushStrBuf(oiddata->op_url);
711 StrBufAppendBuf(oiddata->op_url, xrds.selected_service_uri, 0);
712 return_value = openid_disco_xrds;
715 FreeStrBuf(&xrds.CharData);
716 FreeStrBuf(&xrds.current_service_uri);
717 FreeStrBuf(&xrds.selected_service_uri);
719 return(return_value);
725 * Callback function for perform_openid2_discovery()
726 * We're interested in the X-XRDS-Location: header.
728 size_t yadis_headerfunction(void *ptr, size_t size, size_t nmemb, void *userdata) {
730 StrBuf **x_xrds_location = (StrBuf **) userdata;
732 memcpy(hdr, ptr, (size*nmemb));
735 if (!strncasecmp(hdr, "X-XRDS-Location:", 16)) {
736 *x_xrds_location = NewStrBufPlain(&hdr[16], ((size*nmemb)-16));
737 StrBufTrim(*x_xrds_location);
740 return(size * nmemb);
744 /* Attempt to perform Yadis discovery as specified in Yadis 1.0 section 6.2.5.
746 * If Yadis fails, we then attempt HTML discovery using the same document.
748 * If successful, returns nonzero and calls parse_xrds_document() to act upon the received data.
749 * If fails, returns 0 and does nothing else.
751 int perform_openid2_discovery(StrBuf *SuppliedURL) {
752 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
754 StrBuf *ReplyBuf = NULL;
755 int return_value = 0;
758 char errmsg[1024] = "";
759 struct curl_slist *my_headers = NULL;
760 StrBuf *x_xrds_location = NULL;
762 if (!SuppliedURL) return(0);
763 syslog(LOG_DEBUG, "perform_openid2_discovery(%s)", ChrPtr(SuppliedURL));
764 if (StrLength(SuppliedURL) == 0) return(0);
766 ReplyBuf = NewStrBuf();
767 if (!ReplyBuf) return(0);
769 curl = ctdl_openid_curl_easy_init(errmsg);
770 if (!curl) return(0);
772 curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(SuppliedURL));
773 curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
774 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
776 my_headers = curl_slist_append(my_headers, "Accept:"); /* disable the default Accept: header */
777 my_headers = curl_slist_append(my_headers, "Accept: application/xrds+xml");
778 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, my_headers);
780 curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &x_xrds_location);
781 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, yadis_headerfunction);
783 result = curl_easy_perform(curl);
785 syslog(LOG_DEBUG, "libcurl error %d: %s", result, errmsg);
787 curl_slist_free_all(my_headers);
788 curl_easy_cleanup(curl);
789 docbytes = StrLength(ReplyBuf);
792 * The response from the server will be one of:
794 * Option 1: An HTML document with a <head> element that includes a <meta> element with http-equiv
795 * attribute, X-XRDS-Location,
797 * Does any provider actually do this? If so then we will implement it in the future.
801 * Option 2: HTTP response-headers that include an X-XRDS-Location response-header,
802 * together with a document.
803 * Option 3: HTTP response-headers only, which MAY include an X-XRDS-Location response-header,
804 * a contenttype response-header specifying MIME media type,
805 * application/xrds+xml, or both.
807 * If the X-XRDS-Location header was delivered, we know about it at this point...
809 if ( (x_xrds_location)
810 && (strcmp(ChrPtr(x_xrds_location), ChrPtr(SuppliedURL)))
812 syslog(LOG_DEBUG, "X-XRDS-Location: %s ... recursing!", ChrPtr(x_xrds_location));
813 return_value = perform_openid2_discovery(x_xrds_location);
814 FreeStrBuf(&x_xrds_location);
818 * Option 4: the returned web page may *be* an XRDS document. Try to parse it.
820 if ( (return_value == 0) && (docbytes >= 0)) {
821 return_value = parse_xrds_document(ReplyBuf);
825 * Option 5: if all else fails, attempt HTML based discovery.
827 if ( (return_value == 0) && (docbytes >= 0)) {
828 if (oiddata->op_url == NULL) {
829 oiddata->op_url = NewStrBuf();
831 extract_link(oiddata->op_url, HKEY("openid2.provider"), ReplyBuf);
832 if (StrLength(oiddata->op_url) > 0) {
833 return_value = openid_disco_html;
837 if (ReplyBuf != NULL) {
838 FreeStrBuf(&ReplyBuf);
840 return(return_value);
845 * Setup an OpenID authentication
847 void cmd_oids(char *argbuf) {
848 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
849 const char *Pos = NULL;
850 StrBuf *ArgBuf = NULL;
851 StrBuf *ReplyBuf = NULL;
852 StrBuf *return_to = NULL;
853 StrBuf *RedirectUrl = NULL;
854 ctdl_openid *oiddata;
855 int discovery_succeeded = 0;
857 Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
859 CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
860 if (oiddata == NULL) {
861 syslog(LOG_ALERT, "malloc() failed: %s", strerror(errno));
862 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
865 memset(oiddata, 0, sizeof(ctdl_openid));
866 CCC->openid_data = (void *) oiddata;
868 ArgBuf = NewStrBufPlain(argbuf, -1);
870 oiddata->verified = 0;
871 oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
872 return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
874 StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
875 StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
877 syslog(LOG_DEBUG, "User-Supplied Identifier is: %s", ChrPtr(oiddata->claimed_id));
879 /********** OpenID 2.0 section 7.3 - Discovery **********/
881 /* Section 7.3.1 says we have to attempt XRI based discovery.
882 * No one is using this, no one is asking for it, no one wants it.
883 * So we're not even going to bother attempting this mode.
886 /* Attempt section 7.3.2 (Yadis discovery) and section 7.3.3 (HTML discovery);
888 discovery_succeeded = perform_openid2_discovery(oiddata->claimed_id);
890 if (discovery_succeeded == 0) {
891 cprintf("%d There is no OpenID identity provider at this location.\n", ERROR);
896 * If we get to this point we are in possession of a valid OpenID Provider URL.
898 syslog(LOG_DEBUG, "OP URI '%s' discovered using method %d",
899 ChrPtr(oiddata->op_url),
903 /* We have to "normalize" our Claimed ID otherwise it will cause some OP's to barf */
904 if (cbmstrcasestr(ChrPtr(oiddata->claimed_id), "://") == NULL) {
905 StrBuf *cid = oiddata->claimed_id;
906 oiddata->claimed_id = NewStrBufPlain(HKEY("http://"));
907 StrBufAppendBuf(oiddata->claimed_id, cid, 0);
912 * OpenID 2.0 section 9: request authentication
913 * Assemble a URL to which the user-agent will be redirected.
916 RedirectUrl = NewStrBufDup(oiddata->op_url);
918 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.ns="), 0);
919 StrBufUrlescAppend(RedirectUrl, NULL, "http://specs.openid.net/auth/2.0");
921 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.mode=checkid_setup"), 0);
923 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.claimed_id="), 0);
924 StrBufUrlescAppend(RedirectUrl, oiddata->claimed_id, NULL);
926 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.identity="), 0);
927 StrBufUrlescAppend(RedirectUrl, oiddata->claimed_id, NULL);
929 /* Attribute Exchange */
930 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ns.ax="), 0);
931 StrBufUrlescAppend(RedirectUrl, NULL, "http://openid.net/srv/ax/1.0");
933 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.mode=fetch_request"), 0);
935 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.required=firstname,lastname,friendly,nickname"), 0);
937 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.firstname="), 0);
938 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/first");
940 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.lastname="), 0);
941 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/last");
943 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.friendly="), 0);
944 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/friendly");
946 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.nickname="), 0);
947 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/nickname");
949 /* return_to completes the round trip */
950 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
951 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
953 syslog(LOG_DEBUG, "OpenID: redirecting client to %s", ChrPtr(RedirectUrl));
954 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
958 FreeStrBuf(&ReplyBuf);
959 FreeStrBuf(&return_to);
960 FreeStrBuf(&RedirectUrl);
965 * Finalize an OpenID authentication
967 void cmd_oidf(char *argbuf) {
972 HashList *keys = NULL;
975 ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
977 if (oiddata == NULL) {
978 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
981 if (StrLength(oiddata->op_url) == 0){
982 cprintf("%d No OpenID Endpoint URL has been obtained.\n", ERROR + ILLEGAL_VALUE);
985 keys = NewHash(1, NULL);
987 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
990 cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
992 while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
993 len = extract_token(thiskey, buf, 0, '|', sizeof thiskey);
995 len = sizeof(thiskey) - 1;
997 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
998 Put(keys, thiskey, len, strdup(thisdata), NULL);
1001 /* Check to see if this is a correct response.
1002 * Start with verified=1 but then set it to 0 if anything looks wrong.
1004 oiddata->verified = 1;
1006 char *openid_ns = NULL;
1007 if ( (!GetHash(keys, "ns", 2, (void *) &openid_ns))
1008 || (strcasecmp(openid_ns, "http://specs.openid.net/auth/2.0"))
1010 syslog(LOG_DEBUG, "This is not an an OpenID assertion");
1011 oiddata->verified = 0;
1014 char *openid_mode = NULL;
1015 if ( (!GetHash(keys, "mode", 4, (void *) &openid_mode))
1016 || (strcasecmp(openid_mode, "id_res"))
1018 oiddata->verified = 0;
1021 char *openid_claimed_id = NULL;
1022 if (GetHash(keys, "claimed_id", 10, (void *) &openid_claimed_id)) {
1023 FreeStrBuf(&oiddata->claimed_id);
1024 oiddata->claimed_id = NewStrBufPlain(openid_claimed_id, -1);
1025 syslog(LOG_DEBUG, "Provider is asserting the Claimed ID '%s'", ChrPtr(oiddata->claimed_id));
1028 /* Validate the assertion against the server */
1029 syslog(LOG_DEBUG, "Validating...");
1033 struct curl_httppost *formpost = NULL;
1034 struct curl_httppost *lastptr = NULL;
1035 char errmsg[1024] = "";
1036 StrBuf *ReplyBuf = NewStrBuf();
1038 curl_formadd(&formpost, &lastptr,
1039 CURLFORM_COPYNAME, "openid.mode",
1040 CURLFORM_COPYCONTENTS, "check_authentication",
1044 HashPos *HashPos = GetNewHashPos(keys, 0);
1045 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value) != 0) {
1046 syslog(LOG_DEBUG, "%s = %s", Key, (char *)Value);
1047 if (strcasecmp(Key, "mode")) {
1048 char k_o_keyname[1024];
1049 snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", (const char *)Key);
1050 curl_formadd(&formpost, &lastptr,
1051 CURLFORM_COPYNAME, k_o_keyname,
1052 CURLFORM_COPYCONTENTS, (char *)Value,
1058 curl = ctdl_openid_curl_easy_init(errmsg);
1059 curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->op_url));
1060 curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
1061 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
1062 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
1064 res = curl_easy_perform(curl);
1066 syslog(LOG_DEBUG, "cmd_oidf() libcurl error %d: %s", res, errmsg);
1067 oiddata->verified = 0;
1069 curl_easy_cleanup(curl);
1070 curl_formfree(formpost);
1072 /* syslog(LOG_DEBUG, "Validation reply: \n%s", ChrPtr(ReplyBuf)); */
1073 if (cbmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true") == NULL) {
1074 oiddata->verified = 0;
1076 FreeStrBuf(&ReplyBuf);
1078 syslog(LOG_DEBUG, "OpenID authentication %s", (oiddata->verified ? "succeeded" : "failed") );
1080 /* Respond to the client */
1082 if (oiddata->verified) {
1084 /* If we were already logged in, attach the OpenID to the user's account */
1085 if (CC->logged_in) {
1086 if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
1087 cprintf("attach\n");
1088 syslog(LOG_DEBUG, "OpenID attach succeeded");
1092 syslog(LOG_DEBUG, "OpenID attach failed");
1096 /* Otherwise, a user is attempting to log in using the verified OpenID */
1099 * Existing user who has claimed this OpenID?
1101 * Note: if you think that sending the password back over the wire is insecure,
1102 * check your assumptions. If someone has successfully asserted an OpenID that
1103 * is associated with the account, they already have password equivalency and can
1104 * login, so they could just as easily change the password, etc.
1106 if (login_via_openid(oiddata->claimed_id) == 0) {
1107 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1108 logged_in_response();
1109 syslog(LOG_DEBUG, "Logged in using previously claimed OpenID");
1113 * If this system does not allow self-service new user registration, the
1114 * remaining modes do not apply, so fail here and now.
1116 else if (config.c_disable_newu) {
1118 syslog(LOG_DEBUG, "Creating user failed due to local policy");
1122 * New user whose OpenID is verified and Simple Registration Extension is in use?
1124 else if (openid_create_user_via_sreg(oiddata->claimed_id, keys) == 0) {
1125 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1126 logged_in_response();
1127 syslog(LOG_DEBUG, "Successfully auto-created new user");
1131 * OpenID is verified, but the desired username either was not specified or
1132 * conflicts with an existing user. Manual account creation is required.
1135 char *desired_name = NULL;
1136 cprintf("verify_only\n");
1137 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
1138 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
1139 cprintf("%s\n", desired_name);
1144 syslog(LOG_DEBUG, "The desired display name is already taken.");
1153 if (oiddata->sreg_keys != NULL) {
1154 DeleteHash(&oiddata->sreg_keys);
1155 oiddata->sreg_keys = NULL;
1157 oiddata->sreg_keys = keys;
1162 /**************************************************************************/
1164 /* Functions in this section handle module initialization and shutdown */
1166 /**************************************************************************/
1171 CTDL_MODULE_INIT(openid_rp)
1174 curl_global_init(CURL_GLOBAL_ALL);
1176 /* Only enable the OpenID command set when native mode authentication is in use. */
1177 if (config.c_auth_mode == AUTHMODE_NATIVE) {
1178 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
1179 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
1180 CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
1181 CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
1182 CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
1183 CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
1185 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
1186 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
1187 openid_level_supported = 1; /* This module supports OpenID 1.0 only */
1190 /* return our module name for the log */