Project

General

Profile

Download (15.7 KB) Statistics
| Branch: | Revision:
1
#!/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
use Digest::SHA qw(sha512_base64);
38

    
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
my $totp = $q->param('totp');
82
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
my $validtoken = 0;
87

    
88
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
# 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
      -secure => $at->require_ssl,
104
  );
105
};
106

    
107
my $tktusercookie = CGI::Cookie->new(
108
  -name => 'tktuser',
109
  -value => "",
110
  @auth_domain,
111
  -path => '/',
112
  -secure => $at->require_ssl,
113
  -expires => '-1h'
114
);
115
my $auth_tktcookie = CGI::Cookie->new(
116
  -name => $at->cookie_name,
117
  -value => "",
118
  @auth_domain,
119
  -path => '/',
120
  -secure => $at->require_ssl,
121
  -expires => '-1h'
122
);
123

    
124

    
125
# If no cookies found, first check whether cookies are supported
126
if (! $have_cookies && !$q->param('api')) {
127
  # If this is a self redirect warn the user about cookie support
128
  if ($self_redirect) {
129
    $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.";
130
  }
131
  # If no cookies and not a redirect, redirect to self to test cookies
132
  else {
133
    my $extra = '';
134
    $extra .= 'timeout=1' if $timeout;
135
    $extra .= 'unauth=1' if $unauth;
136
    $extra .= "installsystem=$installsystem" if $installsystem;
137
    $extra = "&$extra" if $extra;
138

    
139
    my $cookie = CGI::Cookie->new(-name => 'auth_probe', -value => 1, @auth_domain);
140

    
141
    print redirect(
142
      -uri => sprintf("%s%s%s?redirect=%s&%s=%s%s",
143
                        $location, $mode, $suffix, $self_redirect + 1, $at->back_arg_name,
144
                        $back_esc || '', $extra),
145
      -cookie => [$cookie, $systemcookie],
146
    );
147

    
148
    #print $q->header(
149
    #  -cookie => [$cookie, $systemcookie],
150
    #);
151
    # For some reason, a Location: redirect doesn't seem to then see the cookie,
152
    #   but a meta refresh one does - go figure
153
    #print $q->start_html(
154
    #  -head => meta({
155
    #    -http_equiv => 'Pragma', -content => "no-cache"
156
    #  }),
157
    #  -head => meta({
158
    #    -http_equiv => 'refresh', -content => ("0;URL=" . sprintf("%s%s%s?redirect=%s&%s=%s%s",
159
    #      $location, $mode, $suffix, $self_redirect + 1, $at->back_arg_name,
160
    #      $back_esc || '', $extra))
161
    #}));
162
    $redirected = 1;
163
  }
164

    
165
} elsif ($mode eq 'autologin') {
166
  $ticket = $ticket || $q->param($at->cookie_name);
167
  # If we have a ticket, redirect to $back, including ticket as GET param
168
  if ($ticket && $back && ! $timeout) {
169
#    my $b = URI->new($back);
170
#    $back .= $b->query ? '&' : '?';
171
#    $back .= $at->cookie_name . '=' . $ticket;
172

    
173
    #print $q->redirect($back);
174
    my %params = $q->Vars;
175
    $steamaccount = $params{'account'};
176
    if ($steamaccount) {
177
      my $cookie = $q->cookie(-name => 'steamaccount',
178
          -value => $steamaccount,
179
          -path => '/',
180
          -secure => $at->require_ssl,
181
          @auth_domain,
182
      );
183
    # Let's extract username from ticket, rather than trusting param
184
      my $valid = $at->validate_ticket($ticket);
185
      unless (time - $valid->{ts} > 2*60*60) { # Default auth_tkt timeout is 2 hours
186
      #  $username = $valid->{uid};
187
      }
188
      $session = substr($ticket, 0, 6);
189
      set_cookie_redirect($ticket, $back, $cookie);
190
    } else {
191
      set_cookie_redirect($ticket, $back, $systemcookie);
192
    }
193
    $redirected = 1;
194

    
195
  }
196
  # Can't autologin - change mode to either guest or login
197
  else {
198
    $mode = $AuthTktConfig::AUTOLOGIN_FALLBACK_MODE;
199
  }
200
}
201

    
202
unless ($fatal || $redirected) {
203
  if (! $at) {
204
    $fatal = "AuthTkt error: " . $at->errstr;
205

    
206
  } elsif ($mode eq 'login') {
207
    if ($username && $password) {
208
      my ($valid, $tokens) = $AuthTktConfig::validate_sub->($username, $password, $totp);
209
      $validtoken = $valid;
210
      if ($valid == 2) { # User has 2fa enabled - present 2fa login screen
211
        push @errors, 'Please type your 2-factor authentication code';
212
      } elsif ($valid) {
213
#       my $user_data = join(':', encrypt($password), time(), ($ip_addr ? $ip_addr : ''));
214
        my $user_data = join(':', time(), ($ip_addr ? $ip_addr : ''));    # Optional
215
        my $tkt = $at->ticket(uid => $username, data => $user_data, 
216
          ip_addr => $ip_addr, tokens => $tokens, debug => $AuthTktConfig::DEBUG);
217
        if (! @errors) {
218
          $redirected = set_cookie_redirect($tkt, $back, $systemcookie);
219
          $fatal = "Login successful.";
220
        }
221
      }
222
      else {
223
        push @errors, "Invalid username or password.";
224
      }
225
    }
226
  } elsif ($mode eq 'guest') {
227
    # Generate a guest ticket and redirect to $back
228
    my $tkt = $at->ticket(uid => $AuthTktConfig::guest_sub->(), ip_addr => $ip_addr);
229
    if (! @errors) {
230
#      $redirected = $set_cookie_redirect->($tkt, $back, $systemcookie);
231
      $redirected = set_cookie_redirect($tkt, $back, $systemcookie);
232
      $fatal = "No back link found.";
233
    }
234
  }
235
}
236

    
237
my @style = ();
238
#@style = ( '-style' => { src => $AuthTktConfig::STYLESHEET } )
239
#  if $AuthTktConfig::STYLESHEET;
240
@style = ( '-style' => { src => '/stabile/static/css/style.css' } );
241
my $title = $AuthTktConfig::TITLE || "\u$mode Page";
242
unless ($redirected) {
243
  if ($q->param('api')) {
244
    print $q->header("application/json");
245
    print qq|{"status": "Error"}\n|;
246
    exit;
247
  }
248
    # If here, either some kind of error or a login page
249
  if ($fatal) {
250
    print $q->header(
251
        -cookie => [$systemcookie,$auth_tktcookie,$tktusercookie]
252
    ),
253
      $q->start_html(
254
        -head => meta({-http_equiv => 'Pragma', -content => "no-cache"}),
255
        -title => $title,
256
        @style,
257
      );
258
  } else {
259
    push @errors, qq(Your session has timed out.) if $timeout;
260
    push @errors, qq(You are not authorised to access this area.) if $unauth;
261
    my $foc = ($username?'1':'0');
262
    print $q->header(-status=>'401', -cookie => [$systemcookie,$auth_tktcookie,$tktusercookie]),
263
      $q->start_html(
264
        -head => [
265
            meta({-http_equiv => 'Pragma', -content => "no-cache"}),
266
            $q->Link({
267
               -rel => 'SHORTCUT ICON',
268
               -href =>$logo_icon,
269
            })
270
          ],
271
        -meta=>{'viewport'=>'width=device-width, initial-scale=1'},
272
        -link=>{'rel'=>'icon', 'href'=>$logo_icon, 'sizes'=>'192x192'},
273
        -title => $title,
274
        -class => 'login',
275
        -onLoad => "getFocus()",
276
        @style,
277
        -script => qq(
278
function getFocus() {
279
  document.forms[0].elements[$foc].focus();
280
  document.forms[0].elements[$foc].select();
281
}));
282
  }
283

    
284
  print <<EOD;
285
<div align="center">
286
EOD
287

    
288

    
289
  if ($AuthTktConfig::DEBUG) {
290
    my $cookie_name = $at->cookie_name;
291
    my $back_cookie_name = $at->back_cookie_name || '';
292
    my $back_arg_name = $at->back_arg_name || '';
293
    my $cookie_expires = $at->cookie_expires || 0;
294
    print <<EOD;
295
<pre>
296
server_name: $server_name
297
server_port: $server_port
298
domain: $AUTH_DOMAIN
299
mode: $mode
300
suffix: $suffix
301
cookie_name: $cookie_name
302
cookie_expires: $cookie_expires
303
back_cookie_name: $back_cookie_name
304
back_arg_name: $back_arg_name
305
back: $back
306
back_esc: $back_esc
307
back_html: $back_html
308
have_cookies: $have_cookies
309
ip_addr: $ip_addr
310
EOD
311
    if ($Apache::AuthTkt::VERSION >= 2.1) {
312
      printf "digest_type: %s\n", $at->digest_type;
313
    }
314
    print "</pre>\n";
315
  }
316

    
317
  if ($fatal) {
318
    print qq(<p class="error">$fatal</p>\n);
319
  }
320

    
321
  else {
322
    my $sha_pwd = $password;
323
    $sha_pwd = sha512_base64($password) unless ($password && length($password) == 86);
324
    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"
325
      if @errors;
326
    print <<EOD;
327
<div id="auth-header">
328
    <a href="#"><img src="$logo" border="0" style="height:48px; vertical-align:middle; margin:20px;"/></a>
329
</div>
330
<form name="login" method="post" style="width:200px;" id="auth-form" accept-charset="utf-8">
331
EOD
332
    ;
333
    if ($validtoken == 2) {
334
      print <<EOD;
335
 			       <input type="hidden" name="username" id="username" value="$username">
336
                   <input type="hidden" name="password" id="password" value="$sha_pwd">
337
                   <img class="logo" src="/stabic/img/google_auth.png" style="margin-bottom: 20px;">
338
                   <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">
339
EOD
340
      ;
341
    } else {
342
      print <<EOD;
343
                  <input value="$username" type="text" name="username" class="form-control" placeholder="Username"/>
344
                  <input type="password" id="password" name="password" class="form-control" placeholder="Password"/>
345
EOD
346
    }
347
  print <<EOD;
348
<input type="submit" value="Login" class="btn btn-success btn-sm pull-right" />
349
EOD
350
    print qq(<input type="hidden" name="back" value="$back_html" />\n) if $back_html;
351
    print qq(</form>\n);
352
}
353
  print <<EOD;
354
</div>
355
</body>
356
</html>
357
EOD
358
}
359

    
360
# ------------------------------------------------------------------------
361
# Set the auth cookie and redirect to $back
362
sub set_cookie_redirect {
363
  my ($tkt, $bk, $systemcook) = @_;
364
  my @expires = $at->cookie_expires ?
365
    ( -expires => sprintf("+%ss", $at->cookie_expires) ) :
366
    ();
367
  my $cookie = CGI::Cookie->new(
368
    -name => $at->cookie_name,
369
    -value => $tkt,
370
    -path => '/',
371
    -secure => $at->require_ssl,
372
    @expires,
373
    @auth_domain
374
  );
375

    
376
  my $usercookie = CGI::Cookie->new(
377
    -name => 'tktuser',
378
    -value => $username,
379
    -path => '/',
380
    -secure => $at->require_ssl,
381
    @expires,
382
    @auth_domain
383
  );
384
  # Zap the guac cookie if redirecting to guacamole
385
  my $guaccookie = CGI::Cookie->new(
386
          -name => 'GUAC_AUTH',
387
          -value => '',
388
          -path => '/guacamole/',
389
          -secure => $at->require_ssl,
390
  );
391

    
392
  #print header();
393
  #print "BACK: $back, ", $q->param($at->back_arg_name), ",", $at->back_arg_name, "\n";
394
  #my $installsystem = $q->param('installsystem');
395
  #my $systemcookie;
396
  #if ($installsystem) {
397
  #   $systemcookie = CGI::Cookie->new(
398
  #      -name => 'installsystem',
399
  #      -value => "$installsystem",
400
  #      -path => '/',
401
  #  );
402
  #}
403

    
404
 # If no $back, just set the auth cookie and hope for the best
405
  if (! $bk) {
406
    print $q->header( -cookie => [$cookie, $usercookie, $systemcook] );
407
    print $q->start_html, $q->p("Login successful"), $q->end_html;
408
    return 0;
409
  }
410

    
411
  my $bkobj = URI->new($bk);
412
  # If $back domain doesn't match $AUTH_DOMAIN, pass ticket via back GET param
413
  my $domain = $AUTH_DOMAIN || $server_name;
414
  if ($bkobj->host !~ m/\b$domain$/i) {
415
    $bk .= $bkobj->query ? '&' : '?';
416
    $bk .= $at->cookie_name . '=' . $tkt;
417
  }
418

    
419
  if ($q->param('api')) {
420
    print header(
421
        -content_type => "application/json",
422
        -cookie => [ $cookie, $usercookie, $systemcook ]
423
    );
424
    print qq|{"status": "OK", "cookie": "| . $at->cookie_name . qq|", "tkt": "$tkt"}\n|;
425
  } else {
426
    prepare_ui_update($username);
427
    $bk = '' if ($bk =~ /login/);
428
    my @cooks = [$cookie, $usercookie, $systemcook, $guaccookie];
429
#    push @cooks, $guaccookie if ($bk =~ /guacamole/);
430
    print redirect(
431
        -uri => $bk || '/stabile/',
432
        -cookie => @cooks,
433
    );
434
  }
435
  return 1;
436
};
437

    
438
sub trim($){
439
	my $string = shift;
440
	$string =~ s/^\s+//;
441
	$string =~ s/\s+$//;
442
	return $string;
443
}
444

    
445
sub prepare_ui_update {
446
  my $uname = shift;
447
  return unless $uname;
448
  # Update allowed port forwards and create links
449
  # AuthTktConfig::syslogit('info', "Now opening ssh ports for $uname...");
450
  # `/usr/local/bin/permitOpen "$uname"`;
451
  #mkpath('../cgi/ui_update') unless (-e '../cgi/ui_update');
452
  `/bin/ln -s ../ui_update.cgi ../cgi/ui_update/$uname~ui_update.cgi` unless (-e "../cgi/ui_update/$uname~ui_update.cgi");
453
  if ($session) {
454
    eval {
455
      `/bin/rm -f /tmp/$uname~*$session.*.tasks`; # Remove any tasks file from a previous session - no quotes
456
      `/usr/bin/pkill -f "$session."`;
457
      1;
458
    } or do {;};
459
  }
460
}
(3-3/5)