File:  [LON-CAPA] / loncom / auth / lonacc.pm
Revision 1.119: download - view: text, annotated - select for diffs
Tue Nov 18 19:14:34 2008 UTC (15 years, 5 months ago) by jms
Branches: MAIN
CVS tags: HEAD
Added/updated/converted POD. Many files had their POD redone to new standards.

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

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