/* ====================================================================
 * Copyright (c) 1998 Thawte Consulting.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by Thawte Consulting
 *    and implements the Thawte Strong Extranet Version 1.1."
 *
 * 4. The names "Strong Extranet" and "Thawte" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission.
 *
 * 5. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by Thawte Consulting
 *    and implements the Thawte Strong Extranet Version 1.1."
 *
 * THIS SOFTWARE IS PROVIDED BY THAWTE CONSULTING ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THAWTE CONSULTING OR
 * ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 */

/*
 * This is a direct adaptation of the Apache Group's mod_auth.c, and
 * all Apache Group copyrights apply:
 *
 *   "This product includes software developed by the Apache Group
 *   for use in the Apache HTTP server project (http://www.apache.org/)."
 */


/*
 * Module Definition Information for Apache 1.3 and later
 *
 * MODULE-DEFINITION-START
 * Name: sxnet_module
 * ConfigStart
 * ConfigEnd
 * MODULE-DEFINITION-END
 */


#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"
#include "sxnet.h"
#include "sxnet.c"
#include "crypto.h"
#if defined(HAVE_CRYPT_H)
#include <crypt.h>
#endif



/*
 * Per-Directory Strong Extranet Configuration
*/ 
typedef struct sxnet_config_struct {
    int   sxnet_zone;
    char *sxnet_grpfile;
    int   sxnet_uencode;
} sxnet_config_rec;



/*
 * Create the per-directory config
*/
static void *create_sxnet_dir_config (pool *p, char *d)
{
    sxnet_config_rec *sec =
    	(sxnet_config_rec *) ap_pcalloc (p, sizeof(sxnet_config_rec));
    sec->sxnet_zone = 0;          /* just to illustrate the default really */ 
    sec->sxnet_grpfile = NULL;    /* unless you have a broken HP cc */
    sec->sxnet_uencode = 0;       /* most id's are normal text */
    return sec;
}



/*
 * set a zone number in a per-diectory config
 */
static const char *set_sxnet_zone_slot (cmd_parms *cmd, void *sxnet_dcfg, char *zone)
{
    int offset = (int)cmd->info;
   *(int *)((char *)sxnet_dcfg + offset) = atoi(zone);
    return NULL;
}


/*
 * Module Commands
*/
static command_rec sxnet_cmds[] = {
{ "SXNetZone", set_sxnet_zone_slot,
  (void*)XtOffsetOf(sxnet_config_rec,sxnet_zone), OR_AUTHCFG, TAKE1, 
  "a zone number"},
{ "SXNetB64EncodeID", ap_set_flag_slot,
  (void*)XtOffsetOf(sxnet_config_rec,sxnet_uencode), OR_AUTHCFG, FLAG,
   "Set to 'yes' if you want the username Base64 encoded (for 8-bit id's)" },
{ "SXNetGroupFile", ap_set_string_slot,
  (void*)XtOffsetOf(sxnet_config_rec,sxnet_grpfile), OR_AUTHCFG, TAKE1, 
  "a group file"},
{ NULL }
};


module sxnet_module;



/*
 * Get a set of groups for a particular user
*/
static table *sxnet_user_groups (pool *p, char *user, char *grpfile) {
    configfile_t *f;
    table *grps = ap_make_table (p, 15);
    pool *sp;
    char l[MAX_STRING_LEN];
    const char *group_name, *ll, *w;

    if (!(f = ap_pcfg_openfile(p, grpfile))) {
        return NULL;
        }

    sp = ap_make_sub_pool (p);
    
    while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
        if((l[0] == '#') || (!l[0])) continue;
	ll = l;
	ap_clear_pool (sp);
	
   group_name = ap_getword(sp, &ll, ':');

	while (ll[0]) {
	    w = ap_getword_conf(sp, &ll);
	    if(!strcmp(w,user)) {
		ap_table_setn(grps, ap_pstrdup(p, group_name), "in");
		break;
	    }
	}
    }
    ap_cfg_closefile(f);
    ap_destroy_pool(sp);
    return grps;
}



/* These functions return 0 if client is OK, and proper error status
 * if not... either FORBIDDEN, if we made a check, and it failed, or
 * SERVER_ERROR, if things are so totally confused that we couldn't
 * figure out how to tell if the client is authorized or not.
 *
 * If they return DECLINED, and all other modules also decline, that's
 * treated by the server core as a configuration error, logged and
 * reported as such.
 */





/* 
 * Extract the Strong Extranet ID if one is present for the specified
 * Strong Extranet Zone.
 */

static int authenticate_sxnet_user (request_rec *r)
{
    sxnet_config_rec *sec =
      (sxnet_config_rec *)ap_get_module_config (r->per_dir_config, &sxnet_module);
    char errstr[MAX_STRING_LEN];
    const char *t;
    int idcount;
    THAWTE_SXNET_IDLIST *ids;
    THAWTE_SXNET_ID *id;
    char *username;
    char *tmpusr;
    X509 *clientcert;
    
/* 
 * do the core checking done by get_basic_auth_pw for Basic auth
 */
    if(!(t = ap_auth_type(r)) || strcasecmp(t, "StrongExtranet"))
        return DECLINED;

    if (!ap_auth_name (r)) {
        ap_log_reason ("Need AuthName for StrongExtranet", r->uri, r);
        return SERVER_ERROR;
    }

/*
 * check if a zone has been set, and show a server error if not
 */
    if(!sec->sxnet_zone) {
        ap_log_reason ("AuthType StrongExtranet requires SXNetZone", r->uri, r);
        return SERVER_ERROR;
    }

/*
 * Retrieve the client cert.  Fail if none was presented.
 */
#if defined(APACHE_SSL) || defined(MOD_SSL) || defined(STRONGHOLD)
   clientcert = SSL_get_peer_certificate(r->connection->client->ssl);
#endif
   if(!clientcert) {
        ap_snprintf(errstr, sizeof(errstr), "No client certificate presented.");
	ap_log_reason (errstr, r->uri, r);
	return HTTP_FORBIDDEN;
    }

/*
 * check if the client cert has a strong extranet extension
 */
   idcount=THAWTE_SXNET_extract_list(clientcert, NULL);
   if(idcount<=0) {
        ap_snprintf(errstr, sizeof(errstr), "Client certificate has no Strong Extranet ID.");
	ap_log_reason (errstr, r->uri, r);
	return HTTP_FORBIDDEN;
    }
      
/*
 * check if the client cert strong extranet extension has an id for
 * the specified zone
 */
   ids=(THAWTE_SXNET_IDLIST *)ap_palloc(r->pool, sizeof(int)+idcount*sizeof(THAWTE_SXNET_ID));
   idcount=THAWTE_SXNET_extract_list(clientcert, &ids);
   id=THAWTE_extract_zone(ids, sec->sxnet_zone);
   if (!id) {
        ap_snprintf(errstr, sizeof(errstr), "Strong Extranet ID List has no ID in the required Zone.");
	ap_log_reason (errstr, r->uri, r);
	return HTTP_FORBIDDEN;
    }

/*
 * make space for the username. use the b64 encoding if required
 */
    if (sec->sxnet_uencode) {
       tmpusr = (char *)binaryToBase64(id->id, id->idLength);
       if (tmpusr==NULL) {
          ap_snprintf(errstr, sizeof(errstr), "Malloc error for B64 SXNet ID.");
          ap_log_reason (errstr, r->uri, r);
          return SERVER_ERROR;
          };
       username = (char *)ap_palloc(r->pool, strlen(tmpusr)+1);
       strcpy(username, tmpusr);
       Free(tmpusr);
       }
    else {
       username = (char *)ap_palloc(r->pool, (id->idLength)+1);
       if (username==NULL) {
           ap_snprintf(errstr, sizeof(errstr), "Malloc error for SXNet ID.");
           ap_log_reason (errstr, r->uri, r);
           return SERVER_ERROR;
           };
       memset(username, 0, id->idLength+1);
       memcpy(username, id->id, id->idLength);
       };
    r->connection->user = username;
    return OK;
}



/* Checking ID */
static int check_sxnet_auth (request_rec *r) {
    sxnet_config_rec *sec =
      (sxnet_config_rec *)ap_get_module_config (r->per_dir_config, &sxnet_module);
    char *user = r->connection->user;
    int m = r->method_number;
    int method_restricted = 0;
    register int x;
    const char *t, *w;
    table *grpstatus;
    const array_header *reqs_arr = ap_requires(r);
    require_line *reqs;

    /* BUG FIX: tadc, 11-Nov-1995.  If there is no "requires" directive, 
     * then any user will do.
     */
    if (!reqs_arr)
        return (OK);
    reqs = (require_line *)reqs_arr->elts;

    if(sec->sxnet_grpfile)
        grpstatus = sxnet_user_groups (r->pool, user, sec->sxnet_grpfile);
    else
        grpstatus = NULL;

    for(x=0; x < reqs_arr->nelts; x++) {
      
	if (! (reqs[x].method_mask & (1 << m))) continue;
	
	method_restricted = 1;

        t = reqs[x].requirement;
        w = ap_getword(r->pool, &t, ' ');
        if(!strcmp(w,"valid-user"))
            return OK;
        if(!strcmp(w,"user")) {
            while(t[0]) {
                w = ap_getword_conf (r->pool, &t);
                if(!strcmp(user,w))
                    return OK;
            }
        }
        else if(!strcmp(w,"group")) {
            if(!grpstatus) 
	        return DECLINED;	/* DBM group?  Something else? */
	    
            while(t[0]) {
                w = ap_getword_conf(r->pool, &t);
                if(ap_table_get (grpstatus, w))
		    return OK;
            }
        }
    }
    
    if (!method_restricted)
      return OK;

    return HTTP_FORBIDDEN;
}



module sxnet_module = {
   STANDARD_MODULE_STUFF,
   NULL,			/* initializer */
   create_sxnet_dir_config,	/* dir config creater */
   NULL,			/* dir merger --- default is to override */
   NULL,			/* server config */
   NULL,			/* merge server config */
   sxnet_cmds,			/* command table */
   NULL,			/* handlers */
   NULL,			/* filename translation */
   authenticate_sxnet_user,	/* check_user_id */
   check_sxnet_auth,		/* check auth */
   NULL,			/* check access */
   NULL,			/* type_checker */
   NULL,			/* fixups */
   NULL,			/* logger */
   NULL				/* header parser */
};


