pax_global_header00006660000000000000000000000064124525327570014526gustar00rootroot0000000000000052 comment=da462d3c22978b5d35430a1a366bd740d4d6deb7 mod-authz-securepass-0~20150105.gitda462d3/000077500000000000000000000000001245253275700201005ustar00rootroot00000000000000mod-authz-securepass-0~20150105.gitda462d3/INSTALL000077500000000000000000000063531245253275700211430ustar00rootroot00000000000000There isn't yet a ready to use package available, but compiling this module is really simple. Follow the steps below: 1) Configure Apache to use cas. Follow the guide: http://support.secure-pass.net/wiki/index.php/Apache 2) Install apxs (APache eXtenSion tool) usually provided with the development package of Apache. For Debian-like distro install apxs with: apt-get install apache2-prefork-dev # or apt-get install apache2-threaded-dev For RedHat distro install apxs with yum install -y httpd-devel make gcc 3) Download the source from git from the stable branch: git clone https://github.com/garlsecurity/mod_authz_securepass.git -b master cd mod_authz_securepass 4) Compile the module and install it: make install 5) In your Apache configuration, place the following line to load this module: LoadModule authz_securepass_module /path/to/mod_authz_securepass.so 6) configure mod_authz_securepass using the following directives: Valid Server/VirtualHost Directives ----------------------------------- Directive: AuthzSecurepassDebug Default: Off Description: Set to On to enable debugging mode for troubleshooting. Directive: AuthzSecurepassCheckGroup Default: On Description: Set to Off to disable checking of group associated to the user Directive: AuthzSecurepassRESTfulAPI Default: NULL Description: URL of RESTful API where to check if a user belongs to a group Directive: AuthzSecurepassAppID Default: NULL Description: Value of X-SecurePass-App-ID to be inserted into HTTP header to invoke Securepass RESTful API Directive: AuthzSecurepassAppSecret Default: NULL Description: Value of X-SecurePass-App-Secret to be inserted into HTTP header to invoke Securepass RESTful API Directive: AuthzSecurepassGroupCachePath Default: NULL Description: The file system directory where mappings betweeen users and Securepass groups are cached Directive: AuthzSecurepassGroupTimeout Default: 600 (10 minutes) Description: The limit in seconds for the cached mappings between users and Securepass groups. When a mapping has reached this age, the user is checked again against the Securepass RESTful API. If set to 0, the mapping will not be cached Directive: AuthzSecurepassCacheCleanInterval Default: 1800 (30 minutes) Description: The minimum amount of time that must pass inbetween cache cleanings. When a new mapping is cached, the time of the last cache clean is compared against this value. If AuthzSecurepassCacheCleanInterval seconds have passed since the last cleaning, then all files in AuthzSecurepassGroupCachePath are examined and if they have expired, they are removed. This is to prevent the file system from becoming excessively cluttered. Valid Directory/.htaccess Directives ----------------------------------- Directive: AuthzSecurepass Default: Off Description: Set to On to enable SecurePass module Directive: AuthzSecurepassAuthoritative Default: On Description: Set to Off to allow access control to be passed along to lower modules if this module can't confirm access rights mod-authz-securepass-0~20150105.gitda462d3/LICENSE000077500000000000000000000455411245253275700211210ustar00rootroot00000000000000Files jsmn.c, jsmn.h are licensed under the MIT License The remaining files are licensed under the GNU GENERAL PUBLIC LICENSE ========================================================================== MIT LICENSE Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================================================== GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. mod-authz-securepass-0~20150105.gitda462d3/Makefile000066400000000000000000000013771245253275700215500ustar00rootroot00000000000000 ## Build the securepass module ## ifneq ($(shell which apxs2 2>/dev/null),) APXS_PATH = apxs2 else APXS_PATH = apxs endif # Note that gcc flags are passed through apxs, so preface with -Wc MY_LDFLAGS=-lcurl MY_CFLAGS=-Wc,-I. -Wc,-Wall SRCS=mod_authz_securepass.c jsmn.c HDRS=jsmn.h BUILDDIR := build .SUFFIXES: .c .o .la all: build/.libs/mod_authz_securepass.so .PHONY: builddir builddir: build $(BUILDDIR): @mkdir -p $@ $(BUILDDIR)/.libs/mod_authz_securepass.so: $(SRCS) $(HDRS) | $(BUILDDIR) @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_authz_securepass.la clean: -rm -rf $(BUILDDIR) mod-authz-securepass-0~20150105.gitda462d3/README.md000077500000000000000000000026561245253275700213730ustar00rootroot00000000000000Apache authorization module for SecurePass ========================================== This is an Apache (2.2 and 2.4) module for authorizing SecurePass users. SecurePass provides web single sign-on through the CAS protocol. This module enhances the Apache authorization features by introducing two rules to restrict access to the Apache resources: * the first rule allows only users belonging to specific SecurePass realm(s) to access the Apache resource * the second rule allows only users belonging to specific SecurePass group(s) to access the Apache resource More on SecurePass at http://www.secure-pass.net To install the module, please read file INSTALL. Credits =========================================== I wrote this module starting from Alessandro Lorenzi version at https://github.com/AlessandroLorenzi/mod_authz_securepass, which provided authorization based on realms I added authorization based on groups, which implied: - call a RESTFul API provided by Securepass (https://beta.secure-pass.net/trac/wiki/GroupsApi), to check if a given user belongs to a given group - parse the JSON packet returned - cache locally, for a configurable time, the user-group mappings returned by the API To parse the JSON packet, I used a nice parser called jsmn, developed by zserge and available at bitbucket.org/zserge/jsmn under the MIT license. Author =========================================== gplll1818@gmail.com, Jun 2014 - Jan 2015 mod-authz-securepass-0~20150105.gitda462d3/authz_securepass.load000077500000000000000000000001241245253275700243310ustar00rootroot00000000000000LoadModule authz_securepass_module /usr/lib/apache2/modules/mod_authz_securepass.so mod-authz-securepass-0~20150105.gitda462d3/jsmn.c000066400000000000000000000174211245253275700212200ustar00rootroot00000000000000/* * Copyright (c) 2010 Serge A. Zaitsev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include #include "jsmn.h" /** * Allocates a fresh unused token from the token pull. */ static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *tok; if (parser->toknext >= num_tokens) { return NULL; } tok = &tokens[parser->toknext++]; tok->start = tok->end = -1; tok->size = 0; #ifdef JSMN_PARENT_LINKS tok->parent = -1; #endif return tok; } /** * Fills token type and boundaries. */ static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, int start, int end) { token->type = type; token->start = start; token->end = end; token->size = 0; } /** * Fills next available token with JSON primitive. */ static jsmnerr_t jsmn_parse_primitive(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *token; int start; start = parser->pos; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { switch (js[parser->pos]) { #ifndef JSMN_STRICT /* In strict mode primitive must be followed by "," or "}" or "]" */ case ':': #endif case '\t' : case '\r' : case '\n' : case ' ' : case ',' : case ']' : case '}' : goto found; } if (js[parser->pos] < 32 || js[parser->pos] >= 127) { parser->pos = start; return JSMN_ERROR_INVAL; } } #ifdef JSMN_STRICT /* In strict mode primitive must be followed by a comma/object/array */ parser->pos = start; return JSMN_ERROR_PART; #endif found: if (tokens == NULL) { parser->pos--; return 0; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; return JSMN_ERROR_NOMEM; } jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif parser->pos--; return 0; } /** * Filsl next token with JSON string. */ static jsmnerr_t jsmn_parse_string(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *token; int start = parser->pos; parser->pos++; /* Skip starting quote */ for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { char c = js[parser->pos]; /* Quote: end of string */ if (c == '\"') { if (tokens == NULL) { return 0; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; return JSMN_ERROR_NOMEM; } jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif return 0; } /* Backslash: Quoted symbol expected */ if (c == '\\') { parser->pos++; switch (js[parser->pos]) { /* Allowed escaped symbols */ case '\"': case '/' : case '\\' : case 'b' : case 'f' : case 'r' : case 'n' : case 't' : break; /* Allows escaped symbol \uXXXX */ case 'u': parser->pos++; int i = 0; for(; i < 4 && js[parser->pos] != '\0'; i++) { /* If it isn't a hex character we have an error */ if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ parser->pos = start; return JSMN_ERROR_INVAL; } parser->pos++; } parser->pos--; break; /* Unexpected symbol */ default: parser->pos = start; return JSMN_ERROR_INVAL; } } } parser->pos = start; return JSMN_ERROR_PART; } /** * Parse JSON string and fill tokens. */ jsmnerr_t jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, unsigned int num_tokens) { jsmnerr_t r; int i; jsmntok_t *token; int count = 0; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { char c; jsmntype_t type; c = js[parser->pos]; switch (c) { case '{': case '[': count++; if (tokens == NULL) { break; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) return JSMN_ERROR_NOMEM; if (parser->toksuper != -1) { tokens[parser->toksuper].size++; #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif } token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); token->start = parser->pos; parser->toksuper = parser->toknext - 1; break; case '}': case ']': if (tokens == NULL) break; type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); #ifdef JSMN_PARENT_LINKS if (parser->toknext < 1) { return JSMN_ERROR_INVAL; } token = &tokens[parser->toknext - 1]; for (;;) { if (token->start != -1 && token->end == -1) { if (token->type != type) { return JSMN_ERROR_INVAL; } token->end = parser->pos + 1; parser->toksuper = token->parent; break; } if (token->parent == -1) { break; } token = &tokens[token->parent]; } #else for (i = parser->toknext - 1; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { if (token->type != type) { return JSMN_ERROR_INVAL; } parser->toksuper = -1; token->end = parser->pos + 1; break; } } /* Error if unmatched closing bracket */ if (i == -1) return JSMN_ERROR_INVAL; for (; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { parser->toksuper = i; break; } } #endif break; case '\"': r = jsmn_parse_string(parser, js, len, tokens, num_tokens); if (r < 0) return r; count++; if (parser->toksuper != -1 && tokens != NULL) tokens[parser->toksuper].size++; break; case '\t' : case '\r' : case '\n' : case ':' : case ',': case ' ': break; #ifdef JSMN_STRICT /* In strict mode primitives are: numbers and booleans */ case '-': case '0': case '1' : case '2': case '3' : case '4': case '5': case '6': case '7' : case '8': case '9': case 't': case 'f': case 'n' : #else /* In non-strict mode every unquoted value is a primitive */ default: #endif r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); if (r < 0) return r; count++; if (parser->toksuper != -1 && tokens != NULL) tokens[parser->toksuper].size++; break; #ifdef JSMN_STRICT /* Unexpected char in strict mode */ default: return JSMN_ERROR_INVAL; #endif } } for (i = parser->toknext - 1; i >= 0; i--) { /* Unmatched opened object or array */ if (tokens[i].start != -1 && tokens[i].end == -1) { return JSMN_ERROR_PART; } } return count; } /** * Creates a new parser based over a given buffer with an array of tokens * available. */ void jsmn_init(jsmn_parser *parser) { parser->pos = 0; parser->toknext = 0; parser->toksuper = -1; } mod-authz-securepass-0~20150105.gitda462d3/jsmn.h000066400000000000000000000052551245253275700212270ustar00rootroot00000000000000/* * Copyright (c) 2010 Serge A. Zaitsev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef __JSMN_H_ #define __JSMN_H_ #ifdef __cplusplus extern "C" { #endif /** * JSON type identifier. Basic types are: * o Object * o Array * o String * o Other primitive: number, boolean (true/false) or null */ typedef enum { JSMN_PRIMITIVE = 0, JSMN_OBJECT = 1, JSMN_ARRAY = 2, JSMN_STRING = 3 } jsmntype_t; typedef enum { /* Not enough tokens were provided */ JSMN_ERROR_NOMEM = -1, /* Invalid character inside JSON string */ JSMN_ERROR_INVAL = -2, /* The string is not a full JSON packet, more bytes expected */ JSMN_ERROR_PART = -3, } jsmnerr_t; /** * JSON token description. * @param type type (object, array, string etc.) * @param start start position in JSON data string * @param end end position in JSON data string */ typedef struct { jsmntype_t type; int start; int end; int size; #ifdef JSMN_PARENT_LINKS int parent; #endif } jsmntok_t; /** * JSON parser. Contains an array of token blocks available. Also stores * the string being parsed now and current position in that string */ typedef struct { unsigned int pos; /* offset in the JSON string */ unsigned int toknext; /* next token to allocate */ int toksuper; /* superior token node, e.g parent object or array */ } jsmn_parser; /** * Create JSON parser over an array of tokens */ void jsmn_init(jsmn_parser *parser); /** * Run JSON parser. It parses a JSON data string into and array of tokens, each describing * a single JSON object. */ jsmnerr_t jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, unsigned int num_tokens); #ifdef __cplusplus } #endif #endif /* __JSMN_H_ */ mod-authz-securepass-0~20150105.gitda462d3/mod_authz_securepass.c000077500000000000000000001013651245253275700245040ustar00rootroot00000000000000/* * * Authors: Alessandro Lorenzi * gplll * */ #include "apr_lib.h" #include "ap_config.h" #include "ap_provider.h" #include "mod_auth.h" #define APR_WANT_STRFUNC #include "apr_want.h" #include "apr_strings.h" #include "httpd.h" #include "http_config.h" #include "http_core.h" #include "http_log.h" #include "http_protocol.h" #include "http_request.h" /* for ap_hook_(check_user_id | auth_checker)*/ #include "util_md5.h" #include "curl/curl.h" #include "jsmn.h" #define DEFAULT_GROUP_TMO 600 #define DEFAULT_CACHE_CLEAN_ITV 1800 #define ERR_LINE_LEN 80 #define CACHE_LINE_LEN 80 #define CURL_BUF_LEN 4096 /* this size is exaggereted...but it's for free */ #define JSON_MAX_TOKENS 200 /* this size is exaggereted...but it's for free */ #define APP_ID "X-SecurePass-App-ID" #define APP_SECRET "X-SecurePass-App-Secret" #define ACCEPT "Accept: application/json" #define RC_STRING "rc" #define RC_STRING_LEN 2 #define RC_RESULT_OK "0" #define RC_RESULT_OK_LEN 1 #define MEMBER_STRING "member" #define MEMBER_STRING_LEN 6 #define MEMBER_RESULT_TRUE "true" #define MEMBER_RESULT_TRUE_LEN 4 #define MYDEBUG 1 /* set to 1 to enable pieces of code useful only during development/maintenance of this module */ /* * Structure for the module itself. The definition of this structure * is at the end of the file. */ module AP_MODULE_DECLARE_DATA authz_securepass_module; typedef enum { cmd_sp_debug, cmd_sp_check_group, cmd_sp_api, cmd_sp_appid, cmd_sp_app_secret, cmd_sp_cache_path, cmd_sp_group_tmo, cmd_sp_clean_itv } valid_cmds; /* Structure for server config */ typedef struct { int debug; int check_group; char *REST_url; char *app_id; char *app_secret; char *cache_path; int cache_group_tmo; int cache_clean_itv; } sp_cfg; /* * Data type for per-directory configuration */ typedef struct { int enabled; int authoritative; char *forced_user; /* only used to simulate CAS user during module development */ char *forced_group; /* only used to simulate a successful user-group mapping during module development */ } authz_securepass_dir_config_rec; typedef struct { char *fullpath; /* full pathname into filesystem */ char *name; /* unique name used to generate MD5 filename */ } sp_cache_file; struct sp_curl_buf { char buf[CURL_BUF_LEN]; size_t size; }; static size_t curl_callback(void *contents, size_t size, size_t nmemb, void *userp) { struct sp_curl_buf *cbuf = (struct sp_curl_buf *)userp; if((nmemb*size) + cbuf->size >= CURL_BUF_LEN) /* response is larger than allocated buffer - return KO */ return 0; /* copy received bytes into buffer */ memcpy((cbuf->buf + cbuf->size), contents, (nmemb*size)); cbuf->size += (nmemb*size); /* return OK */ return (nmemb*size); } static int get_from_URL (request_rec *r, const char *group) { CURLcode res; CURL *curl_handle; struct curl_slist *slist=NULL; struct sp_curl_buf cbuf; jsmn_parser p; jsmntok_t tokens[JSON_MAX_TOKENS]; int n, i, l; char *s; int rc = 0; int is_member = 0; sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: entering get_from_URL()"); /* always initialize curl library, as we don't know if some other module has called curl's in the meantime */ curl_global_init(CURL_GLOBAL_ALL); curl_handle = curl_easy_init(); if (!curl_handle) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass curl_easy_init failed"); return 0; } /* setup the request (URL, callback func, memory buffer, user agent) */ curl_easy_setopt(curl_handle, CURLOPT_URL, c->REST_url); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, curl_callback); cbuf.size = 0; curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&cbuf); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "mod_authz_securepass"); /* set SSL options - for now, don't validate server */ curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0L); /* add HTTP headers */ slist = curl_slist_append(slist, (s=apr_psprintf(r->pool, "%s:%s", APP_ID, c->app_id))); if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: AppID=%s", s); slist = curl_slist_append(slist, apr_psprintf(r->pool, "%s:%s", APP_SECRET, c->app_secret)); slist = curl_slist_append(slist, ACCEPT); curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, slist); /* attach POST data */ curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, (s=apr_psprintf(r->pool,"USERNAME=%s&GROUP=%s",r->user,group))); /* Send the request */ res = curl_easy_perform(curl_handle); if (res != CURLE_OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass curl_easy_perform() failed %s", curl_easy_strerror(res)); curl_easy_cleanup(curl_handle); return 0; } if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass curl_easy_perform() retrieved %lu bytes: %s", (long)cbuf.size, cbuf.buf); /* free resources allocated by curl */ curl_slist_free_all(slist); curl_easy_cleanup(curl_handle); curl_global_cleanup(); /* Parse response to get JSON object */ jsmn_init(&p); n = jsmn_parse(&p, cbuf.buf, cbuf.size, tokens, JSON_MAX_TOKENS); if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: found %d JSON tokens", n); for (i = 0; i < n; i++) { l = tokens[i].end-tokens[i].start; #if 0 // enable this code only if you're really desperate with JSON parsing if (c->debug) { s = apr_pcalloc(r->pool, l+1); memcpy(s, (cbuf.buf + tokens[i].start), l); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: Found JSON token: type=%s, value=%s", json_types[tokens[i].type], s); } #endif /* Look for a field like: "rc": 0 */ if ((tokens[i].type == JSMN_STRING) && (l == RC_STRING_LEN) && (!memcmp(cbuf.buf + tokens[i].start, RC_STRING, l))) { i++; if (i == n) break; l = tokens[i].end-tokens[i].start; if ((tokens[i].type == JSMN_PRIMITIVE) && (l == RC_RESULT_OK_LEN) && (!memcmp(cbuf.buf + tokens[i].start, RC_RESULT_OK, l))) { rc = 1; } if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: got RC=%s from RESTful API", ((rc) ? "OK" : "KO")); continue; } /* Look for a field like: "member": true */ if ((tokens[i].type == JSMN_STRING) && (l == MEMBER_STRING_LEN) && (!memcmp(cbuf.buf + tokens[i].start, MEMBER_STRING, MEMBER_STRING_LEN))) { i++; if (i == n) break; l = tokens[i].end-tokens[i].start; if ((tokens[i].type == JSMN_PRIMITIVE) && (l == MEMBER_RESULT_TRUE_LEN) && (!memcmp(cbuf.buf + tokens[i].start, MEMBER_RESULT_TRUE, l))) { is_member = 1; } if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: got member=%s from RESTful API", ((is_member) ? "true" : "false")); continue; } } if (rc && is_member) return 1; else return 0; } static void clean_cache(request_rec *r, sp_cfg *c) { apr_time_t last_clean; apr_off_t begin = 0; char *path; apr_file_t *lf, *cf; apr_status_t i; apr_dir_t *d; char line[ERR_LINE_LEN]; apr_finfo_t finfo; int file_is_new = 0; if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: entering clean_cache()"); path = apr_psprintf(r->pool, "%s.lastclean", c->cache_path); /* Open .lastclean file, holding time of last clean */ if(apr_file_open(&lf, path, APR_FOPEN_READ|APR_FOPEN_WRITE, APR_FPROT_UREAD|APR_FPROT_UWRITE, r->pool) != APR_SUCCESS) { /* file does not exist or cannot be opened - create it */ if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: .lastclean file %s doesn't exist...creating it", path); if((i = apr_file_open(&lf, path, (APR_FOPEN_WRITE|APR_FOPEN_CREATE), (APR_FPROT_UREAD|APR_FPROT_UWRITE), r->pool)) != APR_SUCCESS) { apr_strerror(i, line, ERR_LINE_LEN); ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, "SecurePass: Could not create cache .lastclean file '%s': %s", path, line); return; } file_is_new = 1; } apr_file_lock(lf, APR_FLOCK_EXCLUSIVE); apr_file_seek(lf, APR_SET, &begin); if (!file_is_new) { /* check if it is time to clean the cache */ apr_file_gets(line, ERR_LINE_LEN, lf); if(sscanf(line, "%" APR_TIME_T_FMT, &last_clean) != 1) { /* corrupt file */ apr_file_unlock(lf); apr_file_close(lf); apr_file_remove(path, r->pool); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass: Cache .lastclean file has been found corrupted and has been removed"); return; } if(last_clean > (apr_time_now()-(c->cache_clean_itv*((apr_time_t) APR_USEC_PER_SEC)))) { /* not enough time has elapsed */ /* release the locks and file descriptors that we no longer need */ apr_file_unlock(lf); apr_file_close(lf); if(c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: Cache not cleaned as not enough time has elapsed"); return; } apr_file_seek(lf, APR_SET, &begin); apr_file_trunc(lf, begin); } if(c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: Beginning cache clean"); apr_file_printf(lf, "%" APR_TIME_T_FMT "\n", apr_time_now()); apr_file_unlock(lf); apr_file_close(lf); /* read all the files in the directory */ if(apr_dir_open(&d, c->cache_path, r->pool) != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, "SecurePass: Error opening cache directory '%s' for cleaning", c->cache_path); return; } do { i = apr_dir_read(&finfo, APR_FINFO_NAME, d); if(i == APR_SUCCESS) { if(finfo.name[0] == '.') /* skip hidden files and parent directories */ continue; path = apr_psprintf(r->pool, "%s%s", c->cache_path, finfo.name); if(c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: Processing cache file '%s'", finfo.name); /* open file */ if(apr_file_open(&cf, path, APR_FOPEN_READ, APR_OS_DEFAULT, r->pool) != APR_SUCCESS) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass: Unable to clean cache file '%s'", path); continue; } /* look if time has elapsed */ apr_file_gets(line, ERR_LINE_LEN, cf); if(sscanf(line, "%" APR_TIME_T_FMT, &last_clean) != 1) { /* corrupt file */ apr_file_close(cf); apr_file_remove(path, r->pool); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass: Cache file %s has been found corrupted and has been removed", path); continue; } if(last_clean > (apr_time_now()-(c->cache_group_tmo*((apr_time_t) APR_USEC_PER_SEC)))) { /* not enough time has elapsed */ /* release the locks and file descriptors that we no longer need */ apr_file_close(cf); if(c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: Cache file %s not removed as time isn't expired", path); continue; } else { /* delete this file since it is no longer valid */ apr_file_close(cf); apr_file_remove(path, r->pool); if(c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: Cache file %s removed as time is expired", path); } } } while (i == APR_SUCCESS); apr_dir_close(d); } static void build_file_info (request_rec *r, const char *group, sp_cache_file *cfile) { char *rv; sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); /* * to create a unique name into filesystem, we need: URL of RESTful API, user name, group name */ cfile->name = apr_psprintf(r->pool, "%s-%s-%s", c->REST_url, r->user, group); // generate md5 string rv = (char *) ap_md5(r->pool, (unsigned char *) cfile->name); // build full pathname cfile->fullpath = apr_psprintf(r->pool, "%s%s", c->cache_path, rv); } static int get_from_cache (request_rec *r, const char *group) { sp_cache_file cfile; apr_file_t *f; char line[CACHE_LINE_LEN]; apr_time_t last_clean; sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: entering get_from_cache()"); build_file_info(r, group, &cfile); /* Open cache file, holding time of last query to RESTful URL */ if (apr_file_open(&f, cfile.fullpath, APR_FOPEN_READ|APR_FOPEN_WRITE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS) { /* file does not exist or cannot be opened */ if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: cache file %s for entry %s doesn't exist", cfile.fullpath, cfile.name); return 0; } /* look if time has elapsed */ apr_file_gets(line, CACHE_LINE_LEN, f); if(sscanf(line, "%" APR_TIME_T_FMT, &last_clean) != 1) { /* corrupt file */ apr_file_close(f); apr_file_remove(cfile.fullpath, r->pool); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass: Cache file %s for entry %s has been found corrupted and has been removed", cfile.fullpath, cfile.name); return 0; } if(last_clean > (apr_time_now()-(c->cache_group_tmo*((apr_time_t) APR_USEC_PER_SEC)))) { /* cache file is still valid */ apr_file_close(f); if(c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: Cache file %s for entry %s is valid", cfile.fullpath, cfile.name); return 1; } else { /* delete this file since it is no longer valid */ apr_file_close(f); apr_file_remove(cfile.fullpath, r->pool); if(c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: Cache file %s for entry %s removed as cache time is expired", cfile.fullpath, cfile.name); return 0; } } static void write_to_cache (request_rec *r, const char *group) { char *name, *fullpath; char errmsg[80]; apr_file_t *f; apr_status_t i = APR_EGENERAL; apr_off_t begin = 0; sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: entering write_to_cache; group= %s", group); /* First of all, remove expired files, if Cache Clean Interval has passes */ clean_cache (r, c); if (c->cache_group_tmo == 0) { if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: cache file for user %s, group %s, not created as AuthzSecurepassGroupTimeout is set to 0", r->user, group); return; } /* to create a unique name for file, we need: URL of RESTful API, user name, group name */ name = apr_psprintf(r->pool, "%s-%s-%s", c->REST_url, r->user, group); /* build full pathname concatenating directory name and generated MD5 string */ fullpath = apr_psprintf(r->pool, "%s%s", c->cache_path, (char *) ap_md5(r->pool, (unsigned char *) name)); //create file if((i = apr_file_open(&f, fullpath, APR_FOPEN_CREATE|APR_FOPEN_WRITE|APR_EXCL, APR_FPROT_UREAD|APR_FPROT_UWRITE, r->pool)) != APR_SUCCESS) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass: cache file %s for entry %s could not be created: %s", fullpath, name, apr_strerror(i, errmsg, 80)); return; } if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: created file %s for cache entry %s", fullpath, name); /* write current time */ apr_file_seek(f, APR_SET, &begin); apr_file_trunc(f, begin); apr_file_printf(f, "%" APR_TIME_T_FMT "\n", apr_time_now()); apr_file_close(f); } static int check_securepass_realm(request_rec *r, const char *realmlist) { char *user= r->user; char *realm,*w; sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); // estrapolo il realm dell'utente realm=strchr(user,'@'); realm++; /* Loop through list of realms passed in */ while (*realmlist != '\0') { // get next realm from 'Require sprealm ...' line w= ap_getword_conf(r->pool, &realmlist); if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: checking realm %s", w); //check if equals to user realm if (strcmp(realm,w)==0) { return 1; } } return 0; } static int check_sp_group (request_rec *r, const char *grouplist) { char *w; authz_securepass_dir_config_rec *dir= (authz_securepass_dir_config_rec *) ap_get_module_config(r->per_dir_config, &authz_securepass_module); sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); #if MYDEBUG /* this is only for debugging/testing purposes during module development */ if (c->debug && dir->forced_group) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: setting group %s", dir->forced_group); if (!get_from_cache(r, dir->forced_group)) { write_to_cache (r, dir->forced_group); } return (1); } #endif /* Loop through list of groups passed in */ while (*grouplist != '\0') { // get all required groups from the request w= ap_getword_conf(r->pool, &grouplist); if (c->debug) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: checking group %s", w); /* see if mapping between user and group is cached */ if (get_from_cache(r,w)) { /* User belong to group */ return(1); } /* check if user belongs to group querying RESTFul API URL */ if (get_from_URL(r,w)) { /* User belong to group */ write_to_cache (r, w); return(1); } } return 0; } /* This is a debug function to dump current directory and vserver config */ static void dump_config (request_rec *r, authz_securepass_dir_config_rec *dir, sp_cfg *c) { /*ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass server=%s", r->server->defn_name);*/ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass enabled=%d, debug=%d, check_group=%d REST_url=%s, cache_group_tmo=%d", dir->enabled, c->debug, c->check_group, c->REST_url, c->cache_group_tmo); } /* Creator per server configuration*/ static void *create_authz_securepass_server_config (apr_pool_t *pool, server_rec *svr) { sp_cfg *c = apr_pcalloc(pool, sizeof(sp_cfg)); c->check_group = TRUE; c->debug = FALSE; c->cache_group_tmo = DEFAULT_GROUP_TMO; c->REST_url = NULL; c->app_id = NULL; c->app_secret = NULL; c->cache_path = NULL; c->cache_clean_itv = DEFAULT_CACHE_CLEAN_ITV; return c; } static void *merge_authz_securepass_server_config (apr_pool_t *pool, void *BASE, void *ADD) { sp_cfg *c = apr_pcalloc(pool, sizeof(sp_cfg)); sp_cfg *base = BASE; sp_cfg *add = ADD; c->check_group =(add->check_group != TRUE ? add->check_group : base->check_group); c->debug =(add->debug != FALSE ? add->debug : base->debug); c->cache_group_tmo =(add->cache_group_tmo != DEFAULT_GROUP_TMO ? add->cache_group_tmo : base->cache_group_tmo); if (add->REST_url != NULL) c->REST_url = apr_pstrdup(pool, add->REST_url); else c->REST_url = apr_pstrdup(pool, base->REST_url); if (add->app_id != NULL) c->app_id = apr_pstrdup(pool, add->app_id); else c->app_id = apr_pstrdup(pool, base->app_id); if (add->app_secret != NULL) c->app_secret = apr_pstrdup(pool, add->app_secret); else c->app_secret = apr_pstrdup(pool, base->app_secret); if (add->cache_path != NULL) c->cache_path = apr_pstrdup(pool, add->cache_path); else c->cache_path = apr_pstrdup(pool, base->cache_path); c->cache_clean_itv =(add->cache_clean_itv != DEFAULT_CACHE_CLEAN_ITV ? add->cache_clean_itv : base->cache_clean_itv); return c; } /* * Creator for per-dir configurations. This is called via the hook in the * module declaration to allocate and initialize the per-directory * configuration data structures declared above. */ static void *create_authz_securepass_dir_config(apr_pool_t *p, char *d) { authz_securepass_dir_config_rec *dir= (authz_securepass_dir_config_rec *) apr_palloc(p, sizeof(authz_securepass_dir_config_rec)); dir->enabled= 0; dir->authoritative= 1; /* strong by default */ dir->forced_user = NULL; dir->forced_group = NULL; return dir; } static const char *read_sp_param(cmd_parms *cmd, void *cfg, const char *value) { apr_finfo_t f; sp_cfg *c = (sp_cfg *) ap_get_module_config(cmd->server->module_config, &authz_securepass_module); switch((size_t) cmd->info) { case cmd_sp_debug: if(apr_strnatcasecmp(value, "On") == 0) c->debug = TRUE; else if(apr_strnatcasecmp(value, "Off") == 0) c->debug = FALSE; break; case cmd_sp_check_group: if(apr_strnatcasecmp(value, "On") == 0) c->check_group = TRUE; else if(apr_strnatcasecmp(value, "Off") == 0) c->check_group = FALSE; break; case cmd_sp_group_tmo: c->cache_group_tmo = atoi(value); break; case cmd_sp_api: c->REST_url = apr_pstrdup(cmd->pool, value); break; case cmd_sp_appid: c->app_id = apr_pstrdup(cmd->pool, value); break; case cmd_sp_app_secret: c->app_secret = apr_pstrdup(cmd->pool, value); break; case cmd_sp_clean_itv: c->cache_clean_itv = atoi(value); break; case cmd_sp_cache_path: if(apr_stat(&f, value, APR_FINFO_TYPE, cmd->temp_pool) != APR_SUCCESS) return(apr_psprintf(cmd->pool, "Securepass: Could not find AuthzSecurepassGroupCachePath '%s'", value)); if(f.filetype != APR_DIR || value[strlen(value)-1] != '/') return(apr_psprintf(cmd->pool, "Securepass:: AuthzSecurepassGroupCachePath '%s' is not a directory or does not end in a trailing '/'!", value)); c->cache_path = apr_pstrdup(cmd->pool, value); /* this is just an example in case we want to log passed parameters*/ /*ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, "SecurePass: AuthzSecurepassGroupCachePath = %s", c->cache_path);*/ break; default: /* should not happen */ return(apr_psprintf(cmd->pool, "SecurePass: invalid command '%s'", cmd->directive->directive)); } return NULL; } /* * Config file commands that this module can handle */ static const command_rec authz_securepass_cmds[] = { /* Server directives */ AP_INIT_TAKE1("AuthzSecurepassDebug", read_sp_param, (void *) cmd_sp_debug, RSRC_CONF, "Set to On to enable SecurePass debug"), AP_INIT_TAKE1("AuthzSecurepassCheckGroup", read_sp_param, (void *) cmd_sp_check_group, RSRC_CONF, "Set to Off to disable checking of group associated to the user"), AP_INIT_TAKE1("AuthzSecurepassRESTfulAPI", read_sp_param, (void *) cmd_sp_api, RSRC_CONF, "URL of RESTful API where to check if a user belongs to a group"), AP_INIT_TAKE1("AuthzSecurepassAppID", read_sp_param, (void *) cmd_sp_appid, RSRC_CONF, "Value of X-SecurePass-App-ID to be inserted into HTTP header to invoke Securepass RESTful API"), AP_INIT_TAKE1("AuthzSecurepassAppSecret", read_sp_param, (void *) cmd_sp_app_secret, RSRC_CONF, "Value of X-SecurePass-App-Secret to be inserted into HTTP header to invoke Securepass RESTful API"), AP_INIT_TAKE1("AuthzSecurepassGroupCachePath", read_sp_param, (void *) cmd_sp_cache_path, RSRC_CONF, "The file system directory where mappings betweeen users and Securepass groups are cached"), AP_INIT_TAKE1("AuthzSecurepassGroupTimeout", read_sp_param, (void *) cmd_sp_group_tmo, RSRC_CONF, "Define the timeout of cached group for each user"), AP_INIT_TAKE1("AuthzSecurepassCacheCleanInterval", read_sp_param, (void *) cmd_sp_clean_itv, RSRC_CONF, "The minimum amount of time that must pass inbetween cache cleanings"), /* Directory directives */ AP_INIT_FLAG("AuthzSecurepass", ap_set_flag_slot, (void *)APR_OFFSETOF(authz_securepass_dir_config_rec, enabled), OR_AUTHCFG, "Set to 'on' to enable SecurePass module"), AP_INIT_FLAG("AuthzSecurepassAuthoritative", ap_set_flag_slot, (void *)APR_OFFSETOF(authz_securepass_dir_config_rec, authoritative), OR_AUTHCFG, "Set to 'off' to allow access control to be passed along to lower " "modules if this module can't confirm access rights" ), AP_INIT_TAKE1("AuthzSecurepassForceUser", ap_set_string_slot, (void *)APR_OFFSETOF(authz_securepass_dir_config_rec, forced_user), OR_AUTHCFG, "only used during module development to simulate CAS user"), AP_INIT_TAKE1("AuthzSecurepassForceGroup", ap_set_string_slot, (void *)APR_OFFSETOF(authz_securepass_dir_config_rec, forced_group), OR_AUTHCFG, "only used during module development to simulate a succesful mapping between user and group"), { NULL } }; #if (AP_SERVER_MINORVERSION_NUMBER == 4) static const char *sp_parse_config(cmd_parms *cmd, const char *require_line, const void **parsed_require_line) { const char *expr_err = NULL; ap_expr_info_t *expr; ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, "SecurePass: entering sp_parse_config(), require_line=%s", require_line); expr = ap_expr_parse_cmd(cmd, require_line, AP_EXPR_FLAG_STRING_RESULT, &expr_err, NULL); if (expr_err) return (apr_pstrcat(cmd->temp_pool, "Cannot parse expression in require line: ", expr_err, NULL)); *parsed_require_line = expr; return NULL; } static authz_status sprealm_check_authorization(request_rec *r, const char *require_args, const void *parsed_require_args) { authz_securepass_dir_config_rec *dir= (authz_securepass_dir_config_rec *) ap_get_module_config(r->per_dir_config, &authz_securepass_module); sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); const char *err = NULL; const ap_expr_info_t *expr = parsed_require_args; const char *require; if (c->debug) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass checking user %s, required_sprealms=%s", r->user, require_args); dump_config (r, dir, c); } #if MYDEBUG /* this is only used during module development to simulate CAS user */ if (dir->forced_user) { if (!r->user) { /* CAS has not been invoked yet */ return AUTHZ_DENIED_NO_USER; } else { /* CAS has been invoked - substitute the user with MY user */ r->user = apr_pcalloc(r->pool, 100); strcpy (r->user, dir->forced_user); } } #endif if (!r->user) { return AUTHZ_DENIED_NO_USER; } require = ap_expr_str_exec(r, expr, &err); if (err) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass: Can't evaluate expression: %s", err); return AUTHZ_DENIED; } if (c->debug) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: require=%s", require); } if (check_securepass_realm (r, require)) { /* a Realm has been found */ return AUTHZ_GRANTED; } else { return AUTHZ_DENIED; } } static authz_status spgroup_check_authorization(request_rec *r, const char *require_args, const void *parsed_require_args) { authz_securepass_dir_config_rec *dir= (authz_securepass_dir_config_rec *) ap_get_module_config(r->per_dir_config, &authz_securepass_module); sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); const char *err = NULL; const ap_expr_info_t *expr = parsed_require_args; const char *require; if (c->debug) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass checking user %s, required_spgroups=%s", r->user, require_args); } #if MYDEBUG /* this is only used during module development to simulate CAS user */ if (dir->forced_user) { if (!r->user) { /* CAS has not been invoked yet */ return AUTHZ_DENIED_NO_USER; } else { /* CAS has been invoked - substitute the user with MY user */ r->user = apr_pcalloc(r->pool, 100); strcpy (r->user, dir->forced_user); } } #endif if (!r->user) { return AUTHZ_DENIED_NO_USER; } require = ap_expr_str_exec(r, expr, &err); if (err) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "SecurePass: Can't evaluate expression: %s", err); return AUTHZ_DENIED; } if (c->debug) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass: require=%s", require); } if (check_sp_group (r, require)) { return AUTHZ_GRANTED; } else { return AUTHZ_DENIED; } } #else // (AP_SERVER_MINORVERSION_NUMBER == 4) static int authz_securepass_check_user_access(request_rec *r) { authz_securepass_dir_config_rec *dir= (authz_securepass_dir_config_rec *) ap_get_module_config(r->per_dir_config, &authz_securepass_module); sp_cfg *c = (sp_cfg *) ap_get_module_config(r->server->module_config, &authz_securepass_module); int m= r->method_number; register int x; const char *t, *w; const apr_array_header_t *reqs_arr= ap_requires(r); require_line *reqs; int realm_requested = 0; int group_requested = 0; int realm_found = 0; int group_found = 0; #if MYDEBUG /* this is only used during module development to simulate CAS user */ if (dir->forced_user) { r->user = apr_pcalloc(r->pool, 100); strcpy (r->user, dir->forced_user); } #endif if (c->debug) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass checking user %s", r->user); dump_config (r, dir, c); } /* If not enabled, pass */ if ( !dir->enabled ) return DECLINED; /* If there are no Require arguments, pass */ if (!reqs_arr) return DECLINED; reqs= (require_line *)reqs_arr->elts; /* Loop through the "Require" argument list */ for(x= 0; x < reqs_arr->nelts; x++) { if (!(reqs[x].method_mask & (AP_METHOD_BIT << m))) continue; t= reqs[x].requirement; w= ap_getword_white(r->pool, &t); /* Check if user belongs to required realm */ if ( !strcasecmp(w, "sprealm") && !realm_found) { realm_requested = 1; if (check_securepass_realm(r,t)){ /* a Realm has been found - don't check for more lines sprealm, in case they exist */ realm_found=1; } } /* Check if user belongs to required group */ if ((c->check_group) && (!strcasecmp(w, "spgroup")) && (!group_found)) { group_requested = 1; if (check_sp_group(r,t)) { /* User belongs to required group - don't check for more lines spgroup, in case they exist */ group_found=1; } } } if (c->debug) { if (realm_requested) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass user %s is %sin realm list", r->user, ((realm_found) ? "":"NOT ")); if (group_requested) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass user %s is %sin required group", r->user, ((group_found) ? "":"NOT ")); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "SecurePass realm_requested=%u realm_found= %u group_requested=%u group_found=%u", realm_requested, realm_found, group_requested, group_found); } if ((!realm_requested||realm_found) && (!group_requested||group_found)) { return OK; } /* If we aren't authoritive, decline */ if (!dir->authoritative) return DECLINED; /* Authentication failed and we are authoritive, declare unauthorized */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "access to %s failed, reason: user %s not allowed access", r->uri, r->user); ap_note_basic_auth_failure(r); return HTTP_UNAUTHORIZED; } #endif static int authz_sp_post_config(apr_pool_t *pool, apr_pool_t *p1, apr_pool_t *p2, server_rec *s) { int status = OK; ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "SecurePass entering authz_sp_post_config()"); while (s != NULL && status == OK) { sp_cfg *c = (sp_cfg *) ap_get_module_config(s->module_config, &authz_securepass_module); if (c->debug) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "SecurePass: server->defn_name=%s", s->defn_name); ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "SecurePass: c->REST_url=%s", c->REST_url); ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "SecurePass: c->cache_path=%s", c->cache_path); } if (c->REST_url == NULL) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "SecurePass: directive AuthzSecurepassRESTfulAPI is not configured!"); status = HTTP_INTERNAL_SERVER_ERROR; } if (c->app_id == NULL) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "SecurePass: directive AuthzSecurepassAppID is not configured!"); status = HTTP_INTERNAL_SERVER_ERROR; } if (c->app_secret == NULL) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "SecurePass: directive AuthzSecurepassAppSecret is not configured!"); status = HTTP_INTERNAL_SERVER_ERROR; } if (c->cache_path == NULL) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "SecurePass: directive AuthzSecurepassGroupCachePath is not configured!"); status = HTTP_INTERNAL_SERVER_ERROR; } s = s->next; } return status; } #if (AP_SERVER_MINORVERSION_NUMBER == 4) static const authz_provider authz_sprealm_provider = { &sprealm_check_authorization, &sp_parse_config, }; static const authz_provider authz_spgroup_provider = { &spgroup_check_authorization, &sp_parse_config, }; #endif static void authz_securepass_register_hooks(apr_pool_t *p) { ap_hook_post_config(authz_sp_post_config, NULL, NULL, APR_HOOK_LAST); #if (AP_SERVER_MINORVERSION_NUMBER == 4) /* Register authz providers */ ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "sprealm", AUTHZ_PROVIDER_VERSION, &authz_sprealm_provider, AP_AUTH_INTERNAL_PER_CONF); ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "spgroup", AUTHZ_PROVIDER_VERSION, &authz_spgroup_provider, AP_AUTH_INTERNAL_PER_CONF); #else ap_hook_auth_checker(authz_securepass_check_user_access, NULL, NULL, APR_HOOK_MIDDLE); #endif } module AP_MODULE_DECLARE_DATA authz_securepass_module = { STANDARD20_MODULE_STUFF, create_authz_securepass_dir_config, /* create per-dir config */ NULL, /* merge per-dir config */ create_authz_securepass_server_config, /* create per-server config */ merge_authz_securepass_server_config, /* merge per-server config */ authz_securepass_cmds, /* command apr_table_t */ authz_securepass_register_hooks /* register hooks */ }; mod-authz-securepass-0~20150105.gitda462d3/mod_authz_securepass.conf000066400000000000000000000001031245253275700251700ustar00rootroot00000000000000LoadModule authz_securepass_module modules/mod_authz_securepass.so mod-authz-securepass-0~20150105.gitda462d3/mod_authz_securepass.spec000066400000000000000000000030151245253275700252020ustar00rootroot00000000000000%global commit 515f59a2731c0b9350a96f2fe4703e5d9e2c8903 %global shortcommit %(c=%{commit}; echo ${c:0:7}) Name: mod_authz_securepass Summary: Apache 2.0/2.2/2.4 compliant module that supports authorization via SecurePass Version: 1.1 Release: 1 Source0: https://github.com/garlsecurity/%{name}/archive/%{version}/%{name}-v%{version}.tar.gz URL: https://github.com/garlsecurity/mod_authz_securepass Group: System Environment/Daemons License: GPLv2+ BuildRoot: %{_tmppath}/%{name}-root BuildRequires: libcurl-devel BuildRequires: httpd-devel Requires: libcurl %description mod_authz_securepass is an Apache module that supports authorization via SecurePass. SecurePass provides identity management and web single sign-on through the CAS protocol. %prep %setup -qn %{name}-%{version} %build make %install [ "$RPM_BUILD_ROOT" != "/" ] && rm -rf $RPM_BUILD_ROOT mkdir -p $RPM_BUILD_ROOT/%{_libdir}/httpd/modules/ mkdir -p $RPM_BUILD_ROOT/etc/httpd/conf.d/ install -m 755 build/.libs/mod_authz_securepass.so $RPM_BUILD_ROOT/%{_libdir}/httpd/modules/ install mod_authz_securepass.conf $RPM_BUILD_ROOT/etc/httpd/conf.d/ %clean [ "$RPM_BUILD_ROOT" != "/" ] && rm -rf $RPM_BUILD_ROOT %files %defattr(-,root,root,-) %doc LICENSE INSTALL README.md %{_libdir}/httpd/modules/*.so %config(noreplace) /etc/httpd/conf.d/*.conf %changelog * Tue Jan 5 2015 Giuseppe Paterno' (gpaterno@garl.ch) - Ported module to Apache 2.4 * Fri Nov 7 2014 Giuseppe Paterno' (gpaterno@garl.ch) - First RPM of the SecurePass Apache authrization module