<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">
package AuthCAS;

use strict;

my $VERSION = 1.0;

=head1 NAME

AuthCAS - Client library for CAS 2.0 authentication server

=head1 VERSION

Version 1.0

=head1 DESCRIPTION

AuthCAS aims at providing a Perl API to Yale's Central Authentication System (CAS). Only a basic Perl library is provided with CAS whereas AuthCAS is a full object-oriented library. 
=head1 PREREQUISITES

This script requires IO::Socket::SSL and LWP::UserAgent

=pod OSNAMES

any

=pod SCRIPT CATEGORIES

Network

=head1 SYNOPSIS

  A simple example with a direct CAS authentication

  use AuthCAS;
  my $cas = new AuthCAS(casUrl =&gt; 'https://cas.myserver, 
		    CAFile =&gt; '/etc/httpd/conf/ssl.crt/ca-bundle.crt',
		    );

  my $login_url = $cas-&gt;getServerLoginURL('http://myserver/app.cgi');

  ## The user should be redirected to the $login_url
  ## When coming back from the CAS server a ticket is provided in the QUERY_STRING

  ## $ST should contain the receaved Service Ticket
  my $user = $cas-&gt;validateST('http://myserver/app.cgi', $ST);

  printf "User authenticated as %s\n", $user;


  In the following example a proxy is requesting a Proxy Ticket for the target application

  $cas-&gt;proxyMode(pgtFile =&gt; '/tmp/pgt.txt',
	          pgtCallbackUrl =&gt; 'https://myserver/proxy.cgi?callback=1
		  );
  
  ## Same as before but the URL is the proxy URL
  my $login_url = $cas-&gt;getServerLoginURL('http://myserver/proxy.cgi');

  ## Like in the previous example we should receave a $ST

  my $user = $cas-&gt;validateST('http://myserver/proxy.cgi', $ST);

  ## Process errors
  printf STDERR "Error: %s\n", &amp;AuthCAS::get_errors() unless (defined $user);

  ## Now we request a Proxy Ticket for the target application
  my $PT = $cas-&gt;retrievePT('http://myserver/app.cgi');
    
  ## This piece of code is executed by the target application
  ## It received a Proxy Ticket from the proxy
  my ($user, @proxies) = $cas-&gt;validatePT('http://myserver/app.cgi', $PT);

  printf "User authenticated as %s via %s proxies\n", $user, join(',',@proxies);


=head1 DESCRIPTION

CAS is Yale University's web authentication system, heavily inspired by Kerberos.
Release 2.0 of CAS provides "proxied credential" feature that allows authentication
tickets to be carried by intermediate applications (Portals for instance), they are
called proxy.

This AuthCAS Perl module provides required subroutines to validate and retrieve CAS tickets.

=head1 SEE ALSO

Yale Central Authentication Service (http://www.yale.edu/tp/auth/) 
 phpCAS (http://esup-phpcas.sourceforge.net/)

=head1 COPYRIGHT

Copyright (C) 2003 Comite Reseau des Universites (http://www.cru.fr). All rights reserved.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 AUTHORS

Olivier Salaun

=cut

my @ISA = qw(Exporter);
my @EXPORT = qw($errors);

my $errors;

use Carp;

sub new {
    my($pkg, %param) = @_;
    my $cas_server = {};
    
    $cas_server-&gt;{'url'} = $param{'casUrl'};
    $cas_server-&gt;{'CAFile'} = $param{'CAFile'};
    $cas_server-&gt;{'CAPath'} = $param{'CAPath'};

    $cas_server-&gt;{'loginPath'} = $param{'loginPath'} || '/login';
    $cas_server-&gt;{'logoutPath'} = $param{'logoutPath'} || '/logout';
    $cas_server-&gt;{'serviceValidatePath'} = $param{'serviceValidatePath'} || '/serviceValidate';
    $cas_server-&gt;{'proxyPath'} = $param{'proxyPath'} || '/proxy';
    $cas_server-&gt;{'proxyValidatePath'} = $param{'proxyValidatePath'} || '/proxyValidate';

    bless $cas_server, $pkg;

    return $cas_server;
}

## Return module errors
sub get_errors {
    return $errors;
}

## Use the CAS object as a proxy
sub proxyMode {
    my $self = shift;
    my %param = @_;

    $self-&gt;{'pgtFile'} = $param{'pgtFile'};
    $self-&gt;{'pgtCallbackUrl'} = $param{'pgtCallbackUrl'};
    $self-&gt;{'proxy'} = 1;
    
    return 1;
}

## Escape dangerous chars in URLS
sub _escape_chars {
    my $s = shift;    

    ## Escape chars
    ##  !"#$%&amp;'()+,:;&lt;=&gt;?[] AND accented chars
    ## escape % first
#    foreach my $i (0x25,0x20..0x24,0x26..0x2c,0x3a..0x3f,0x5b,0x5d,0x80..0x9f,0xa0..0xff) {
    foreach my $i (0x26) {
	my $hex_i = sprintf "%lx", $i;
	$s =~ s/\x$hex_i/%$hex_i/g;
    }

    return $s;
}

sub dump_var {
    my ($var, $level, $fd) = @_;
    
    if (ref($var)) {
	if (ref($var) eq 'ARRAY') {
	    foreach my $index (0..$#{$var}) {
		print $fd "\t"x$level.$index."\n";
		&amp;dump_var($var-&gt;[$index], $level+1, $fd);
	    }
	}elsif (ref($var) eq 'HASH') {
	    foreach my $key (sort keys %{$var}) {
		print $fd "\t"x$level.'_'.$key.'_'."\n";
		&amp;dump_var($var-&gt;{$key}, $level+1, $fd);
	    }    
	}
    }else {
	if (defined $var) {
	    print $fd "\t"x$level."'$var'"."\n";
	}else {
	    print $fd "\t"x$level."UNDEF\n";
	}
    }
}

## Parse an HTTP URL 
sub _parse_url {
    my $url = shift;

    my ($host, $port, $path);

    if ($url =~ /^(https?):\/\/([^:\/]+)(:(\d+))?(.*)$/) {
	$host = $2;
	$path = $5;
	if ($1 eq 'http') {
	    $port = $4 || 80;
	}elsif ($1 eq 'https') {
	    $port = $4 || 443;
	}else {
	    $errors = sprintf "Unknown protocol '%s'\n", $1;
	    return undef;
	}
    }else {
	$errors = sprintf "Unable to parse URL '%s'\n", $url;
	return undef;
    }

    return ($host, $port, $path);
}

## Simple XML parser
sub _parse_xml {
    my $data = shift;

    my %xml_struct;

    while ($data =~ /^&lt;([^\s&gt;]+)(\s+[^\s&gt;]+)?&gt;([\s\S\n]*)(&lt;\/\1&gt;)/m) {
	my ($new_tag, $new_data) = ($1,$3);
	chomp $new_data;
	$new_data =~ s/^[\s\n]+//m;
	$data =~ s/^&lt;$new_tag(\s+[^\s&gt;]+)?&gt;([\s\S\n]*)(&lt;\/$new_tag&gt;)//m;
	$data =~ s/^[\s\n]+//m;
	
	## Check if data still includes XML tags
	my $struct;
	if ($new_data =~/^&lt;([^\s&gt;]+)(\s+[^\s&gt;]+)?&gt;([\s\S\n]*)(&lt;\/\1&gt;)/m) {
	    $struct = &amp;_parse_xml($new_data);
	}else {
	    $struct = $new_data;
	}
	push @{$xml_struct{$new_tag}}, $struct;
    }
    
    return \%xml_struct;
}

sub getServerLoginURL {
    my $self = shift;
    my $service = shift;
    
    return $self-&gt;{'url'}.$self-&gt;{'loginPath'}.'?service='.&amp;_escape_chars($service);
}

## Returns non-blocking login URL
## ie: if user is logged in, return the ticket, otherwise do not prompt for login
sub getServerLoginGatewayURL {
    my $self = shift;
    my $service = shift;
    
    return $self-&gt;{'url'}.$self-&gt;{'loginPath'}.'?service='.&amp;_escape_chars($service).'&amp;gateway=1';
}

## Return logout URL
## After logout user is redirected back to the application
sub getServerLogoutURL {
    my $self = shift;
    my $service = shift;
    
    return $self-&gt;{'url'}.$self-&gt;{'logoutPath'}.'?service='.&amp;_escape_chars($service).'&amp;gateway=1';
}

sub getServerServiceValidateURL {
    my $self = shift;
    my $service = shift;
    my $ticket = shift;
    my $pgtUrl = shift;

    my $query_string = 'service='.&amp;_escape_chars($service).'&amp;ticket='.$ticket;
    if (defined $pgtUrl) {
	$query_string .= '&amp;pgtUrl='.&amp;_escape_chars($pgtUrl);
    }

    ## URL was /validate with CAS 1.0
    return $self-&gt;{'url'}.$self-&gt;{'serviceValidatePath'}.'?'.$query_string;
}

sub getServerProxyURL {
    my $self = shift;
    my $targetService = shift;
    my $pgt = shift;

    return $self-&gt;{'url'}.$self-&gt;{'proxyPath'}.'?targetService='.&amp;_escape_chars($targetService).'&amp;pgt='.&amp;_escape_chars($pgt);
}

sub getServerProxyValidateURL {
    my $self = shift;
    my $service = shift;
    my $ticket = shift;

    return $self-&gt;{'url'}.$self-&gt;{'proxyValidatePath'}.'?service='.&amp;_escape_chars($service).'&amp;ticket='.&amp;_escape_chars($ticket);
     
}

## Validate a Service Ticket
## Also used to get a PGT
sub validateST {
    my $self = shift;
    my $service = shift;
    my $ticket = shift;

    my $pgtUrl = $self-&gt;{'pgtCallbackUrl'};
    
    my $xml = $self-&gt;callCAS($self-&gt;getServerServiceValidateURL($service, $ticket, $pgtUrl));

    if (defined $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationFailure'}) {
	$errors = sprintf "Failed to validate Service Ticket %s : %s\n", $ticket, $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationFailure'}[0];
	return undef;
    }

    my $user = $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationSuccess'}[0]{'cas:user'}[0];
    
    ## If in Proxy mode, also retreave a PGT
    if ($self-&gt;{'proxy'}) {
	my $pgtIou;
	if (defined $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationSuccess'}[0]{'cas:proxyGrantingTicket'}) {
	    $pgtIou = $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationSuccess'}[0]{'cas:proxyGrantingTicket'}[0];
	}
	
	unless (defined $self-&gt;{'pgtFile'}) {
	    $errors = sprintf "pgtFile not defined\n";
	    return undef;
	}

	## Check stored PGT
	unless (open STORE, $self-&gt;{'pgtFile'}) {
	    $errors = sprintf "Unable to read %s\n", $self-&gt;{'pgtFile'};
	    return undef;
	}
	
	my $pgtId;
	while (&lt;STORE&gt;) {
	    if (/^$pgtIou\s+(.+)$/) {
		$pgtId = $1;
		last;
	    }
	}
	
	$self-&gt;{'pgtId'} = $pgtId;
    }

    return ($user);
}

## Validate a Proxy Ticket
sub validatePT {
    my $self = shift;
    my $service = shift;
    my $ticket = shift;

    my $xml = $self-&gt;callCAS($self-&gt;getServerProxyValidateURL($service, $ticket));

    if (defined $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationFailure'}) {
	$errors = sprintf "Failed to validate Proxy Ticket %s : %s\n", $ticket, $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationFailure'}[0];
	return undef;
    }

    my $user = $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationSuccess'}[0]{'cas:user'}[0];
    
    my @proxies;
    if (defined $xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationSuccess'}[0]{'cas:proxies'}) {
	@proxies = @{$xml-&gt;{'cas:serviceResponse'}[0]{'cas:authenticationSuccess'}[0]{'cas:proxies'}[0]{'cas:proxy'}};
    }

    return ($user, @proxies);
}

## Access a CAS URL and parses received XML
sub callCAS {
    my $self = shift;
    my $url = shift;

    my ($host, $port, $path) = &amp;_parse_url($url);
    
    my @xml = &amp;get_https2($host, $port, $path,{'cafile' =&gt;  $self-&gt;{'CAFile'},  'capath' =&gt; $self-&gt;{'CAPath'}});

    ## Skip HTTP header fields
    my $line = shift @xml;
    while ($line !~ /^\s*$/){
	$line = shift @xml;
    }

    return &amp;_parse_xml(join('', @xml));
}

sub storePGT {
    my $self = shift;
    my $pgtIou = shift;
    my $pgtId = shift;
    
    unless (open STORE, "&gt;&gt;$self-&gt;{'pgtFile'}") {
	$errors = sprintf "Unable to write to %s\n", $self-&gt;{'pgtFile'};
	return undef;
    }
    printf STORE "%s\t%s\n", $pgtIou, $pgtId;
    close STORE;

    return 1;
}


sub retrievePT {
    my $self = shift;
    my $service = shift;

    my $xml = $self-&gt;callCAS($self-&gt;getServerProxyURL($service, $self-&gt;{'pgtId'}));

    if (defined $xml-&gt;{'cas:serviceResponse'}[0]{'cas:proxyFailure'}) {
	$errors = sprintf "Failed to get PT : %s\n", $xml-&gt;{'cas:serviceResponse'}[0]{'cas:proxyFailure'}[0];
	return undef;
    }

    if (defined $xml-&gt;{'cas:serviceResponse'}[0]{'cas:proxySuccess'}[0]{'cas:proxyTicket'}) {
	return $xml-&gt;{'cas:serviceResponse'}[0]{'cas:proxySuccess'}[0]{'cas:proxyTicket'}[0];
    }

    return undef;
}

# request a document using https, return status and content
sub get_https2{
	my $host = shift;
	my $port = shift;
	my $path = shift;

	my $ssl_data= shift;

	my $trusted_ca_file = $ssl_data-&gt;{'cafile'};
	my $trusted_ca_path = $ssl_data-&gt;{'capath'};

	if (($trusted_ca_file &amp;&amp; !(-r $trusted_ca_file)) ||  
		 ($trusted_ca_path &amp;&amp; !(-d $trusted_ca_path))) {
	    $errors = sprintf "error : incorrect access to cafile $trusted_ca_file or capath $trusted_ca_path\n";
	    return undef;
	}
	
	unless (require IO::Socket::SSL) {
	    $errors = sprintf "Unable to use SSL library, IO::Socket::SSL required, install IO-Socket-SSL (CPAN) first\n";
	    return undef;
	}
	
	unless (require LWP::UserAgent) {
	    $errors = sprintf "Unable to use LWP library, LWP::UserAgent required, install LWP (CPAN) first\n";
	    return undef;
	}

	my $ssl_socket;

	my %ssl_options = (SSL_use_cert =&gt; 0,
			   PeerAddr =&gt; $host,
			   PeerPort =&gt; $port,
			   Proto =&gt; 'tcp',
			   Timeout =&gt; '5'
			   );

	$ssl_options{'SSL_ca_file'} = $trusted_ca_file if ($trusted_ca_file);
	$ssl_options{'SSL_ca_path'} = $trusted_ca_path if ($trusted_ca_path);
	
	## If SSL_ca_file or SSL_ca_path =&gt; verify peer certificate
	$ssl_options{'SSL_verify_mode'} = 0x01 if ($trusted_ca_file || $trusted_ca_path);
	
	$ssl_socket = new IO::Socket::SSL(%ssl_options);
	
	unless ($ssl_socket) {
	    $errors = sprintf "error %s unable to connect https://%s:%s/\n",&amp;IO::Socket::SSL::errstr,$host,$port;
	    return undef;
	}
	
	my $request = "GET $path HTTP/1.0\n\n";
	print $ssl_socket "$request\n\n";

	my @result;
	while (my $line = $ssl_socket-&gt;getline) {
	    push  @result, $line;
	} 
	
	$ssl_socket-&gt;close(SSL_no_shutdown =&gt; 1);	

	return (@result);	
}

1;

</pre></body></html>