File:  [LON-CAPA] / loncom / auth / lonacc.pm
Revision 1.113: download - view: text, annotated - select for diffs
Tue Nov 6 02:42:40 2007 UTC (16 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: version_2_6_X, version_2_6_3, version_2_6_2, version_2_6_1, version_2_6_0, version_2_5_99_1, version_2_5_99_0, HEAD
- boundary value is announced in the content-type so use it there rather
  than trying to self discover it

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

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