File:  [LON-CAPA] / loncom / auth / lonacc.pm
Revision 1.111: download - view: text, annotated - select for diffs
Tue Oct 2 01:09:59 2007 UTC (16 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- convert exisiting cookie reads/validations to use
   lonnet::check_for_valid_session

    1: # The LearningOnline Network
    2: # Cookie Based Access Handler
    3: #
    4: # $Id: lonacc.pm,v 1.111 2007/10/02 01:09:59 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonacc;
   31: 
   32: use strict;
   33: use Apache::Constants qw(:common :http :methods);
   34: use Apache::File;
   35: use Apache::lonnet;
   36: use Apache::loncommon();
   37: use Apache::lonlocal;
   38: use Apache::restrictedaccess();
   39: use Apache::blockedaccess(); 
   40: use Fcntl qw(:flock);
   41: use LONCAPA;
   42: 
   43: sub cleanup {
   44:     my ($r)=@_;
   45:     if (! $r->is_initial_req()) { return DECLINED; }
   46:     &Apache::lonnet::save_cache();
   47:     &Apache::lontexconvert::jsMath_reset();
   48:     return OK;
   49: }
   50: 
   51: sub goodbye {
   52:     my ($r)=@_;
   53:     &Apache::lonnet::goodbye();
   54:     return DONE;
   55: }
   56: 
   57: ###############################################
   58: 
   59: sub get_posted_cgi {
   60:     my ($r) = @_;
   61: 
   62:     my $buffer;
   63:     if ($r->header_in('Content-length')) {
   64: 	$r->read($buffer,$r->header_in('Content-length'),0);
   65:     }
   66:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
   67: 	my @pairs=split(/&/,$buffer);
   68: 	my $pair;
   69: 	foreach $pair (@pairs) {
   70: 	    my ($name,$value) = split(/=/,$pair);
   71: 	    $value =~ tr/+/ /;
   72: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
   73: 	    $name  =~ tr/+/ /;
   74: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
   75: 	    &Apache::loncommon::add_to_env("form.$name",$value);
   76: 	}
   77:     } else {
   78: 	my $contentsep=$1;
   79: 	my @lines = split (/\n/,$buffer);
   80: 	my $name='';
   81: 	my $value='';
   82: 	my $fname='';
   83: 	my $fmime='';
   84: 	my $i;
   85: 	for ($i=0;$i<=$#lines;$i++) {
   86: 	    if ($lines[$i]=~/^$contentsep/) {
   87: 		if ($name) {
   88: 		    chomp($value);
   89: 		    if ($fname) {
   90: 			$env{"form.$name.filename"}=$fname;
   91: 			$env{"form.$name.mimetype"}=$fmime;
   92: 		    } else {
   93: 			$value=~s/\s+$//s;
   94: 		    }
   95: 		    &Apache::loncommon::add_to_env("form.$name",$value);
   96: 		}
   97: 		if ($i<$#lines) {
   98: 		    $i++;
   99: 		    $lines[$i]=~
  100: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
  101: 		    $name=$1;
  102: 		    $value='';
  103: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
  104: 			$fname=$1;
  105: 			if 
  106:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
  107: 				$fmime=$1;
  108: 				$i++;
  109: 			    } else {
  110: 				$fmime='';
  111: 			    }
  112: 		    } else {
  113: 			$fname='';
  114: 			$fmime='';
  115: 		    }
  116: 		    $i++;
  117: 		}
  118: 	    } else {
  119: 		$value.=$lines[$i]."\n";
  120: 	    }
  121: 	}
  122:     }
  123: #
  124: # Digested POSTed values
  125: #
  126: # Remember the way this was originally done (GET or POST)
  127: #
  128:     $env{'request.method'}=$ENV{'REQUEST_METHOD'};
  129: #
  130: # There may also be stuff in the query string
  131: # Tell subsequent handlers that this was GET, not POST, so they can access query string.
  132: # Also, unset POSTed content length to cover all tracks.
  133: #
  134: 
  135:     $r->method_number(M_GET);
  136: 
  137:     $r->method('GET');
  138:     $r->headers_in->unset('Content-length');
  139: }
  140: 
  141: # handle the case of the single sign on user, at this point $r->user 
  142: # will be set and valid now need to find the loncapa user info and possibly
  143: # balance them
  144: # returns OK if it was a SSO and user was handled
  145: #         undef if not SSO or no means to hanle the user
  146: sub sso_login {
  147:     my ($r,$handle) = @_;
  148: 
  149:     my $lonidsdir=$r->dir_config('lonIDsDir');
  150:     if (!($r->user 
  151: 	  && (!defined($env{'user.name'}) && !defined($env{'user.domain'}))
  152: 	  && ($handle eq ''))) {
  153: 	# not an SSO case or already logged in
  154: 	return undef;
  155:     }
  156: 
  157:     my ($user) = ($r->user =~ m/([a-zA-Z0-9_\-@.]*)/);
  158: 
  159:     my $domain = $r->dir_config('lonDefDomain');
  160:     my $home=&Apache::lonnet::homeserver($user,$domain);
  161:     if ($home !~ /(con_lost|no_host|no_such_host)/) {
  162: 	&Apache::lonnet::logthis(" SSO authorized user $user ");
  163: 	if ($r->dir_config("lonBalancer") eq 'yes') {
  164: 	    # login but immeaditly go to switch server to find us a new 
  165: 	    # machine
  166: 	    &Apache::lonauth::success($r,$user,$domain,$home,'noredirect');
  167:             $env{'request.sso.login'} = 1;
  168:             if (defined($r->dir_config("lonSSOReloginServer"))) {
  169:                 $env{'request.sso.reloginserver'} =
  170:                     $r->dir_config('lonSSOReloginServer');
  171:             }
  172: 	    $r->internal_redirect('/adm/switchserver');
  173: 	    $r->set_handlers('PerlHandler'=> undef);
  174: 	} else {
  175: 	    # need to login them in, so generate the need data that
  176: 	    # migrate expects to do login
  177: 	    my %info=('ip'        => $r->connection->remote_ip(),
  178: 		      'domain'    => $domain,
  179: 		      'username'  => $user,
  180: 		      'server'    => $r->dir_config('lonHostID'),
  181: 		      'sso.login' => 1
  182: 		      );
  183:             if (defined($r->dir_config("lonSSOReloginServer"))) {
  184:                 $info{'sso.reloginserver'} = 
  185:                     $r->dir_config('lonSSOReloginServer'); 
  186:             }
  187: 	    my $token = 
  188: 		&Apache::lonnet::tmpput(\%info,
  189: 					$r->dir_config('lonHostID'));
  190: 	    $env{'form.token'} = $token;
  191: 	    $r->internal_redirect('/adm/migrateuser');
  192: 	    $r->set_handlers('PerlHandler'=> undef);
  193: 	}
  194: 	return OK;
  195:     } elsif (defined($r->dir_config('lonSSOUserUnknownRedirect'))) {
  196: 	&Apache::lonnet::logthis(" SSO authorized unknown user $user ");
  197:         $r->subprocess_env->set('SSOUserUnknown' => $user);
  198:         $r->subprocess_env->set('SSOUserDomain' => $domain);
  199: 	$r->internal_redirect($r->dir_config('lonSSOUserUnknownRedirect'));
  200: 	$r->set_handlers('PerlHandler'=> undef);
  201: 	return OK;
  202:     }
  203:     return undef;
  204: }
  205: 
  206: sub handler {
  207:     my $r = shift;
  208:     my $requrl=$r->uri;
  209:     if (&Apache::lonnet::is_domainimage($requrl)) {
  210:         return OK;
  211:     }
  212: 
  213:     
  214:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  215: 
  216:     my $result = &sso_login($r,$handle);
  217:     if (defined($result)) {
  218: 	return $result
  219:     }
  220: 
  221: 
  222:     if ($r->dir_config("lonBalancer") eq 'yes') {
  223: 	$r->set_handlers('PerlResponseHandler'=>
  224: 			 [\&Apache::switchserver::handler]);
  225:     }
  226:     
  227:     if ($handle eq '') {
  228: 	$r->log_reason("Cookie $handle not valid", $r->filename); 
  229:     } elsif ($handle ne '') {
  230: 
  231: # ------------------------------------------------------ Initialize Environment
  232: 	my $lonidsdir=$r->dir_config('lonIDsDir');
  233: 	&Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  234: 
  235: # --------------------------------------------------------- Initialize Language
  236: 
  237: 	&Apache::lonlocal::get_language_handle($r);
  238: 
  239:     }
  240: 
  241: # -------------------------------------------------- Should be a valid user now
  242:     if ($env{'user.name'} ne '' && $env{'user.domain'} ne '') {
  243: # -------------------------------------------------------------- Resource State
  244: 
  245: 	if ($requrl=~/^\/+(res|uploaded)\//) {
  246: 	    $env{'request.state'} = "published";
  247: 	} else {
  248: 	    $env{'request.state'} = 'unknown';
  249: 	}
  250: 	$env{'request.filename'} = $r->filename;
  251: 	$env{'request.noversionuri'} = &Apache::lonnet::deversion($requrl);
  252: # -------------------------------------------------------- Load POST parameters
  253: 
  254: 	&Apache::lonacc::get_posted_cgi($r);
  255: 
  256: # ---------------------------------------------------------------- Check access
  257: 	my $now = time;
  258: 	if ($requrl !~ m{^/(?:adm|public|prtspool)/}
  259: 	    || $requrl =~ /^\/adm\/.*\/(smppg|bulletinboard)(\?|$ )/x) {
  260: 	    my $access=&Apache::lonnet::allowed('bre',$requrl);
  261: 	    if ($access eq '1') {
  262: 		$env{'user.error.msg'}="$requrl:bre:0:0:Choose Course";
  263: 		return HTTP_NOT_ACCEPTABLE; 
  264: 	    }
  265: 	    if ($access eq 'A') {
  266: 		&Apache::restrictedaccess::setup_handler($r);
  267: 		return OK;
  268: 	    }
  269:             if ($access eq 'B') {
  270:                 &Apache::blockedaccess::setup_handler($r);
  271:                 return OK;
  272:             }
  273: 	    if (($access ne '2') && ($access ne 'F')) {
  274: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  275: 		return HTTP_NOT_ACCEPTABLE; 
  276: 	    }
  277: 	}
  278: 	if ($requrl =~ m|^/prtspool/|) {
  279: 	    my $start='/prtspool/'.$env{'user.name'}.'_'.
  280: 		$env{'user.domain'};
  281: 	    if ($requrl !~ /^\Q$start\E/) {
  282: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  283: 		return HTTP_NOT_ACCEPTABLE;
  284: 	    }
  285: 	}
  286: 	if ($requrl =~ m|^/zipspool/|) {
  287: 	    my $start='/zipspool/zipout/'.$env{'user.name'}.":".
  288: 		$env{'user.domain'};
  289: 	    if ($requrl !~ /^\Q$start\E/) {
  290: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  291: 		return HTTP_NOT_ACCEPTABLE;
  292: 	    }
  293: 	}
  294: 	if ($env{'user.name'} eq 'public' && 
  295: 	    $env{'user.domain'} eq 'public' &&
  296: 	    $requrl !~ m{^/+(res|public|uploaded)/} &&
  297: 	    $requrl !~ m{^/adm/[^/]+/[^/]+/aboutme/portfolio$ }x &&
  298: 	    $requrl !~ m{^/+adm/(help|logout|restrictedaccess|randomlabel\.png)}) {
  299: 	    $env{'request.querystring'}=$r->args;
  300: 	    $env{'request.firsturl'}=$requrl;
  301: 	    return FORBIDDEN;
  302: 	}
  303: # ------------------------------------------------------------- This is allowed
  304: 	if ($env{'request.course.id'}) {
  305: 	    &Apache::lonnet::countacc($requrl);
  306: 	    $requrl=~/\.(\w+)$/;
  307: 	    if ((&Apache::loncommon::fileembstyle($1) eq 'ssi') ||
  308: 		($requrl=~/^\/adm\/.*\/(aboutme|navmaps|smppg|bulletinboard)(\?|$ )/x) ||
  309: 		($requrl=~/^\/adm\/wrapper\//) ||
  310: 		($requrl=~m|^/adm/coursedocs/showdoc/|) ||
  311: 		($requrl=~m|\.problem/smpedit$|) ||
  312: 		($requrl=~/^\/public\/.*\/syllabus$/)) {
  313: # ------------------------------------- This is serious stuff, get symb and log
  314: 		my $query=$r->args;
  315: 		my $symb;
  316: 		if ($query) {
  317: 		    &Apache::loncommon::get_unprocessed_cgi($query,['symb']);
  318: 		}
  319: 		if ($env{'form.symb'}) {
  320: 		    $symb=&Apache::lonnet::symbclean($env{'form.symb'});
  321: 		    if ($requrl =~ m|^/adm/wrapper/|
  322: 			|| $requrl =~ m|^/adm/coursedocs/showdoc/|) {
  323: 			my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  324: 			&Apache::lonnet::symblist($map,$murl => [$murl,$mid],
  325: 						  'last_known' =>[$murl,$mid]);
  326: 		    } elsif ((&Apache::lonnet::symbverify($symb,$requrl)) ||
  327: 			     (($requrl=~m|(.*)/smpedit$|) &&
  328: 			      &Apache::lonnet::symbverify($symb,$1))) {
  329: 			my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  330: 			&Apache::lonnet::symblist($map,$murl => [$murl,$mid],
  331: 						  'last_known' =>[$murl,$mid]);
  332: 		    } else {
  333: 			$r->log_reason('Invalid symb for '.$requrl.': '.
  334: 				       $symb);
  335: 			$env{'user.error.msg'}=
  336: 			    "$requrl:bre:1:1:Invalid Access";
  337: 			return HTTP_NOT_ACCEPTABLE; 
  338: 		    }
  339: 		} else {
  340: 		    $symb=&Apache::lonnet::symbread($requrl);
  341: 		    if (&Apache::lonnet::is_on_map($requrl) && $symb &&
  342: 			!&Apache::lonnet::symbverify($symb,$requrl)) {
  343: 			$r->log_reason('Invalid symb for '.$requrl.': '.$symb);
  344: 			$env{'user.error.msg'}=
  345: 			    "$requrl:bre:1:1:Invalid Access";
  346: 			return HTTP_NOT_ACCEPTABLE; 
  347: 		    }
  348: 		    if ($symb) {
  349: 			my ($map,$mid,$murl)=
  350: 			    &Apache::lonnet::decode_symb($symb);
  351: 			&Apache::lonnet::symblist($map,$murl =>[$murl,$mid],
  352: 						  'last_known' =>[$murl,$mid]);
  353: 		    }
  354: 		}
  355: 		$env{'request.symb'}=$symb;
  356: 		&Apache::lonnet::courseacclog($symb);
  357: 	    } else {
  358: # ------------------------------------------------------- This is other content
  359: 		&Apache::lonnet::courseacclog($requrl);    
  360: 	    }
  361: 	}
  362: 	return OK;
  363:     }
  364: # -------------------------------------------- See if this is a public resource
  365:     if ($requrl=~m|^/+adm/+help/+|) {
  366:  	return OK;
  367:     }
  368: # ------------------------------------ See if this is a viewable portfolio file
  369:     if (&Apache::lonnet::is_portfolio_url($requrl)) {
  370: 	my $access=&Apache::lonnet::allowed('bre',$requrl);
  371: 	if ($access eq 'A') {
  372: 	    &Apache::restrictedaccess::setup_handler($r);
  373: 	    return OK;
  374: 	}
  375: 	if (($access ne '2') && ($access ne 'F')) {
  376: 	    $env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  377: 	    return HTTP_NOT_ACCEPTABLE;
  378: 	}
  379:     }
  380: 
  381: # -------------------------------------------------------------- Not authorized
  382:     $requrl=~/\.(\w+)$/;
  383: #    if ((&Apache::loncommon::fileembstyle($1) eq 'ssi') ||
  384: #        ($requrl=~/^\/adm\/(roles|logout|email|menu|remote)/) ||
  385: #        ($requrl=~m|^/prtspool/|)) {
  386: # -------------------------- Store where they wanted to go and get login screen
  387: 	$env{'request.querystring'}=$r->args;
  388: 	$env{'request.firsturl'}=$requrl;
  389:        return FORBIDDEN;
  390: #   } else {
  391: # --------------------------------------------------------------------- Goodbye
  392: #       return HTTP_BAD_REQUEST;
  393: #   }
  394: }
  395: 
  396: 1;
  397: __END__
  398: 
  399: =head1 NAME
  400: 
  401: Apache::lonacc - Cookie Based Access Handler
  402: 
  403: =head1 SYNOPSIS
  404: 
  405: Invoked (for various locations) by /etc/httpd/conf/srm.conf:
  406: 
  407:  PerlAccessHandler       Apache::lonacc
  408: 
  409: =head1 INTRODUCTION
  410: 
  411: This module enables cookie based authentication and is used
  412: to control access for many different LON-CAPA URIs.
  413: 
  414: Whenever the client sends the cookie back to the server, 
  415: this cookie is handled by either lonacc.pm or loncacc.pm
  416: (see srm.conf for what is invoked when).  If
  417: the cookie is missing or invalid, the user is re-challenged
  418: for login information.
  419: 
  420: This is part of the LearningOnline Network with CAPA project
  421: described at http://www.lon-capa.org.
  422: 
  423: =head1 HANDLER SUBROUTINE
  424: 
  425: This routine is called by Apache and mod_perl.
  426: 
  427: =over 4
  428: 
  429: =item *
  430: 
  431: transfer profile into environment
  432: 
  433: =item *
  434: 
  435: load POST parameters
  436: 
  437: =item *
  438: 
  439: check access
  440: 
  441: =item *
  442: 
  443: if allowed, get symb, log, generate course statistics if applicable
  444: 
  445: =item *
  446: 
  447: otherwise return error
  448: 
  449: =item *
  450: 
  451: see if public resource
  452: 
  453: =item *
  454: 
  455: store attempted access
  456: 
  457: =back
  458: 
  459: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>