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