Project

General

Profile

Download (15.5 KB) Statistics
| Branch: | Revision:
1 95b003ff Origo
#!/usr/bin/perl -w
2
3
# mod_auth_tkt sample login script - runs as a vanilla CGI, under
4
#   mod_perl 1 via Apache::Registry, and under mod_perl2 via 
5
#   ModPerl::Registry.
6
#
7
# This script can run in a few different modes, depending on how it is 
8
#   named. Copy the script to a cgi-bin area, and create appropriately 
9
#   named symlinks to access the different behaviours. 
10
# Modes:
11
#   - login mode (default): request a username and password and test via
12
#     $AuthTktConfig::validate_sub - if successful, issue an auth ticket 
13
#     and redirect to the back location
14
#   - autologin mode ('autologin.cgi'): [typically used to allow tickets 
15
#     across multiple domains] if no valid auth ticket exists, redirect
16
#     to the login (or guest) version; otherwise automatically redirect 
17
#     to the back location passing the current auth ticket as a GET 
18
#     argument. mod_auth_tkt (>= 1.3.8) will turn this new ticket into 
19
#     an auth cookie for the new domain if none already exists.
20
#   - guest mode ('guest.cgi'): [DEPRECATED - use TktAuthGuestLogin instead]
21
#     automatically issues an auth ticket a special username (as defined in 
22
#     $AuthTktConfig::guest_sub, default 'guest'), and redirect to the back 
23
#     location 
24
#
25
26
use File::Basename;
27
#use lib dirname($ENV{SCRIPT_FILENAME});
28
use lib ".";
29
use Apache::AuthTkt 0.03;
30
use AuthTktConfig;
31
use CGI qw(:standard);
32
use CGI::Cookie;
33
use URI::Escape;
34
use URI;
35
use Data::Dumper;
36
use File::Path;
37 54401133 hq
use Digest::SHA qw(sha512_base64);
38 95b003ff Origo
39
$ENV{PATH} = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
40
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
41
42
# Main code begins
43
my $at = Apache::AuthTkt->new(conf => $ENV{MOD_AUTH_TKT_CONF});
44
my $q = CGI->new;
45
my ($server_name, $server_port) = split /:/, $ENV{HTTP_HOST} if $ENV{HTTP_HOST};
46
$server_name ||= $ENV{SERVER_NAME} if $ENV{SERVER_NAME};
47
$server_port ||= $ENV{SERVER_PORT} if $ENV{SERVER_PORT};
48
49
my $AUTH_DOMAIN = $at->domain || $server_name;
50
my @auth_domain = $AUTH_DOMAIN ? ( -domain => $AUTH_DOMAIN ) : ();
51
my $ticket = $q->cookie($at->cookie_name);
52
my $probe = $q->cookie('auth_probe');
53
my $back_cookie = $q->cookie($at->back_cookie_name) if $at->back_cookie_name;
54
my $have_cookies = $ticket || $probe || $back_cookie || '';
55
my $back = '';
56
$back = $AuthTktConfig::FIXED_BACK_LOCATION if $AuthTktConfig::FIXED_BACK_LOCATION;
57
$back ||= $back_cookie;
58
$back ||= $q->param($at->back_arg_name) if $at->back_arg_name;
59
#$back ||= $ENV{HTTP_REFERER} if $ENV{HTTP_REFERER} && $AuthTktConfig::BACK_REFERER;
60
$back ||= $AuthTktConfig::DEFAULT_BACK_LOCATION if $AuthTktConfig::DEFAULT_BACK_LOCATION;
61
if ($back && $back =~ m!^/!) {
62
  my $hostname = $server_name;
63
  my $port = $server_port;
64
  $hostname .= ':' . $port if $port && $port != 80 && $port != 443;
65
  $back = sprintf "http%s://%s%s", ($port == 443 ? 's' : ''), $hostname, $back;
66
} elsif ($back && $back !~ m/^http/i) {
67
  $back = 'http://' . $back;
68
}
69
$back = uri_unescape($back) if $back && $back =~ m/^https?%3A%2F%2F/;
70
my $back_esc = uri_escape($back) if $back;
71
my $back_html = escapeHTML($back) if $back;
72
73
my ($fatal, @errors);
74
my ($mode, $location, $suffix) = fileparse($ENV{SCRIPT_NAME}, '\.cgi', '\.pl');
75
$mode = 'autologin' if ($ENV{SCRIPT_NAME} =~ /autologin/);
76
$mode = 'login' unless ($mode eq 'guest' || $mode eq 'autologin');
77
my $self_redirect = $q->param('redirect') || 0;
78
$username = '';
79
$username = &trim(lc($q->param('username'))) if ($q->param('username'));
80
my $password = $q->param('password');
81 54401133 hq
my $totp = $q->param('totp');
82 95b003ff Origo
my $timeout = $q->param('timeout');
83
my $unauth = $q->param('unauth');
84
my $ip_addr = $at->ignore_ip ? '' : $ENV{REMOTE_ADDR};
85
my $redirected = 0;
86 54401133 hq
my $validtoken = 0;
87 95b003ff Origo
88 6fdc8676 hq
my $logo = "/stabile/static/img/logo.png";
89
my $logo_icon = "/stabile/static/img/logo-icon.png";
90
# my $logo_icon_32 = "/stabile/static/img/logo-icon-32.png";
91
$logo = "/stabile/static/img/logo-$AUTH_DOMAIN.png" if (-e "/var/www/stabile/static/img/logo-$AUTH_DOMAIN.png");
92
$logo_icon = "/stabile/static/img/logo-icon-$AUTH_DOMAIN.png" if (-e "/var/www/stabile/static/img/logo-icon-$AUTH_DOMAIN.png");
93
94 95b003ff Origo
# Actual processing
95
96
my $installsystem = $q->param('installsystem');
97
my $systemcookie;
98
if ($installsystem) {
99
   $systemcookie = CGI::Cookie->new(
100
      -name => 'installsystem',
101
      -value => "$installsystem",
102
      -path => '/',
103
  );
104
};
105
106
my $tktusercookie = CGI::Cookie->new(
107
  -name => 'tktuser',
108
  -value => "",
109
  @auth_domain,
110
  -path => '/',
111
  -expires => '-1h'
112
);
113
my $auth_tktcookie = CGI::Cookie->new(
114
  -name => $at->cookie_name,
115
  -value => "",
116
  @auth_domain,
117
  -path => '/',
118
  -expires => '-1h'
119
);
120
121
122
# If no cookies found, first check whether cookies are supported
123
if (! $have_cookies && !$q->param('api')) {
124
  # If this is a self redirect warn the user about cookie support
125
  if ($self_redirect) {
126
    $fatal = "Your browser does not appear to support cookies or has cookie support disabled.<br />\nThis site requires cookies - please turn cookie support on or try again using a different browser.";
127
  }
128
  # If no cookies and not a redirect, redirect to self to test cookies
129
  else {
130
    my $extra = '';
131
    $extra .= 'timeout=1' if $timeout;
132
    $extra .= 'unauth=1' if $unauth;
133
    $extra .= "installsystem=$installsystem" if $installsystem;
134
    $extra = "&$extra" if $extra;
135
136
    my $cookie = CGI::Cookie->new(-name => 'auth_probe', -value => 1, @auth_domain);
137
138
    print redirect(
139
      -uri => sprintf("%s%s%s?redirect=%s&%s=%s%s",
140
                        $location, $mode, $suffix, $self_redirect + 1, $at->back_arg_name,
141
                        $back_esc || '', $extra),
142
      -cookie => [$cookie, $systemcookie],
143
    );
144
145
    #print $q->header(
146
    #  -cookie => [$cookie, $systemcookie],
147
    #);
148
    # For some reason, a Location: redirect doesn't seem to then see the cookie,
149
    #   but a meta refresh one does - go figure
150
    #print $q->start_html(
151
    #  -head => meta({
152
    #    -http_equiv => 'Pragma', -content => "no-cache"
153
    #  }),
154
    #  -head => meta({
155
    #    -http_equiv => 'refresh', -content => ("0;URL=" . sprintf("%s%s%s?redirect=%s&%s=%s%s",
156
    #      $location, $mode, $suffix, $self_redirect + 1, $at->back_arg_name,
157
    #      $back_esc || '', $extra))
158
    #}));
159
    $redirected = 1;
160
  }
161
162
} elsif ($mode eq 'autologin') {
163
  $ticket = $ticket || $q->param($at->cookie_name);
164
  # If we have a ticket, redirect to $back, including ticket as GET param
165
  if ($ticket && $back && ! $timeout) {
166
#    my $b = URI->new($back);
167
#    $back .= $b->query ? '&' : '?';
168
#    $back .= $at->cookie_name . '=' . $ticket;
169
170
    #print $q->redirect($back);
171
    my %params = $q->Vars;
172
    $steamaccount = $params{'account'};
173
    if ($steamaccount) {
174
      my $cookie = $q->cookie(-name => 'steamaccount',
175
          -value => $steamaccount,
176
          -path => '/',
177
          -secure => $at->require_ssl,
178
          @auth_domain,
179
      );
180
    # Let's extract username from ticket, rather than trusting param
181
      my $valid = $at->validate_ticket($ticket);
182
      unless (time - $valid->{ts} > 2*60*60) { # Default auth_tkt timeout is 2 hours
183
      #  $username = $valid->{uid};
184
      }
185
      $session = substr($ticket, 0, 6);
186
      set_cookie_redirect($ticket, $back, $cookie);
187
    } else {
188
      set_cookie_redirect($ticket, $back, $systemcookie);
189
    }
190
    $redirected = 1;
191
192
  }
193
  # Can't autologin - change mode to either guest or login
194
  else {
195
    $mode = $AuthTktConfig::AUTOLOGIN_FALLBACK_MODE;
196
  }
197
}
198
199
unless ($fatal || $redirected) {
200
  if (! $at) {
201
    $fatal = "AuthTkt error: " . $at->errstr;
202
203
  } elsif ($mode eq 'login') {
204 54401133 hq
    if ($username && $password) {
205
      my ($valid, $tokens) = $AuthTktConfig::validate_sub->($username, $password, $totp);
206
      $validtoken = $valid;
207
      if ($valid == 2) { # User has 2fa enabled - present 2fa login screen
208 705b5366 hq
        push @errors, 'Please type your 2-factor authentication code';
209 54401133 hq
      } elsif ($valid) {
210 95b003ff Origo
#       my $user_data = join(':', encrypt($password), time(), ($ip_addr ? $ip_addr : ''));
211
        my $user_data = join(':', time(), ($ip_addr ? $ip_addr : ''));    # Optional
212
        my $tkt = $at->ticket(uid => $username, data => $user_data, 
213
          ip_addr => $ip_addr, tokens => $tokens, debug => $AuthTktConfig::DEBUG);
214
        if (! @errors) {
215
          $redirected = set_cookie_redirect($tkt, $back, $systemcookie);
216
          $fatal = "Login successful.";
217
        }
218
      }
219
      else {
220
        push @errors, "Invalid username or password.";
221
      }
222
    }
223
  } elsif ($mode eq 'guest') {
224
    # Generate a guest ticket and redirect to $back
225
    my $tkt = $at->ticket(uid => $AuthTktConfig::guest_sub->(), ip_addr => $ip_addr);
226
    if (! @errors) {
227
#      $redirected = $set_cookie_redirect->($tkt, $back, $systemcookie);
228
      $redirected = set_cookie_redirect($tkt, $back, $systemcookie);
229
      $fatal = "No back link found.";
230
    }
231
  }
232
}
233
234
my @style = ();
235
#@style = ( '-style' => { src => $AuthTktConfig::STYLESHEET } )
236
#  if $AuthTktConfig::STYLESHEET;
237
@style = ( '-style' => { src => '/stabile/static/css/style.css' } );
238
my $title = $AuthTktConfig::TITLE || "\u$mode Page";
239
unless ($redirected) {
240
  if ($q->param('api')) {
241
    print $q->header("application/json");
242
    print qq|{"status": "Error"}\n|;
243
    exit;
244
  }
245
    # If here, either some kind of error or a login page
246
  if ($fatal) {
247
    print $q->header(
248
        -cookie => [$systemcookie,$auth_tktcookie,$tktusercookie]
249
    ),
250
      $q->start_html(
251
        -head => meta({-http_equiv => 'Pragma', -content => "no-cache"}),
252
        -title => $title,
253
        @style,
254
      );
255
  } else {
256
    push @errors, qq(Your session has timed out.) if $timeout;
257
    push @errors, qq(You are not authorised to access this area.) if $unauth;
258
    my $foc = ($username?'1':'0');
259
    print $q->header(-status=>'401', -cookie => [$systemcookie,$auth_tktcookie,$tktusercookie]),
260
      $q->start_html(
261
        -head => [
262
            meta({-http_equiv => 'Pragma', -content => "no-cache"}),
263
            $q->Link({
264
               -rel => 'SHORTCUT ICON',
265 6fdc8676 hq
               -href =>$logo_icon,
266 95b003ff Origo
            })
267
          ],
268
        -meta=>{'viewport'=>'width=device-width, initial-scale=1'},
269 6fdc8676 hq
        -link=>{'rel'=>'icon', 'href'=>$logo_icon, 'sizes'=>'192x192'},
270 95b003ff Origo
        -title => $title,
271
        -class => 'login',
272
        -onLoad => "getFocus()",
273
        @style,
274
        -script => qq(
275
function getFocus() {
276
  document.forms[0].elements[$foc].focus();
277
  document.forms[0].elements[$foc].select();
278
}));
279
  }
280
281
  print <<EOD;
282
<div align="center">
283
EOD
284
285
286
  if ($AuthTktConfig::DEBUG) {
287
    my $cookie_name = $at->cookie_name;
288
    my $back_cookie_name = $at->back_cookie_name || '';
289
    my $back_arg_name = $at->back_arg_name || '';
290
    my $cookie_expires = $at->cookie_expires || 0;
291
    print <<EOD;
292
<pre>
293
server_name: $server_name
294
server_port: $server_port
295
domain: $AUTH_DOMAIN
296
mode: $mode
297
suffix: $suffix
298
cookie_name: $cookie_name
299
cookie_expires: $cookie_expires
300
back_cookie_name: $back_cookie_name
301
back_arg_name: $back_arg_name
302
back: $back
303
back_esc: $back_esc
304
back_html: $back_html
305
have_cookies: $have_cookies
306
ip_addr: $ip_addr
307
EOD
308
    if ($Apache::AuthTkt::VERSION >= 2.1) {
309
      printf "digest_type: %s\n", $at->digest_type;
310
    }
311
    print "</pre>\n";
312
  }
313
314
  if ($fatal) {
315
    print qq(<p class="error">$fatal</p>\n);
316
  }
317
318
  else {
319 54401133 hq
    my $sha_pwd = $password;
320
    $sha_pwd = sha512_base64($password) unless (length($password) == 86);
321
    print qq(<p class="alert alert-info" style="width:400px; padding:10px; margin: 10px;"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>\n), join(qq(<br />\n), @errors), "</p>\n"
322 95b003ff Origo
      if @errors;
323
    print <<EOD;
324
<div id="auth-header">
325 6fdc8676 hq
    <a href="#"><img src="$logo" border="0" style="height:48px; vertical-align:middle; margin:20px;"/></a>
326 95b003ff Origo
</div>
327
<form name="login" method="post" style="width:200px;" id="auth-form" accept-charset="utf-8">
328 54401133 hq
EOD
329
    ;
330
    if ($validtoken == 2) {
331
      print <<EOD;
332
 			       <input type="hidden" name="username" id="username" value="$username">
333
                   <input type="hidden" name="password" id="password" value="$sha_pwd">
334
                   <img class="logo" src="/stabic/img/google_auth.png" style="margin-bottom: 20px;">
335
                   <input type="number" pattern="[0-9.]+" maxlength="6" minlength="6" name="totp" id="totp" class="form-control required password" aria-label="totp" aria-required="true" required="" placeholder="Authentication Token"  autofocus="on">
336
EOD
337
      ;
338
    } else {
339
      print <<EOD;
340
                  <input value="$username" type="text" name="username" class="form-control" placeholder="Username"/>
341
                  <input type="password" id="password" name="password" class="form-control" placeholder="Password"/>
342
EOD
343
    }
344
  print <<EOD;
345 95b003ff Origo
<input type="submit" value="Login" class="btn btn-success btn-sm pull-right" />
346
EOD
347
    print qq(<input type="hidden" name="back" value="$back_html" />\n) if $back_html;
348
    print qq(</form>\n);
349
}
350
  print <<EOD;
351
</div>
352
</body>
353
</html>
354
EOD
355
}
356
357
# ------------------------------------------------------------------------
358
# Set the auth cookie and redirect to $back
359
sub set_cookie_redirect {
360
  my ($tkt, $bk, $systemcook) = @_;
361
  my @expires = $at->cookie_expires ?
362
    ( -expires => sprintf("+%ss", $at->cookie_expires) ) :
363
    ();
364
  my $cookie = CGI::Cookie->new(
365
    -name => $at->cookie_name,
366
    -value => $tkt,
367
    -path => '/',
368
    -secure => $at->require_ssl,
369
    @expires,
370
    @auth_domain
371
  );
372
373
  my $usercookie = CGI::Cookie->new(
374
    -name => 'tktuser',
375
    -value => $username,
376
    -path => '/',
377
    -secure => $at->require_ssl,
378
    @expires,
379
    @auth_domain
380
  );
381
  # Zap the guac cookie if redirecting to guacamole
382
  my $guaccookie = CGI::Cookie->new(
383
          -name => 'GUAC_AUTH',
384
          -value => '',
385
          -path => '/guacamole/'
386
  );
387
388
  #print header();
389
  #print "BACK: $back, ", $q->param($at->back_arg_name), ",", $at->back_arg_name, "\n";
390
  #my $installsystem = $q->param('installsystem');
391
  #my $systemcookie;
392
  #if ($installsystem) {
393
  #   $systemcookie = CGI::Cookie->new(
394
  #      -name => 'installsystem',
395
  #      -value => "$installsystem",
396
  #      -path => '/',
397
  #  );
398
  #}
399
400
 # If no $back, just set the auth cookie and hope for the best
401
  if (! $bk) {
402
    print $q->header( -cookie => [$cookie, $usercookie, $systemcook] );
403
    print $q->start_html, $q->p("Login successful"), $q->end_html;
404
    return 0;
405
  }
406
407
  my $bkobj = URI->new($bk);
408
  # If $back domain doesn't match $AUTH_DOMAIN, pass ticket via back GET param
409
  my $domain = $AUTH_DOMAIN || $server_name;
410
  if ($bkobj->host !~ m/\b$domain$/i) {
411
    $bk .= $bkobj->query ? '&' : '?';
412
    $bk .= $at->cookie_name . '=' . $tkt;
413
  }
414
415
  if ($q->param('api')) {
416
    print header(
417
        -content_type => "application/json",
418
        -cookie => [ $cookie, $usercookie, $systemcook ]
419
    );
420
    print qq|{"status": "OK", "cookie": "| . $at->cookie_name . qq|", "tkt": "$tkt"}\n|;
421
  } else {
422
    prepare_ui_update($username);
423
    $bk = '' if ($bk =~ /login/);
424
    my @cooks = [$cookie, $usercookie, $systemcook, $guaccookie];
425
#    push @cooks, $guaccookie if ($bk =~ /guacamole/);
426
    print redirect(
427
        -uri => $bk || '/stabile/',
428
        -cookie => @cooks,
429
    );
430
  }
431
  return 1;
432
};
433
434
sub trim($){
435
	my $string = shift;
436
	$string =~ s/^\s+//;
437
	$string =~ s/\s+$//;
438
	return $string;
439
}
440
441
sub prepare_ui_update {
442
  my $uname = shift;
443
  return unless $uname;
444
  # Update allowed port forwards and create links
445
  # AuthTktConfig::syslogit('info', "Now opening ssh ports for $uname...");
446
  # `/usr/local/bin/permitOpen "$uname"`;
447
  #mkpath('../cgi/ui_update') unless (-e '../cgi/ui_update');
448
  `/bin/ln -s ../ui_update.cgi ../cgi/ui_update/$uname~ui_update.cgi` unless (-e "../cgi/ui_update/$uname~ui_update.cgi");
449
  if ($session) {
450
    eval {
451
      `/bin/rm -f /tmp/$uname~*$session.*.tasks`; # Remove any tasks file from a previous session - no quotes
452
      `/usr/bin/pkill -f "$session."`;
453
      1;
454
    } or do {;};
455
  }
456
}