Annotation of loncom/auth/lonauth.pm, revision 1.75

1.1       albertel    1: # The LearningOnline Network
                      2: # User Authentication Module
1.27      www         3: #
1.75    ! albertel    4: # $Id: lonauth.pm,v 1.74 2006/04/05 22:39:55 albertel Exp $
1.27      www         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: #
1.1       albertel   28: 
                     29: package Apache::lonauth;
                     30: 
1.18      albertel   31: use strict;
1.1       albertel   32: use Apache::Constants qw(:common);
                     33: use Apache::File;
                     34: use CGI qw(:standard);
                     35: use CGI::Cookie();
1.26      harris41   36: use DynaLoader; # for Crypt::DES version
1.8       www        37: use Crypt::DES;
1.45      matthew    38: use Apache::loncommon();
1.66      albertel   39: use Apache::lonnet;
1.12      www        40: use Apache::lonmenu();
1.18      albertel   41: use Fcntl qw(:flock);
1.56      www        42: use Apache::lonlocal;
1.37      www        43: 
                     44: my %FORM;
                     45: 
1.1       albertel   46: # ------------------------------------------------------------ Successful login
                     47: 
                     48: sub success {
1.6       www        49:     my ($r, $username, $domain, $authhost,$lowerurl) = @_;
1.1       albertel   50:     my $lonids=$r->dir_config('lonIDsDir');
1.4       www        51: 
1.69      albertel   52:     my $public=($username eq 'public' && $domain eq 'public');
                     53: 
1.4       www        54: # See if old ID present, if so, remove
1.17      www        55: 
1.69      albertel   56:     my ($filename,$cookie,$userroles);
                     57:     my $now=time;
                     58: 
                     59:     if ($public) {
                     60: 	my $max_public=100;
                     61: 	my $oldest;
                     62: 	my $oldest_time=0;
                     63: 	for(my $next=1;$next<=$max_public;$next++) {
                     64: 	    if (-e $lonids."/publicuser_$next.id") {
                     65: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                     66: 		if ($mtime<$oldest_time || !$oldest_time) {
                     67: 		    $oldest_time=$mtime;
                     68: 		    $oldest=$next;
                     69: 		}
                     70: 	    } else {
                     71: 		$cookie="publicuser_$next";
                     72: 		last;
                     73: 	    }
                     74: 	}
                     75: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                     76:     } else {
                     77: 	opendir(DIR,$lonids);
                     78: 	while ($filename=readdir(DIR)) {
                     79: 	    if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                     80: 		unlink($lonids.'/'.$filename);
                     81: 	    }
                     82: 	}
                     83: 	closedir(DIR);
1.4       www        84: 
                     85: # Give them a new cookie
                     86: 
1.69      albertel   87: 	$cookie="$username\_$now\_$domain\_$authhost";
                     88:     
1.5       www        89: # Initialize roles
                     90: 
1.69      albertel   91: 	$userroles=Apache::lonnet::rolesinit($domain,$username,$authhost);
                     92:     }
1.7       www        93: # ------------------------------------ Check browser type and MathML capability
1.6       www        94: 
1.45      matthew    95:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                     96:         $clientunicode,$clientos) = &Apache::loncommon::decode_user_agent($r);
1.6       www        97: 
1.40      www        98: # -------------------------------------- Any accessibility options to remember?
                     99:     if (($FORM{'interface'}) && ($FORM{'remember'} eq 'true')) {
1.41      albertel  100: 	foreach ('imagesuppress','appletsuppress',
                    101: 		 'embedsuppress','fontenhance','blackwhite') {
                    102: 	    if ($FORM{$_} eq 'true') {
                    103: 		&Apache::lonnet::put('environment',{$_ => 'on'},
                    104: 				     $domain,$username);
                    105: 	    } else {
                    106: 		&Apache::lonnet::del('environment',[$_],$domain,$username);
                    107: 	    }
                    108: 	}
                    109:     }
1.11      www       110: # ------------------------------------------------------------- Get environment
                    111: 
1.32      albertel  112:     my $userenv;
                    113:     my %userenv=Apache::lonnet::dump('environment',$domain,$username);
                    114:     my ($tmp) = keys(%userenv);
                    115:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.73      albertel  116: 	# default remote control to off
                    117: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
1.32      albertel  118: 	foreach my $key (keys(%userenv)) {
                    119: 	    $userenv.="environment.$key=$userenv{$key}\n";
                    120: 	}
1.11      www       121:     }
1.38      www       122:     if (($userenv{'interface'}) && (!$FORM{'interface'})) {
                    123: 	$FORM{'interface'}=$userenv{'interface'};
                    124:     }
1.66      albertel  125:     $env{'environment.remote'}=$userenv{'remote'};
1.65      albertel  126:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                    127: 
1.54      www       128: # --------------- Do not trust query string to be put directly into environment
                    129:     foreach ('imagesuppress','appletsuppress',
                    130: 	     'embedsuppress','fontenhance','blackwhite',
                    131: 	     'interface','localpath','localres') {
                    132: 	$FORM{$_}=~s/[\n\r\=]//gs;
                    133:     }
1.7       www       134: # --------------------------------------------------------- Write first profile
1.5       www       135: 
1.41      albertel  136:     {
                    137: 	my $idf=Apache::File->new(">$lonids/$cookie.id");
                    138: 	unless (flock($idf,LOCK_EX)) {
                    139: 	    &Apache::lonnet::logthis("<font color=blue>WARNING: ".
                    140: 			   'Could not obtain exclusive lock in lonauth: '.$!);
                    141: 	    $idf->close();
                    142: 	    return 'error: '.$!;
                    143: 	}
                    144: 	if ($userenv ne '') { print $idf "$userenv\n"; }
                    145: 	print $idf "user.name=$username\n";
                    146: 	print $idf "user.domain=$domain\n";
                    147: 	print $idf "user.home=$authhost\n";
                    148: 	print $idf "browser.type=$clientbrowser\n";
                    149: 	print $idf "browser.version=$clientversion\n";
                    150: 	print $idf "browser.mathml=$clientmathml\n";
                    151: 	print $idf "browser.unicode=$clientunicode\n";
                    152: 	print $idf "browser.os=$clientos\n";
1.53      www       153:         if ($FORM{'localpath'}) {
                    154:            print $idf "browser.localpath=$FORM{'localpath'}\n";
                    155:            print $idf "browser.localres=$FORM{'localres'}\n";
                    156:         }
1.71      www       157:         print $idf "server.domain=".$r->dir_config('lonDefDomain')."\n";
1.41      albertel  158: 	print $idf "request.course.fn=\n";
                    159: 	print $idf "request.course.uri=\n";
                    160: 	print $idf "request.course.sec=\n";
                    161: 	print $idf "request.role=cm\n";
1.66      albertel  162:         print $idf "request.role.adv=$env{'user.adv'}\n";
1.42      www       163: 	print $idf "request.host=$ENV{'REMOTE_ADDR'}\n";
1.69      albertel  164: 	if ($public) {
1.68      albertel  165: 	    print $idf "environment.remote=off\n";
                    166: 	}
1.41      albertel  167: 	if ($FORM{'interface'}) {
                    168: 	    $FORM{'interface'}=~s/\W//gs;
                    169: 	    print $idf "browser.interface=$FORM{'interface'}\n";
1.66      albertel  170: 	    $env{'browser.interface'}=$FORM{'interface'};
1.41      albertel  171: 	    foreach ('imagesuppress','appletsuppress',
                    172: 		     'embedsuppress','fontenhance','blackwhite') {
                    173: 		if (($FORM{$_} eq 'true') ||
                    174: 		    ($userenv{$_} eq 'on')) {
                    175: 		    print $idf "browser.$_=on\n";
                    176: 		}
1.18      albertel  177: 	    }
1.41      albertel  178: 	}
                    179: 	if ($userroles ne '') { print $idf "$userroles"; }
                    180: 	$idf->close();
                    181:     }
1.66      albertel  182:     $env{'request.role'}='cm';
                    183:     $env{'request.role.adv'}=$env{'user.adv'};
                    184:     $env{'browser.type'}=$clientbrowser;
1.7       www       185: # -------------------------------------------------------------------- Log this
                    186: 
                    187:     &Apache::lonnet::log($domain,$username,$authhost,
                    188:                          "Login $ENV{'REMOTE_ADDR'}");
1.4       www       189: 
1.14      www       190: # ------------------------------------------------- Check for critical messages
                    191: 
1.21      www       192:     my @what=&Apache::lonnet::dump('critical',$domain,$username);
1.14      www       193:     if ($what[0]) {
1.22      www       194: 	if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
1.21      www       195: 	    $lowerurl='/adm/email?critical=display';
1.14      www       196:         }
                    197:     }
                    198: 
1.5       www       199: # ------------------------------------------------------------ Get cookie ready
                    200: 
1.70      albertel  201:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
                    202: 
1.1       albertel  203:     $cookie="lonID=$cookie; path=/";
1.12      www       204: # -------------------------------------------------------- Menu script and info
1.31      www       205:     my $windowinfo=&Apache::lonmenu::open($clientos);
1.35      www       206:     my $startupremote=&Apache::lonmenu::startupremote($lowerurl);
1.63      albertel  207:     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
1.35      www       208:     my $setflags=&Apache::lonmenu::setflags();
                    209:     my $maincall=&Apache::lonmenu::maincall();
1.74      albertel  210:     my $start_page=&Apache::loncommon::start_page('Successful Login',
                    211: 						  $startupremote);
                    212:     my $end_page  =&Apache::loncommon::end_page();
                    213: 
1.64      albertel  214:     my $continuelink;
1.66      albertel  215:     if (($env{'browser.interface'} eq 'textual') ||
                    216:         ($env{'environment.remote'} eq 'off')) {
1.64      albertel  217: 	$continuelink="<a href=\"$lowerurl\">".&mt('Continue')."</a>";
                    218:     }
1.5       www       219: # ------------------------------------------------- Output for successful login
                    220: 
1.74      albertel  221:     &Apache::loncommon::content_type($r,'text/html');
                    222:     $r->header_out('Set-cookie' => $cookie);
                    223:     $r->send_http_header;
1.1       albertel  224: 
1.58      www       225:     my %lt=&Apache::lonlocal::texthash(
                    226: 				       'wel' => 'Welcome',
                    227: 				       'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up',
                    228: 				       'pro' => 'Problems',
                    229: 				       'log' => 'loginproblems.html',
                    230: 				       );
1.1       albertel  231:     $r->print(<<ENDSUCCESS);
1.74      albertel  232: $start_page
1.35      www       233: $setflags
1.19      www       234: $windowinfo
1.58      www       235: <h1>$lt{'wel'}</h1>
                    236: $lt{'mes'}.<p>
                    237: <a href="/adm/$lt{'log'}">$lt{'pro'}?</a></p>
1.63      albertel  238: $remoteinfo
1.35      www       239: $maincall
1.64      albertel  240: $continuelink
1.74      albertel  241: $end_page
1.1       albertel  242: ENDSUCCESS
                    243: }
                    244: 
                    245: # --------------------------------------------------------------- Failed login!
                    246: 
                    247: sub failed {
                    248:     my ($r,$message) = @_;
1.74      albertel  249:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login');
                    250:     my $end_page   = &Apache::loncommon::end_page();
                    251: 
                    252:     my %lt=('sorry'  => &mt('Sorry ...'),
                    253: 	    'please' => 
                    254: 	    &mt('Please [_1]log in again[_2].',
                    255: 		"<a href=\"/adm/login?username=$FORM{'uname'}&domain=$FORM{'udom'}\">",
                    256: 		'</a>'),
                    257: 	    'problemspage' => &mt('loginproblems.html'),
                    258: 	    'problems'     => 'Problems',
                    259: 	    );
                    260:     &Apache::loncommon::content_type($r,'text/html');
                    261:     $r->send_http_header;
1.1       albertel  262: 
                    263:     $r->print(<<ENDFAILED);
1.74      albertel  264: $start_page
                    265: <h1>$lt{'sorry'}</h1>
1.43      www       266: <p><b>$message</b></p>
1.74      albertel  267: <p>$lt{'please'}</p>
1.43      www       268: <p>
1.74      albertel  269: <a href="/adm/$lt{'problemspage'}">$lt{'problems'}</a></p>
                    270: $end_page
1.1       albertel  271: ENDFAILED
1.60      www       272: }
                    273: 
1.55      www       274: # ------------------------------------------------------------------ Rerouting!
                    275: 
                    276: sub reroute {
1.74      albertel  277:     my ($r) = @_;
                    278:     &Apache::loncommon::content_type($r,'text/html');
                    279:     $r->send_http_header;
                    280:     my $msg='<h1>Sorry ...</h1>
                    281:              Please <a href="/">log in again</a>.';
                    282:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg);
1.55      www       283: }
                    284: 
1.1       albertel  285: # ---------------------------------------------------------------- Main handler
                    286: 
                    287: sub handler {
                    288:     my $r = shift;
1.55      www       289: 
                    290: # Are we re-routing?
                    291:     if (-e '/home/httpd/html/lon-status/reroute.txt') {
                    292: 	&reroute($r);
                    293: 	return OK;
                    294:     }
1.56      www       295: 
1.57      www       296:     &Apache::lonlocal::get_language_handle($r);
1.1       albertel  297: 
1.59      www       298: # -------------------------------- Prevent users from attempting to login twice
                    299:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    300:     my $lonid=$cookies{'lonID'};
                    301:     my $cookie;
                    302:     if ($lonid) {
                    303: 	my $handle=$lonid->value;
                    304:         $handle=~s/\W//g;
                    305:         my $lonidsdir=$r->dir_config('lonIDsDir');
                    306:         if ((-e "$lonidsdir/$handle.id") && ($handle ne '')) {
                    307: # Indeed, a valid token is found
1.74      albertel  308: 	    &Apache::loncommon::content_type($r,'text/html');
                    309: 	    $r->send_http_header;
                    310: 	    my $start_page = 
                    311: 		&Apache::loncommon::start_page('Already logged in');
                    312: 	    my $end_page = 
                    313: 		&Apache::loncommon::end_page();
1.59      www       314: 	    $r->print(<<ENDFAILED);
1.74      albertel  315: $start_page
1.59      www       316: <h1>You are already logged in</h1>
                    317: <p>Please either <a href="/adm/roles">continue the current session</a> or
                    318: <a href="/adm/logout">logout</a>.</p>
                    319: <p>
                    320: <a href="/adm/loginproblems.html">Problems?</a></p>
1.74      albertel  321: $end_page
1.59      www       322: ENDFAILED
                    323:            return OK;
                    324: 	}
                    325:     }
                    326: 
                    327: # ---------------------------------------------------- No valid token, continue
                    328: 
                    329: 
1.1       albertel  330:     my $buffer;
1.49      albertel  331:     $r->read($buffer,$r->header_in('Content-length'),0);
1.1       albertel  332:     my @pairs=split(/&/,$buffer);
1.37      www       333:     my $pair; my $name; my $value;
                    334:     undef %FORM;
                    335:     %FORM=();
1.1       albertel  336:     foreach $pair (@pairs) {
                    337:        ($name,$value) = split(/=/,$pair);
1.7       www       338:        $value =~ tr/+/ /;
                    339:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.1       albertel  340:        $FORM{$name}=$value;
                    341:     } 
                    342: 
1.67      www       343:     if ((!$FORM{'uname'}) || (!$FORM{'upass0'}) || (!$FORM{'udom'})) {
1.43      www       344: 	failed($r,'Username, password and domain need to be specified.');
1.1       albertel  345:         return OK;
                    346:     }
1.61      www       347: 
                    348: # split user logging in and "su"-user
                    349: 
                    350:     ($FORM{'uname'},$FORM{'suname'})=split(/\:/,$FORM{'uname'});
1.1       albertel  351:     $FORM{'uname'} =~ s/\W//g;
1.61      www       352:     $FORM{'suname'} =~ s/\W//g;
1.1       albertel  353:     $FORM{'udom'}  =~ s/\W//g;
                    354: 
                    355:     my $role   = $r->dir_config('lonRole');
                    356:     my $domain = $r->dir_config('lonDefDomain');
                    357:     my $prodir = $r->dir_config('lonUsersDir');
                    358: 
1.8       www       359: # ---------------------------------------- Get the information from login token
                    360: 
                    361:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$FORM{'logtoken'},
                    362:                                       $FORM{'serverid'});
                    363: 
                    364:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
1.43      www       365: 	failed($r,'Information needed to verify your login information is missing, inaccessible or expired.');
1.8       www       366:         return OK;
1.44      www       367:     } else {
                    368:         unless (&Apache::lonnet::reply('tmpdel:'.$FORM{'logtoken'},
                    369:                                          $FORM{'serverid'}) eq 'ok') {
                    370:             &failed($r,'Session could not be opened.');
                    371: 	}
1.8       www       372:     }
1.9       www       373:     my ($key,$firsturl)=split(/&/,$tmpinfo);
1.8       www       374: 
                    375:     my $keybin=pack("H16",$key);
                    376: 
1.26      harris41  377:     my $cipher;
                    378:     if ($Crypt::DES::VERSION>=2.03) {
                    379: 	$cipher=new Crypt::DES $keybin;
                    380:     }
                    381:     else {
                    382: 	$cipher=new DES $keybin;
                    383:     }
1.67      www       384:     my $upass='';
                    385:     for (my $i=0;$i<=2;$i++) {
                    386: 	my $chunk=
                    387: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},0,16))));
1.8       www       388: 
1.67      www       389: 	$chunk.=
                    390: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},16,16))));
1.8       www       391: 
1.67      www       392: 	$chunk=substr($chunk,1,ord(substr($chunk,0,1)));
                    393: 	$upass.=$chunk;
                    394:     }
1.8       www       395: 
1.1       albertel  396: # ---------------------------------------------------------------- Authenticate
                    397:     my $authhost=Apache::lonnet::authenticate($FORM{'uname'},
1.8       www       398:                                               $upass,
1.1       albertel  399:                                               $FORM{'udom'});
                    400:     
                    401: # --------------------------------------------------------------------- Failed?
                    402: 
                    403:     if ($authhost eq 'no_host') {
1.43      www       404: 	failed($r,'Username and/or password could not be authenticated.');
1.1       albertel  405:         return OK;
                    406:     }
                    407: 
1.59      www       408:     if (($firsturl eq '') || 
                    409: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
1.24      www       410: 	$firsturl='/adm/roles';
1.7       www       411:     }
1.61      www       412: # --------------------------------- Are we attempting to login as somebody else?
                    413:     if ($FORM{'suname'}) {
                    414: # ------------ see if the original user has enough privileges to pull this stunt
                    415: 	if (&Apache::lonnet::privileged($FORM{'uname'},$FORM{'udom'})) {
                    416: # ---------------------------------------------------- see if the su-user exists
                    417: 	    unless (&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'})
                    418: 		eq 'no_host') {
                    419: 		&Apache::lonnet::logthis(&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'}));
                    420: # ------------------------------ see if the su-user is not too highly privileged
                    421: 		unless (&Apache::lonnet::privileged($FORM{'suname'},$FORM{'udom'})) {
                    422: # -------------------------------------------------------- actually switch users
                    423: 		    &Apache::lonnet::logperm('User '.$FORM{'uname'}.' at '.$FORM{'udom'}.
                    424: 			' logging in as '.$FORM{'suname'});
                    425: 		    $FORM{'uname'}=$FORM{'suname'};
                    426: 		} else {
                    427: 		    &Apache::lonnet::logthis('Attempted switch user to privileged user');
                    428: 		}
                    429: 	    }
                    430: 	} else {
                    431: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
                    432: 	}
                    433:     }
                    434:     &success($r,$FORM{'uname'},$FORM{'udom'},$authhost,$firsturl);
1.1       albertel  435:     return OK;
                    436: }
                    437: 
                    438: 1;
                    439: __END__
1.7       www       440: 
                    441: 

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