pax_global_header00006660000000000000000000000064123030447560014516gustar00rootroot0000000000000052 comment=66b37b16d8c29072c16a8c2c8d4a53256a67bcdb mod_authnz_persona-0.8.1/000077500000000000000000000000001230304475600154235ustar00rootroot00000000000000mod_authnz_persona-0.8.1/.gitignore000066400000000000000000000000121230304475600174040ustar00rootroot00000000000000/build *~ mod_authnz_persona-0.8.1/COPYING000066400000000000000000000261351230304475600164650ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. mod_authnz_persona-0.8.1/Makefile000066400000000000000000000023401230304475600170620ustar00rootroot00000000000000ifeq ($(APXS_PATH),) APXS_PATH=/usr/sbin/apxs endif MY_LDFLAGS=-lcurl -lyajl # Note that gcc flags are passed through apxs, so preface with -Wc MY_CFLAGS=-Wc,-I. -Wc,-Wall -Wc,-g -Wc,-Wno-unused-function SRCS=src/mod_authnz_persona.c src/cookie.c src/verify.c src/hmac.c HDRS=src/cookie.h src/defines.h src/verify.h src/hmac.h BUILDDIR := build .SUFFIXES: .c .o .la all: build/.libs/mod_authnz_persona.so .PHONY: builddir builddir: build $(BUILDDIR): @mkdir -p $@ $(BUILDDIR)/bin2c: tools/bin2c.c | $(BUILDDIR) @gcc -Wall -g -o $(BUILDDIR)/bin2c $< $(BUILDDIR)/signin_page.h: src/signin.html $(BUILDDIR)/bin2c | $(BUILDDIR) @$(BUILDDIR)/bin2c $^ > $@ $(BUILDDIR)/error.html: src/error.html src/signin.html @cp src/signin.html $@ @cat src/error.html >> $@ $(BUILDDIR)/error_page.h: $(BUILDDIR)/error.html $(BUILDDIR)/bin2c | $(BUILDDIR) @$(BUILDDIR)/bin2c $^ > $@ $(BUILDDIR)/.libs/mod_authnz_persona.so: $(SRCS) $(HDRS) $(BUILDDIR)/signin_page.h $(BUILDDIR)/error_page.h @cd $(BUILDDIR) && for file in $(SRCS) $(HDRS) ; do ln -sf ../$$file . ; done @cd $(BUILDDIR) && $(APXS_PATH) $(MY_LDFLAGS) $(MY_CFLAGS) -c $(subst src/,,$(SRCS)) install: all $(APXS_PATH) -i $(BUILDDIR)/mod_authnz_persona.la clean: -rm -rf $(BUILDDIR) mod_authnz_persona-0.8.1/README.md000066400000000000000000000064531230304475600167120ustar00rootroot00000000000000mod_authnz_persona is a module for Apache 2.0 or later that allows you to quickly add Persona authentication to a site hosted with Apache. # Installation First, install the dependencies: * apache 2.2 or later * libcurl 7.10.8 or later (for remote verification) * yajl 2.0 or later (for JSON parsing) On Red Hat-derivative distributions, this might help: ``` yum install httpd httpd-devel curl-devel cmake wget http://fedora.mirror.nexicom.net/linux/development/rawhide/source/SRPMS/y/yajl-2.0.4-3.fc20.src.rpm rpmbuild --rebuild yajl-*.src.rpm sudo yum install ~/rpmbuild/RPMS/`uname -i`/yajl-*.rpm ``` (CMake is a build-time yajl dependency.) Then, clone the source and build: ``` git clone https://github.com/mozilla/mod_authnz_persona.git cd mod_authnz_persona make sudo make install ``` (This assumes apxs is behaving properly on your system; set the APXS_PATH variable to your apxs or apxs2 as appropriate.) # Configuration Configure the module: LoadModule authnz_persona_module modules/mod_authnz_persona.so AuthType Persona Require valid-user # Or, require users with host/IdP example.com: # Require persona-idp example.com # Or, require specific users (requires mod_authz_user) # Require user user@example.com This will cause the module to require Persona authentication for all requests to the server. # Features * **zero configuration** - The module is designed with reasonable defaults, so you can simply drop it in. * **automatic re-auth** - The module is designed to use session cookies and automatically re-authenticate. # How it works The module works by intercepting requests bound for protected resources, and checking for the presence of a session cookie. If the cookie is not found, the user agent is served an HTML document that presents a Persona login page. Upon successful authentication with Persona, this page will send a request to the server with a Persona assertion in an HTTP header. The module, upon detecting no cookie is present, will look for this header, validate the assertion, and set a short session cookie. The authentication page will then reload the desired resource. # Further configuration settings * `AuthPersonaServerSecret`: A secret that will be used to sign cookies. Must be set in a server or VirtualHost context. If not provided, upon server start a secret will be generated automatically. Given re-authentication is automatic, it is only required to set a cookie secret if your application is hosted on multiple load-balanced Apache servers. * `AuthPersonaLogoutPath`: A path that can be linked to for logout. Relative to the server root; must start with a `/` to match. If this is enabled, users can be logged out by linking to the URL set up by this option. After logout, the user will be redirected to the full URL passed in the `returnto` query string argument, if available; if not, the user will be redirected to `/` (which can be confusing, due to automatic re-authentication). * `Require persona-idp`: Only allow users with email addresses backed by the given Identity Provider. Note that this will often, but not necessarily, be the host part of the verified email address, in the case of email addresses backed by a secondary IdP (like the fallback IdP or a bridging IdP). mod_authnz_persona-0.8.1/src/000077500000000000000000000000001230304475600162125ustar00rootroot00000000000000mod_authnz_persona-0.8.1/src/cookie.c000066400000000000000000000127371230304475600176410ustar00rootroot00000000000000/* Copyright 1999-2014 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Based in part, on mod_auth_memcookie, made by Mathieu CARBONNEAUX. * * See http://authmemcookie.sourceforge.net/ for details; * licensed under Apache License, Version 2.0. * * SHA-1 implementation by Steve Reid, steve@edmweb.com, in * public domain. */ #include #include #include #include #include #include #include #include #include "cookie.h" #include "defines.h" #include "hmac.h" /** Generates a HMAC with the given inputs, returning a Base64-encoded * signature value. */ static char *generateHMAC(request_rec *r, const buffer_t *secret, const Cookie cookie) { char *data; unsigned char digest[HMAC_DIGESTSIZE]; char *digest64; char timestr[12]; snprintf(timestr, 12, "%" APR_TIME_T_FMT, cookie->created); data = apr_pstrcat(r->pool, cookie->verifiedEmail, cookie->identityIssuer, timestr, NULL); hmac(secret->data, secret->len, data, strlen(data), &digest); digest64 = apr_palloc(r->pool, apr_base64_encode_len(HMAC_DIGESTSIZE)); apr_base64_encode(digest64, (char*)digest, HMAC_DIGESTSIZE); return digest64; } /* Look through the 'Cookie' headers for the indicated cookie; extract it * and URL-unescape it. Return the cookie on success, NULL on failure. */ char * extractCookie(request_rec *r, const buffer_t *secret, const char *szCookie_name) { char *szRaw_cookie_start=NULL, *szRaw_cookie_end; char *szCookie; /* get cookie string */ char*szRaw_cookie = (char*)apr_table_get( r->headers_in, "Cookie"); if (!szRaw_cookie) return 0; /* loop to search cookie name in cookie header */ do { ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, ERRTAG "Checking cookie %s, looking for %s", szRaw_cookie, szCookie_name); /* search cookie name in cookie string */ if (!(szRaw_cookie = strstr(szRaw_cookie, szCookie_name))) return 0; szRaw_cookie_start=szRaw_cookie; /* search '=' */ if (!(szRaw_cookie = strchr(szRaw_cookie, '='))) return 0; } while (strncmp(szCookie_name,szRaw_cookie_start,szRaw_cookie-szRaw_cookie_start)!=0); /* skip '=' */ szRaw_cookie++; /* search end of cookie name value: ';' or end of cookie strings */ if (!((szRaw_cookie_end = strchr(szRaw_cookie, ';')) || (szRaw_cookie_end = strchr(szRaw_cookie, '\0')))) return 0; /* dup the value string found in apache pool and set the result pool ptr to szCookie ptr */ if (!(szCookie = apr_pstrndup(r->pool, szRaw_cookie, szRaw_cookie_end-szRaw_cookie))) return 0; /* unescape the value string */ if (ap_unescape_url(szCookie) != 0) return 0; ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, ERRTAG "finished cookie scan, returning %s", szCookie); return szCookie; } /* Check the cookie and make sure it is valid */ Cookie validateCookie(request_rec *r, const buffer_t *secret, const char *szCookieValue) { /* split at | */ char *iss = NULL; char *sig = NULL; char *crea = NULL; char *addr = apr_strtok((char *) szCookieValue, "|", &iss); if (!addr) { ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, ERRTAG "malformed Persona cookie, can't extract email"); return NULL; } iss = apr_strtok((char *) iss, "|", &crea); if (!iss) { ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, ERRTAG "malformed Persona cookie, can't extract issuer"); return NULL; } crea = apr_strtok((char *) crea, "|", &sig); if (!crea) { ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, ERRTAG "malformed Persona cookie, can't extract time"); return NULL; } Cookie c = apr_pcalloc(r->pool, sizeof(struct _Cookie)); c->verifiedEmail = addr; c->identityIssuer = iss; c->created = strtol(crea, NULL, 10); char *digest64 = generateHMAC(r, secret, c); ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, ERRTAG "Got cookie: email is %s; expected digest is %s; got digest %s", addr, digest64, sig); /* paranoia indicates that we should use a time-invariant compare here */ if (strcmp(digest64, sig)) { ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, ERRTAG "invalid Persona cookie"); return NULL; } return c; } /** Create a session cookie with a given identity */ void sendSignedCookie(request_rec *r, const buffer_t *secret, const Cookie cookie) { char *digest64 = generateHMAC(r, secret, cookie); /* syntax of cookie is identity|issuer|timestamp|signature */ apr_table_set(r->err_headers_out, "Set-Cookie", apr_psprintf(r->pool, "%s=%s|%s|%" APR_TIME_T_FMT "|%s; Path=/", PERSONA_COOKIE_NAME, cookie->verifiedEmail, cookie->identityIssuer, cookie->created, digest64)); } void sendResetCookie(request_rec *r) { apr_table_set(r->err_headers_out, "Set-Cookie", apr_psprintf(r->pool, "%s=; Path=/; Expires=Thu, 01-Jan-1970 00:00:01 GMT", PERSONA_COOKIE_NAME)); } mod_authnz_persona-0.8.1/src/cookie.h000066400000000000000000000030331230304475600176330ustar00rootroot00000000000000/* Copyright 1999-2014 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Cookie management routines */ #ifndef __COOKIE_H__ #define __COOKIE_H__ #include #include "defines.h" typedef struct _Cookie { const char *verifiedEmail; // email that was verified const char *identityIssuer; // domain that issued the identity apr_time_t created; // when this cookie was created }* Cookie; /* Look through the 'Cookie' headers for the indicated cookie; extract it * and URL-unescape it. Return the cookie on success, NULL on failure. */ char * extractCookie(request_rec *r, const buffer_t *secret, const char *szCookie_name); /* Check the cookie and make sure it is valid */ Cookie validateCookie(request_rec *r, const buffer_t *secret, const char *szCookieValue); /** Create a session cookie with a given identity */ void sendSignedCookie(request_rec *r, const buffer_t *secret, const Cookie cookie); /* Send an empty cookie, to reset the session */ void sendResetCookie(request_rec *r); #endif mod_authnz_persona-0.8.1/src/defines.h000066400000000000000000000023061230304475600200010ustar00rootroot00000000000000/* Copyright 1999-2014 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __DEFINES_H__ #define __DEFINES_H__ #include #define PERSONA_DEFAULT_VERIFIER_URL "https://verifier.login.persona.org/verify" #define PERSONA_COOKIE_NAME "Persona" #define PERSONA_ISSUER_NOTE "persona-identity-issuer" #define PERSONA_SECRET_SIZE 1024 #define PERSONA_ASSERTION_HEADER "Persona-Assertion" #define PERSONA_END_PAGE "\n\n\n" #define ERRTAG "authnz_persona: " #define VERSION "1.0.0" typedef struct buffer { size_t len; char *data; } buffer_t; typedef struct persona_config { buffer_t *secret; buffer_t *logout_path; } persona_config_t; #endif mod_authnz_persona-0.8.1/src/error.html000066400000000000000000000007021230304475600202300ustar00rootroot00000000000000var loggedInUser = null; var cookies = document.cookie.split('; '); for (var x in cookies) { var cookieData = cookies[x]; var name = cookieData.split('=')[0]; if (name == 'Persona') { var cookieValue = cookieData.split('=').slice(1).join('='); loggedInUser = cookieValue.split('|')[0]; showError({ "status": "failure", "reason": "user '" + loggedInUser + "' is not authorized" }); break; } } mod_authnz_persona-0.8.1/src/hmac.c000077500000000000000000000052061230304475600172740ustar00rootroot00000000000000/* Copyright 1999-2014 Philippe M. Chiasson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "hmac.h" #define HMAC_BLOCKSIZE 64 /* Somewhat arbitrary mask values, but they are straight from the spec */ #define HMAC_IPAD 0x36 #define HMAC_OPAD 0x5c static void mxor(void *, const void *, apr_size_t); /* Implements an HMAC with SHA1 the correct, safe way : http://en.wikipedia.org/wiki/Hash-based_message_authentication_code * * Basic idea is to split the key in 2 parts, then hash the data twice, with 2 separate pieces of the key appended * * HMAC (K,m) = H((K+opad) | H((K+ipad) | m)) * * Tricky, but much, much safer than the trivial implementation of HMAC(K,m) = H(K|m) * */ void hmac(const void *key, apr_size_t keylen, const char *data, apr_size_t datalen, void *result) { apr_sha1_ctx_t inner; apr_sha1_ctx_t outer; unsigned char keypad[HMAC_BLOCKSIZE]; unsigned char inner_digest[APR_SHA1_DIGESTSIZE]; /* Shorten the key down to the blocksize, anything more is useless */ if (keylen > HMAC_BLOCKSIZE) { apr_sha1_ctx_t context; unsigned char digest[APR_SHA1_DIGESTSIZE]; apr_sha1_init(&context); apr_sha1_update_binary(&context, key, keylen); apr_sha1_final(digest, &context); key = digest; keylen = APR_SHA1_DIGESTSIZE; } /* Prepare and mask the inner portion of the key */ memset(keypad, HMAC_IPAD, HMAC_BLOCKSIZE); mxor(keypad, key, keylen); /* Compute the inner hash */ apr_sha1_init(&inner); apr_sha1_update_binary(&inner, keypad, HMAC_BLOCKSIZE); apr_sha1_update(&inner, data, datalen); apr_sha1_final(inner_digest, &inner); /* Prepare and mask the outer portion of the key */ memset(keypad, HMAC_OPAD, HMAC_BLOCKSIZE); mxor(keypad, key, keylen); /* Compute the outer hash */ apr_sha1_init(&outer); apr_sha1_update_binary(&outer, keypad, HMAC_BLOCKSIZE); apr_sha1_update_binary(&outer, inner_digest, APR_SHA1_DIGESTSIZE); apr_sha1_final(result, &outer); } /* util to XOR src on top of dst */ static void mxor(void *dst, const void *src, apr_size_t len) { char const *s = src; char *d = dst; for (; len > 0; len--) *d++ ^= *s++; return; } mod_authnz_persona-0.8.1/src/hmac.h000066400000000000000000000015461230304475600173010ustar00rootroot00000000000000/* Copyright 1999-2014 Philippe M. Chiasson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __HMAC_H__ #define __HMAC_H__ #include #include #include #define HMAC_DIGESTSIZE APR_SHA1_DIGESTSIZE void hmac(const void *key, apr_size_t keylen, const char *data, apr_size_t datalen, void *result); #endif mod_authnz_persona-0.8.1/src/mod_authnz_persona.c000066400000000000000000000306251230304475600222630ustar00rootroot00000000000000/* Copyright 1999-2014 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Based in part, on mod_auth_memcookie, made by Mathieu CARBONNEAUX. * * See http://authmemcookie.sourceforge.net/ for details; * licensed under Apache License, Version 2.0. * * SHA-1 implementation by Steve Reid, steve@edmweb.com, in * public domain. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* for ap_hook_(check_user_id | auth_checker)*/ #include #include #if AP_MODULE_MAGIC_AT_LEAST(20080403, 1) #include "mod_auth.h" #endif #include "defines.h" #include "cookie.h" #include "verify.h" #include "signin_page.h" #include "error_page.h" /* apache module name */ module AP_MODULE_DECLARE_DATA authnz_persona_module; static int persona_authn_active(request_rec *r) { return (strncmp("Persona", ap_auth_type(r), 9) == 0) ? 1 : 0; } /* Parse x-www-url-formencoded args */ apr_table_t *parse_args(request_rec *r, char *args) { char* pair; char* last = NULL; char* eq; char *delim = "&"; apr_table_t *vars = apr_table_make(r->pool, 10); for (pair = apr_strtok(r->args, delim, &last); pair; pair = apr_strtok(NULL, delim, &last)) { for (eq = pair; *eq; ++eq) if (*eq == '+') *eq = ' '; ap_unescape_url(pair); eq = strchr(pair, '='); if (eq) { *eq++ = 0; apr_table_merge(vars, pair, eq); } else { apr_table_merge(vars, pair, ""); } } return vars; } static int process_logout(request_rec *r) { const char *returnto = NULL; sendResetCookie(r); if (r->args) { if (strlen(r->args) > 16384) return HTTP_REQUEST_URI_TOO_LARGE; returnto = apr_table_get(parse_args(r, r->args), "returnto"); } apr_table_set(r->headers_out, "Location", returnto == NULL ? "/" : returnto); return HTTP_SEE_OTHER; } /************************************************** * Authentication phase * * - If AuthType != Persona, do nothing * - Handle POSTed assertions ("null" -> logout) * - If we have a cookie, set up user context **************************************************/ static int Auth_persona_check_cookie(request_rec *r) { char *szCookieValue=NULL; char *szRemoteIP=NULL; const char *assertion=NULL; if (!persona_authn_active(r)) { return DECLINED; } ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, ERRTAG "Auth_persona_check_cookie"); // We'll trade you a valid assertion for a session cookie! // this is a programmatic XHR request. persona_config_t *conf = ap_get_module_config(r->server->module_config, &authnz_persona_module); assertion = apr_table_get(r->headers_in, PERSONA_ASSERTION_HEADER); if (assertion) { if (strcmp(r->method, "POST")) { r->status = HTTP_METHOD_NOT_ALLOWED; ap_set_content_type(r, "application/json"); const char *error = "{\"status\": \"failure\", \"reason\":" "\"login must be performed with POST\"}"; ap_rwrite(error, strlen(error), r); return DONE; } if (!strcmp(assertion, "null")) { sendResetCookie(r); r->status = HTTP_OK; const char *status = "{\"status\": \"okay\"}"; ap_set_content_type(r, "application/json"); ap_rwrite(status, strlen(status), r); return DONE; } VerifyResult res = processAssertion(r, assertion); ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO, 0,r,ERRTAG "Assertion received '%s'", assertion); if (res->verifiedEmail) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r, ERRTAG "email '%s' verified, vouched for by issuer '%s'", res->verifiedEmail, res->identityIssuer); Cookie cookie = apr_pcalloc(r->pool, sizeof(struct _Cookie)); cookie->verifiedEmail = res->verifiedEmail; cookie->identityIssuer = res->identityIssuer; cookie->created = apr_time_sec(r->request_time); sendSignedCookie(r, conf->secret, cookie); return DONE; } else { assert(res->errorResponse != NULL); r->status = HTTP_INTERNAL_SERVER_ERROR; ap_set_content_type(r, "application/json"); ap_rwrite(res->errorResponse, strlen(res->errorResponse), r); // upon assertion verification failure we return JSON explaining why return DONE; } } // handle logout via LogoutPath hit before letting valid cookies through if (conf->logout_path->len && !strncmp(r->uri, conf->logout_path->data, conf->logout_path->len)) { return process_logout(r); } // if there's a valid cookie, allow the user through szCookieValue = extractCookie(r, conf->secret, PERSONA_COOKIE_NAME); Cookie cookie = NULL; if (szCookieValue && (cookie = validateCookie(r, conf->secret, szCookieValue))) { r->user = (char *) cookie->verifiedEmail; apr_table_setn(r->notes, PERSONA_ISSUER_NOTE, cookie->identityIssuer); apr_table_setn(r->subprocess_env, "REMOTE_USER", cookie->verifiedEmail); ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, 0, r, ERRTAG "Valid auth cookie found, passthrough"); ap_custom_response(r, 401, (const char*) build_error_html); ap_custom_response(r, 403, (const char*) build_error_html); return OK; } ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, 0, r, ERRTAG "Persona cookie not found; not authorized! RemoteIP:%s",szRemoteIP); r->status = HTTP_UNAUTHORIZED; ap_set_content_type(r, "text/html"); ap_rwrite(src_signin_html, sizeof(src_signin_html), r); ap_rprintf(r, "var loggedInUser = undefined;\n"); ap_rwrite(PERSONA_END_PAGE, sizeof(PERSONA_END_PAGE), r); return DONE; } #if !AP_MODULE_MAGIC_AT_LEAST(20080403, 1) /************************************************** * Authorization phase (Apache 2.2) * * Requires authentication phase to run first. * * Handles Require persona-idp directives. **************************************************/ static int Auth_persona_check_auth(request_rec *r) { const apr_array_header_t *reqs_arr=NULL; require_line *reqs=NULL; register int x; const char *szRequireLine; char *szRequire_cmd; if (!persona_authn_active(r)) { return DECLINED; } ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, ERRTAG "Auth_persona_check_auth"); /* get require line */ reqs_arr = ap_requires(r); reqs = reqs_arr ? (require_line *) reqs_arr->elts : NULL; /* decline if no require line found */ if (!reqs_arr) return DECLINED; /* walk through the array to check each require command */ for (x = 0; x < reqs_arr->nelts; x++) { if (!(reqs[x].method_mask & (AP_METHOD_BIT << r->method_number))) continue; /* get require line */ szRequireLine = reqs[x].requirement; ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO, 0,r,ERRTAG "Require Line is '%s'", szRequireLine); /* get the first word in require line */ szRequire_cmd = ap_getword_white(r->pool, &szRequireLine); ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO, 0,r,ERRTAG "Require Cmd is '%s'", szRequire_cmd); // persona-idp: check host part of user name if (!strcmp("persona-idp", szRequire_cmd)) { char *reqIdp = ap_getword_conf(r->pool, &szRequireLine); const char *issuer = apr_table_get(r->notes, PERSONA_ISSUER_NOTE); if (!issuer || strcmp(issuer, reqIdp)) { return HTTP_FORBIDDEN; } ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, 0, r, ERRTAG "user '%s' is authorized", r->user); return OK; } } return DECLINED; } #else /************************************************** * Authorization phase (Apache 2.4) * * Handles Require persona-idp directives. * * When this is first called, the authentication context hasn't been setup * yet. Return AUTHZ_DENIED_NO_USER to force it to run, then this will be * called again, with the context setup. **************************************************/ static authz_status persona_idp_check_authorization(request_rec *r, const char *require_args, const void *parsed_require_args) { ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, ERRTAG "Require persona-idp"); if (!r->user) // this triggers running authn hook, which we need return AUTHZ_DENIED_NO_USER; char *reqIdp = ap_getword_white(r->pool, &require_args); const char *issuer = apr_table_get(r->notes, PERSONA_ISSUER_NOTE); return issuer && !strcmp(issuer, reqIdp) ? AUTHZ_GRANTED : AUTHZ_DENIED; } static const authz_provider authz_persona_idp_provider = { &persona_idp_check_authorization, NULL, }; #endif /************************************************** * register module hooks **************************************************/ static void register_hooks(apr_pool_t *p) { // these hooks are executed in order, first is first. #if AP_MODULE_MAGIC_AT_LEAST(20080403, 1) ap_hook_check_authn(Auth_persona_check_cookie, NULL, NULL, APR_HOOK_FIRST, AP_AUTH_INTERNAL_PER_CONF); ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "persona-idp", AUTHZ_PROVIDER_VERSION, &authz_persona_idp_provider, AP_AUTH_INTERNAL_PER_CONF); #else ap_hook_check_user_id(Auth_persona_check_cookie, NULL, NULL, APR_HOOK_FIRST); ap_hook_auth_checker(Auth_persona_check_auth, NULL, NULL, APR_HOOK_FIRST); #endif } #define RAND_BYTES_AT_A_TIME 256 static void *persona_create_svr_config(apr_pool_t *p, server_rec *s) { persona_config_t *conf = apr_palloc(p, sizeof(*conf)); apr_random_t *prng = apr_random_standard_new(p); while (apr_random_secure_ready(prng) == APR_ENOTENOUGHENTROPY) { unsigned char randbuf[RAND_BYTES_AT_A_TIME]; apr_generate_random_bytes(randbuf, RAND_BYTES_AT_A_TIME); apr_random_add_entropy(prng, randbuf, RAND_BYTES_AT_A_TIME); } char *secret = apr_palloc(p, PERSONA_SECRET_SIZE); apr_random_secure_bytes(prng, secret, PERSONA_SECRET_SIZE); conf->secret = apr_palloc(p, sizeof(buffer_t)); conf->secret->len = PERSONA_SECRET_SIZE; conf->secret->data = secret; conf->logout_path = apr_palloc(p, sizeof(buffer_t)); conf->logout_path->len = 0; conf->logout_path->data = NULL; return conf; } const char* persona_server_secret_option(cmd_parms *cmd, void *cfg, const char *arg) { server_rec *s = cmd->server; persona_config_t *conf = ap_get_module_config(s->module_config, &authnz_persona_module); conf->secret->len = strlen(arg); conf->secret->data = apr_palloc(cmd->pool, conf->secret->len); strncpy(conf->secret->data, arg, conf->secret->len); return NULL; } const char* persona_logout_path(cmd_parms *cmd, void *cfg, const char *arg) { server_rec *s = cmd->server; persona_config_t *conf = ap_get_module_config(s->module_config, &authnz_persona_module); conf->logout_path->len = strlen(arg); conf->logout_path->data = apr_palloc(cmd->pool, conf->logout_path->len); strncpy(conf->logout_path->data, arg, conf->logout_path->len); return NULL; } static const command_rec Auth_persona_options[] = { AP_INIT_TAKE1( "AuthPersonaServerSecret", persona_server_secret_option, NULL, RSRC_CONF, "Server secret to use for cookie signing" ), AP_INIT_TAKE1( "AuthPersonaLogoutPath", persona_logout_path, NULL, RSRC_CONF, "Path used to trigger logout" ), {NULL} }; /* apache module structure */ module AP_MODULE_DECLARE_DATA authnz_persona_module = { STANDARD20_MODULE_STUFF, NULL, /* dir config creator */ NULL, /* dir merger --- default is to override */ persona_create_svr_config, /* server config creator */ NULL, /* merge server config */ Auth_persona_options, /* command apr_table_t */ register_hooks /* register hooks */ }; mod_authnz_persona-0.8.1/src/signin.html000066400000000000000000000433711230304475600203770ustar00rootroot00000000000000

Please sign in to continue.

Progress indicatorSign in with your email