lib/VOMS/Lite/VOMS.pm untested

filter: Statementstmt 0.0% 0 / 1124 Branchbran 0.0% 0 / 362 Conditioncond 0.0% 0 / 137 MC/DCmcdc 0.0% 0 / 85 Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 1755 CC 182 SCAR 79.8
CC
182
Cov
0%
Server
4290.0
Get
3306.0
List
2862.0
CRAP 2934.6
1 package VOMS::Lite::VOMS;
2  
3 #Use/require here
4 use VOMS::Lite::ASN1Helper qw(DecToHex Hex ASN1Wrap ASN1Index ASN1OIDtoOID);
5 use IO::Socket;
6 use VOMS::Lite::X509;
7 use VOMS::Lite::CertKeyHelper qw(buildchain);
8 use VOMS::Lite::PEMHelper qw(readCert writeCert writeKey readPrivateKey encodeAC);
9 use VOMS::Lite::RSAHelper qw(rsaencrypt rsasign rsadecrypt rsaverify);
10 use VOMS::Lite::Base64;
11 use VOMS::Lite::AC;
12  
13 use Digest::MD5 qw(md5_hex md5);
14 use Digest::SHA1 qw(sha1_hex sha1);
15 use Crypt::CBC;
16  
17 require Exporter;
18 use vars qw($VERSION $DEBUG @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
19 @ISA = qw(Exporter);
20 $VERSION = '0.20';
21  
22 BEGIN {
23 $DEBUG='no';
24 }
25  
26 my $CAdir="/etc/grid-security/certificates";
27 my $maxrecordsize=16384;
28 #sub ContMesg { return sprintf("%08s",DecToHex(length($_[0])/2)); } # returns hex continuation message for hexstring
29 sub Bin { return pack("H*", $_[0]); }
30 sub handShake { return $_[0].sprintf("%06s",DecToHex(length($_[1])/2)).$_[1]; }
31 sub Seq { return sprintf("%016s",DecToHex($_[0])); }
32 sub recordLayer {
33 my $rsz=$maxrecordsize*2; my $rs;
34 my $len=length($_[1]);
35 for (my $i=0;($i<$len) and $f=substr($_[1],$i,$rsz);$i+=$rsz) { $rs.=$_[0]."0300".sprintf("%04s",DecToHex(length($f)/2)).$f; }
36 return $rs;
37 }
38 my ($pad1md5,$pad2md5,$pad1sha,$pad2sha) = ("\x36" x 48,"\x5c" x 48,"\x36" x 40,"\x5c" x 40);
39 sub MAC { my ($MS,$D)=@_; return md5_hex($MS.$pad2md5.md5($D.$MS.$pad1md5)).sha1_hex($MS.$pad2sha.sha1($D.$MS.$pad1sha));}
40 sub debug {
41 return if ( $DEBUG ne "yes" );
42 my ($type,$out,$hex) = @_;
43 if ( $out eq "" ) { $out="$type\n"; }
44 elsif ( $out =~ /^[\n -~]*$/ and ! defined($hex) ) { $out =~ s/(\n?)([^\n]{1,60})/$type.=(($1 eq "\n")?" +":"");printf("%-19s %s\n",$type,$2);$type=""/ges; }
45 else { $out =~ s/(.{1,16})/$a=Hex($1), $a=~s|..|$& |g,printf("%-19s %s\n",$type,$a),$type=""/ges; }
46 print STDERR $out;
47 }
48  
49 sub Read {
50 my $sock=shift; if ( $sock eq "INETD" ) { $sock = *STDIN;}
51 my ($data,$len);
52 debug("Reading","4 bytes");
53 read ($sock,$data,4); debug("Read",$data);
54 if ( $data =~ /^(.)(.)(.)(.)$/s ) { $len=(ord($1)*16777216 + ord($2)*65536 + ord($3)*256 + ord($4)); }
55 else { return undef; }
56 debug("Reading","$len bytes");
57 read ($sock,$data,$len); debug("Read",$data);
58 return $data;
59 }
60  
61 sub Write {
62 my $sock=shift; if ( $sock eq "INETD" ) { $sock = *STDOUT;}
63 my $data=shift;
64 my $datacont = Bin(sprintf("%08s",DecToHex(length($data))));
65 debug("Sending",$datacont);
66 print $sock $datacont;
67 debug("Sending",$data);
68 print $sock $data;
69 return length($data);
70 }
71  
72 my %SSLv3Errors = ( 0 => "Close notify", #warning/fatal
73 10 => "Unexpected message", #fatal
74 20 => "Bad record MAC", #fatal Possibly a bad SSL implementation, or payload has been tampered with. E.g., FTP firewall rule on FTPS server.
75 21 => "Decryption failed", #fatal TLS only, reserved
76 22 => "Record overflow", #fatal TLS only
77 30 => "Decompression failure", #fatal
78 40 => "Handshake failure", #fatal
79 41 => "No certificate", #warning/fatal SSL v3 only, reserved
80 42 => "Bad certificate", #warning/fatal
81 43 => "Unsupported certificate", #warning/fatal Eg certificate has only Server authentication usage enabled, and is presented as a client certificate
82 44 => "Certificate revoked", #warning/fatal
83 45 => "Certificate expired", #warning/fatal
84 46 => "Certificate unknown", #warning/fatal
85 47 => "Illegal parameter" #fatal
86 );
87  
88 my %SSLv3Warnings = ( 0 => "Close notify",
89 41 => "No certificate",
90 42 => "Bad certificate",
91 43 => "Unsupported certificate",
92 44 => "Certificate revoked",
93 45 => "Certificate expired",
94 46 => "Certificate unknown"
95 );
96  
97 sub ErrWarn { if ( ref($_[0]) eq "ARRAY" ) { push @{ $_[0]} , (caller(1))[3].": $_[1]"; } else { return [ (caller(1))[3].": $_[0]" ]; } }
98  
99 # Parse message records
100 sub ParseRecords {
101 my $records=shift;
102 my %Hand;
103 my @Order;
104 while ($records =~ /^(.)(.)(.)(.)/s) {
105 my ($id,$len) = (ord($1),(ord($2)*65536)+(ord($3)*256)+ord($4));
106 $Hand{'Head'}{$id}=substr($records,0,4,''); # Strip ID and Length bits
107 $Hand{$id} = substr($records,0,$len,'');
108 push @Order,$id;
109 debug("Handshake $id","$Hand{$id}");
110 }
111 $Hand{'Order'}=\@Order;
112 return %Hand;
113 }
114  
115 ###############################################
116  
117 sub Keygen {
118 my ($hexpremastersecret,$Crandom,$Srandom)=@_;
119 # MasterSecret
120 my $hexmaster_secret='';
121 foreach my $ABBCCC ("41","4242","434343") {
122 my $tobesha1ed = Bin($ABBCCC.$hexpremastersecret.$Crandom.$Srandom);
123 my $tobemd5ed = Bin($hexpremastersecret.Digest::SHA1::sha1_hex($tobesha1ed));
124 $hexmaster_secret .= Digest::MD5::md5_hex($tobemd5ed);
125 }
126 my $ms = Bin($hexmaster_secret);
127 # Generate a key block
128 my $kb='';
129 foreach my $ABBCCC ("41","4242","434343","44444444","4545454545","464646464646","47474747474747") {
130 my $tobesha1ed = Bin($ABBCCC.$hexmaster_secret.$Srandom.$Crandom);
131 my $tobemd5ed = $ms.Digest::SHA1::sha1($tobesha1ed);
132 $kb .= Digest::MD5::md5($tobemd5ed);
133 }
134 # Partition key block for DES+SHA1 and return
135 my %keys=( MS => $ms, CMAC=>substr($kb,0,20), SMAC=>substr($kb,20,20), CK=>substr($kb,40,24), SK=>substr($kb,64,24), CIV=>substr($kb,88,8), SIV=>substr($kb,96,8) );
136 foreach ( qw(MS CMAC SMAC CK SK CIV SIV) ) { debug("$_","$keys{$_}");}
137 return %keys;
138 }
139  
140 ###############################################
141  
142 sub Server {
143 my %context=%{ $_[0]};
144 my @error;
145 my @warning; ErrWarn(\@warning,"This function is experimnetal");
146  
147 if ( $] < 5.004 ) { ErrWarn(\@warning,"Perl version is old; random seed is not good"); }
148  
149 # Check necessary inputs are set
150 if ( ! defined $context{'Server'} ) { ErrWarn(\@error,"Server not Specified"); }
151 if ( ! defined $context{'Port'} ) { ErrWarn(\@error,"Port not Specified"); }
152 if ( ! defined $context{'Lifetime'} ) { ErrWarn(\@warning,"No Lifetime specified, setting limit to 12 hours"); }
153  
154 if ( ! defined $context{'Cert'} && ! defined $context{'CertFile'} ) { ErrWarn(\@error,"Certificate not Specified"); }
155 if ( ! defined $context{'Key'} && ! defined $context{'KeyFile'} ) { ErrWarn(\@error,"Key not Specified"); }
156 if ( ! defined $context{'Cert'} && defined $context{'CertFile'} && ! -r $context{'CertFile'} ) { ErrWarn(\@error,"Certificate file unreadable"); }
157 if ( ! defined $context{'Key'} && defined $context{'KeyFile'} && ! -r $context{'KeyFile'} ) { ErrWarn(\@error,"Key file unreadable"); }
158  
159 if ( ! defined $context{'mapfile'} || ! -r $context{'mapfile'} ) { ErrWarn(\@error,"mapfile unreadable"); }
160  
161 if ( @error > 0 ) { return { Errors => \@error, Warnings => \@warning }; }
162  
163 # Check format of input data
164 my $Server = (($context{'Server'} =~ /^([a-z0-9_.-]+)$/) ? $& : undef);
165 my $Port = (($context{'Port'} =~ /^([0-9]{1,5})$/ && $context{'Port'} < 65536) ? $& : undef);
166 my $lifetime = ((defined $context{'Lifetime'}) ? ( ($context{'Lifetime'} =~ /^([0-9]+)$/s ) ? $& : undef ) : 43200 );
167  
168 # Barf if data is not good
169 if ( ! defined $Server ) { ErrWarn(\@error,"Bad VOMS server string"); }
170 if ( ! defined $Port ) { ErrWarn(\@error,"Bad Port"); }
171 if ( ! defined $lifetime ) { ErrWarn(\@error,"Invalid max lifetime"); }
172  
173 # Check VOMS server Inputs: Cert, Key and CAdirs
174 my @certs; my $key;
175 if ( ref($context{'Cert'}) eq "ARRAY" ) { @certs = @{ $context{'Cert'} }; }
176 elsif ( defined($context{'Cert'}) and ref($context{'Cert'}) eq "" ) { @certs = ( $context{'Cert'} ); } #might consider a function to seperate concatenated DERs
177 elsif ( defined($context{'Cert'}) ) { ErrWarn(\@error,"Certs Argument was not an array reference nor a scalar"); }
178 else { @certs = ( readCert($context{'CertFile'}) );}
179  
180 if ( ! @certs ) { ErrWarn(\@error,"Unable to get any server certs."); }
181 foreach my $i (0 .. $#certs) { if ( $certs[$i] !~ /^\x30/s ) { ErrWarn(\@error,"Supplied certificate (\@context{'Cert'}[$i]) $certs[$i] not in DER format"); } }
182  
183 if ( defined $context{'Key'} && $context{'Key'} !~ /^\x30/s ) { ErrWarn(\@error,"Key not in DER format"); }
184 if ( defined $context{'Key'} ) { $key=$context{'Key'}; }
185 else { $key=readPrivateKey($context{'KeyFile'}); }
186 if (! defined($key) ) { ErrWarn(\@error,"Unable to get user key."); }
187  
188 my @CAdirs;
189 if ( defined $context{'CAdirs'} ) {
190 if ( ref($context{'CAdirs'}) eq "ARRAY" ) { @CAdirs = @{ $context{'CAdirs'} }; }
191 elsif ( ref($context{'Cert'}) eq "" ) { @CAdirs = split(':',$context{'CAdirs'}); }
192 else { ErrWarn(\@error,"CAdirs Argument was not a array reference nor a scalar"); }
193 }
194  
195 foreach my $i (0 .. $#CAdirs) { if ( ! -d $CAdirs[$i] ) { ErrWarn(\@error,"Supplied CA directory (\@context{'CAdirs'}[$i]) is not a directory"); } }
196 if ( @error > 0 ) { return { Errors => \@error, Warnings => \@warning }; }
197  
198 #######################################
199 # If CAdirs is not defined try to get CAdirs from environment
200 if ( ! @CAdirs and $ENV{X509_CERT_DIR} ) {
201 if ( -d $ENV{X509_CERT_DIR} and $ENV{X509_CERT_DIR} =~ /^(.+)$/) { push @CAdirs,$1; }
202 else { return { Errors => ErrWarn("X509_CERT_DIR defined but it is not a directory"), Warnings => \@warning }; }
203 }
204 elsif ( ! @CAdirs ) {
205 if ( -d $CAdir ) { push @CAdirs, $CAdir; ErrWarn(\@warning,"No CAdirs specified Using $CAdir"); }
206 else { return { Errors => ErrWarn('No CAdir found'), Warnings => \@warning }; }
207 }
208  
209  
210 #######################################
211 # Listen on $socket $port if INETD is not set
212 my $sock="INETD";
213 if ( ! defined $context{Inetd} ) {
214 my $socklistener = new IO::Socket::INET ( LocalHost => $Server, LocalPort => $Port, Proto => 'tcp', Listen => 1, Reuse => 1, );
215 die "dead" unless $socklistener;
216 return { Errors => ["Unable to listen on $Server:$Port"], Warnings => \@warning } unless $socklistener;
217 $socklistener->autoflush(1);
218 $sock = $socklistener->accept();
219 }
220  
221 #######################################
222 # Listen for ClientHello
223  
224 my $response=Read($sock);
225  
226 my $hexclienthellorecord=Hex($response);
227 my $records="";
228 my @clienthello;
229 while (length($response) > 0) {
230 my $lenstr=substr($response,0,5,'');
231 my $len;
232 if ($lenstr =~ /^\x16\x03\x00(.)(.)/s ) { $len=ord($1)*256+ord($2); }
233 else { return { Errors => ["Malformed SSL header from client while waiting for SSL ClientHello messages"], Warnings => \@warning }; }
234 push @clienthello,Hex($lenstr.substr($response,0,$len));
235 $records.=substr($response,0,$len,'');
236 }
237  
238 my $Hmsgs=$records; ###Used to verify client cert later
239  
240 # Parse Handshake message records
241 my %Hand = ParseRecords($records);
242  
243 #Get ClientHello bits and pieces
244 my $cHello = $Hand{1};
245 my $cHelloVer = substr($cHello,0,2,'');
246 my $cHelloTime = substr($cHello,0,4,'');
247 my $cHelloRand = substr($cHello,0,28,'');
248 my $cHelloIDlen = ord(substr($cHello,0,1,''));
249 my $cHelloSessionID = substr($cHello,0,$cHelloIDlen,'');
250 my $cHelloCypherSuiteslen = substr($cHello,0,2,'');
251 my $CSlen = (ord(substr($cHelloCypherSuiteslen,0,1))*256) + ord(substr($cHelloCypherSuiteslen,1,1));
252 my $cHelloCypherSuites = substr($cHello,0,$CSlen,'');
253 my $cHelloCompressionMethodlen = ord(substr($cHello,0,1,''));
254 my $cHelloCompressionMethod = substr($cHello,0,$cHelloCompressionMethodlen,'');
255 debug("cHello",$Hand{1});
256 debug("cHelloVer","$cHelloVer");
257 debug("cHelloTime","$cHelloTime");
258 debug("cHelloRand","$cHelloRand");
259 debug("cHelloIDlen","$cHelloIDlen");
260 debug("cHelloSessionID","$cHelloSessionID");
261 debug("cHelloCypherSuiteslen","$cHelloCypherSuiteslen");
262 debug("CSlen",$CSlen);
263 debug("cHelloCypherSuites","$cHelloCypherSuites");
264 debug("CMlen",$cHelloCompressionMethodlen);
265 debug("cHelloCompressionMethod","$cHelloCompressionMethod");
266  
267 #check for the (only) cyphersuite I support
268 return { Errors => ["No Common Cyphersuite supported"], Warnings => \@warning } if ( $cHelloCypherSuites !~ /^(..)*?\x00\x0a/ );
269 return { Errors => ["No Common Cyphersuite supported"], Warnings => \@warning } if ( $cHelloCompressionMethod !~ /\x00/ );
270 #All implementations must support compression method 00
271  
272 # Send Server Hello
273 my $hextime = DecToHex(time);
274 my $time = Bin($hextime);
275 my $rnd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $rnd =~ s/./chr(int(rand 256))/ge;#not so good on Win32 32000 cycle reported
276 my $hexrnd = Hex($rnd);
277 my $hexrandom = $hextime.$hexrnd;
278 my $ses = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $ses =~ s/./chr(int(rand 256))/ge; ### Not used
279 my $hexsession = "20".Hex($ses);
280 my $hexcypher = "000a"; #Ciphersuite TLS_RSA_WITH_3DES_EDE_CBC_SHA
281 my $hexcompression = "00"; #CompressionMeth - Use none no need data minimal + this is a lite implementation
282 my $hexssl_version = "0300";
283 # my $hexhandshake_parts = $hexssl_version.$hexrandom.$hexsession.$hexcypher.$hexcompression;
284 my $hexhello = handShake("02",$hexssl_version.$hexrandom.$hexsession.$hexcypher.$hexcompression);
285 my $hexhellorecord = recordLayer("16",$hexhello);
286  
287 $Hmsgs .= Bin($hexhello);
288  
289 ############
290 # CA names message
291 my @CAfiles;
292 foreach my $DIR (@CAdirs) { opendir(my $dh, $DIR); foreach (grep { /\.[0-9]+$/ && -f "$DIR/$_" } readdir($dh)) { push @CAfiles, $DIR."/".$_; } closedir $dh; }
293  
294 my $hexcacerts="";
295  
296 foreach $cafile (@CAfiles) {
297 my $DER = readCert("$cafile");
298 my %certinfo = %{ VOMS::Lite::X509::Examine( $DER, { X509subject => "" }) };
299 debug ("X509Subject","$certinfo{X509subject}");
300 $hexcacerts.=sprintf("%04s",DecToHex(length($certinfo{'X509subject'}))).Hex($certinfo{'X509subject'});
301 }
302  
303 $hexcacerts="020102".sprintf("%04s",DecToHex(length($hexcacerts)/2)).$hexcacerts; #####Perhaps 0101 rather than 020102
304  
305 my $RSACertreq = handShake("0d",$hexcacerts);
306  
307 $Hmsgs.=Bin($RSACertreq);
308  
309 # Construct Server Certificate Message
310 # Get details from Cert
311 my %chain = %{ VOMS::Lite::CertKeyHelper::buildchain( { trustedCAdirs => \@CAdirs, suppliedcerts => \@certs } ) };
312 my @chain = @{ $chain{'Certs'} };
313 my $certmsgcerts; foreach ( @chain ) { $certmsgcerts.=sprintf("%06s",DecToHex(length($_))).Hex($_); }
314 $certmsgcerts = sprintf("%06s",DecToHex(length($certmsgcerts)/2)).$certmsgcerts;
315 my $hexServerCertMsg = handShake("0b",$certmsgcerts);
316  
317 $Hmsgs .= Bin($hexServerCertMsg);
318  
319 # Construct ServerFinished
320 my $ServerFinished = handShake("0e","");
321  
322 $Hmsgs.=Bin($ServerFinished);
323  
324 # Send Server Hello Record
325 Write($sock,Bin($hexhellorecord.recordLayer("16",$RSACertreq.$hexServerCertMsg.$ServerFinished)));
326  
327 ############################ Wait for client
328 #Expect: 'hexcertsmessagerecord','hexClientKeyExchangeMessageRecord','hex_ssl_certificateverifyrecord','hexkeyselection','hex_finishedrecord'
329  
330 $response=Read($sock);
331 my $hexclientresponse=Hex($response);
332 my $records=""; my $changecypher;
333 my @clientResponse;
334 while (length($response) > 0) {
335 my $lenstr=substr($response,0,5,'');
336 my $len;
337 if ($lenstr =~ /^\x16\x03\x00(.)(.)/s ) { $len=ord($1)*256+ord($2); }
338 elsif ($lenstr =~ /^\x14\x03\x00(.)(.)/s ) {
339 $len=ord($1)*256+ord($2);
340 $changecypher=substr($response,0,$len,''); #CCS
341 return { Errors => ["Unknown Encryption Message"], Warnings => \@warning } unless ($changecypher =~ /^\x01$/ );
342 last;
343 }
344 else { return { Errors => ["Malformed SSL header from client while waiting for SSL messages"], Warnings => \@warning }; }
345 push @clientResponse,Hex($lenstr.substr($response,0,$len));
346 $records.=substr($response,0,$len,'');
347 }
348  
349 my $clienthellomsgs2=""; #### used in verify step
350 my $clienthellomsgs3=""; #### Used in hello finished verification
351  
352 my %Hand = ParseRecords($records);
353 foreach (@{ $Hand{'Order'} }) { last if ($_ eq "15"); $Hmsgs.=$Hand{'Head'}{$_}.$Hand{$_}; }
354  
355 #Get the client certificate - 1, Verify it 2, key material for pre-master key exchange later
356 my $certcont = $Hand{11};
357 my $lcerts = substr($certcont,0,3,'');
358 my @CLIcerts=();
359 while ( length($certcont)>3 && ($lcert=substr($certcont,0,3,''))) {
360 if ($lcert =~ /(.)(.)(.)/s ) { push @CLIcerts, substr($certcont,0,(ord($1)*65536)+(ord($2)*256)+ord($3),''); }
361 }
362 return { Errors => ["No cert returned from client"], Warnings => \@warning } unless (@CLIcerts);
363 my %ClientCertInfo= %{ VOMS::Lite::X509::Examine( $CLIcerts[0], { SubjectDN=>"", IssuerDN=>"", Keymodulus=>"", KeypublicExponent=>"", subjectAltName=>"" }) };
364 my $ClientDN=$ClientCertInfo{'SubjectDN'};
365 # my @SubjectAltNames=@{ $ClientCertInfo{'subjectAltNameArray'} }; foreach (@SubjectAltNames) { debug("Altname",$_); }
366 debug("Client DN",$ClientDN);
367  
368 #Get the client key exchange message
369 my $keyexchange = $Hand{16};
370 my %KeyInfo = %{ VOMS::Lite::KEY::Examine($key, {Keymodulus=>"", KeyprivateExponent=>""} ) };
371 my $hexpremastersecret = rsadecrypt(Hex($keyexchange),Hex($KeyInfo{KeyprivateExponent}),Hex($KeyInfo{Keymodulus}));
372 return {Errors => ["VOMS::Lite::VOMS::Server: Premaster Secret received from client did not decrypt correctly with Server's private key"],
373 Warnings => \@warning } if ($hexpremastersecret !~ /^0300.{92}$/s );
374  
375 ###########################################
376 # Build and verify client certificate chain
377  
378 foreach (@CAdirs) { debug("CADIR","$_")};
379 my %Chain = %{ buildchain( { trustedCAdirs => \@CAdirs, suppliedcerts => \@CLIcerts } ) };
380 my @returnedCerts = @{ $Chain{Certs} };
381 my @Trust = @{ $Chain{TrustedCA} };
382 my $EECDN = $Chain{EndEntityDN};
383 my $EECIDN = $Chain{EndEntityIssuerDN};
384 my $EEC = $Chain{EndEntityCert};
385 my @Errors = @{ $Chain{Errors} };
386  
387 #Check for cerification errors in client certificate
388 ErrWarn(\@warning, "NO CRL Check implemented");
389 ErrWarn(\@warning, "NO Certificate Purpose Check implemented");
390 ErrWarn(\@warning, "NO CA signing policy check implemented");
391 for (my $i=0;$i < $#Errors;$i++ ) { if ( @{ $Errors[$i] } ) { ErrWarn(\@error,"Error verifying client's certificate chain (depth $i): ".join(", ",@{ $Errors[$i] })); } }
392 ErrWarn(\@error,"Client's Certificate is not trusted by server") unless ($Trust[-1]);
393 return { Errors => \@error, Warnings => \@warning } if (@error);
394  
395  
396 #Derive Key Material
397 my %KEYS=Keygen($hexpremastersecret,Hex($cHelloTime.$cHelloRand),$hexrandom);
398  
399 # Derive Certificate Verify
400 my $verifymac = MAC($KEYS{'MS'},$Hmsgs);
401  
402 # Decrypt (verify) Certificate Verify
403 my $TBVverifymac=$Hand{15};
404 my $TBVverifymaclen=(ord(substr($TBVverifymac,0,1,''))*256) + ord(substr($TBVverifymac,0,1,''));
405 if ( length($TBVverifymac) != $TBVverifymaclen ) { return { Errors => ErrWarn("Certificate Verification failed verify Mac length mismatch"), Warnings => \@warning }; }
406 my $verifyData = rsaverify(Hex($TBVverifymac),Hex($ClientCertInfo{KeypublicExponent}),Hex($ClientCertInfo{Keymodulus}));
407  
408 if ($verifyData ne $verifymac) { return { Errors => ErrWarn("Certificate Verification failed verify Mac mismatch"), Warnings => \@warning }; }
409  
410 # Set up the Client and Server DES3-EDE sessions
411 my $Ccipher = Crypt::CBC->new( -literal_key => 1, -padding => 'null', -key => $KEYS{'CK'}, -iv => $KEYS{'CIV'}, -header => 'none', -cipher => 'DES_EDE3' );
412 my $Scipher = Crypt::CBC->new( -literal_key => 1, -padding => 'null', -key => $KEYS{'SK'}, -iv => $KEYS{'SIV'}, -header => 'none', -cipher => 'DES_EDE3' );
413 my $Cseq=0;
414 my $Sseq=0;
415  
416 # Decrypt received finished message and check against locally derived message
417 $Hmsgs.=$Hand{'Head'}{15}.$Hand{15};
418 my $clientfinishedhex=Hex(&Decrypt($response,$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher));
419 my $unechexfinished = handShake("14",MAC($KEYS{'MS'},$Hmsgs."CLNT"));
420 if ($clientfinishedhex ne $unechexfinished) { return { Errors => ["Hello Finished decryption failed"], Warnings => \@warning }; }
421  
422 # Send Change Cipher Spec and Server Finished
423 my $hexkeyselection="140300000101";
424  
425 my $unechexfinished = handShake("14",MAC($KEYS{'MS'},$Hmsgs.Bin($unechexfinished)."SRVR"));
426 my $hex_finishedrecord = &Encrypt(Bin(recordLayer("16",$unechexfinished)),$KEYS{'SMAC'},$pad1sha,$pad2sha,$Sseq,$Scipher);
427 my $hex_finished = $hex_finishedrecord;
428 $hex_finished =~ s/^..........//s;
429  
430 Write($sock,Bin($hexkeyselection.$hex_finishedrecord));
431  
432 # Read GSI Data
433 $response=Read($sock);
434  
435 if ( $response !~ /^\x17/ ) { return { Errors => ErrWarn("Expecting Encrypted Application Data, got something else"), Warnings => \@warning }; }
436 my $apdata=&Decrypt($response,$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher);
437  
438 if ( $apdata ne "0" ) { return { Errors => ErrWarn("Client Requested Delegation"), Warnings => \@warning }; }
439  
440 ####################################################
441 # GSI Secured Channel now in operation
442  
443 $response=Read($sock);
444  
445 if ( $response !~ /^\x17/ ) { return { Errors => ["Expecting Encrypted Application Data, got something else"], Warnings => \@warning }; }
446 my $apdata=&Decrypt($response,$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher);
447  
448 my @W; my @E;
449  
450 my ($VOMSReq) = $apdata =~ m{<voms>(.*)</voms>};
451 my @Command = $VOMSReq =~ m{<command>([^<]*)</command>}g;
452 my ($Base) = $VOMSReq =~ m{<base64>([^<]*)</base64>};
453 my ($Version) = $VOMSReq =~ m{<version>([^<]*)</version>};
454 my ($Lifetime) = $VOMSReq =~ m{<lifetime>([0-9]*)</lifetime>};
455 if ($Lifetime > $lifetime) {
456 ErrWarn(\@warning,"Lifetime requested too large. Defaulting to $lifetime");
457 push @W,"<item><number>901</number><message>Lifetime $Lifetime too large defaulting to ${lifetime}s</message></item>";
458 } else { $lifetime = $Lifetime }
459  
460 my ($Order) = $VOMSReq =~ m{<order>([^<]*)</order>};
461 my ($Target) = $VOMSReq =~ m{<targets>([^<]*)</targets>};
462  
463 foreach (@Command) { debug("Command",$_); }
464 debug("Base",$Base);
465 debug("Version",$Version);
466 debug("Lifetime",$Lifetime);
467 debug("Order",$Order);
468 debug("Target",$Target);
469  
470 my $Data='<xml version="1.0" encoding = "US-ASCII"?><vomsans>';
471  
472 my @CommandData;
473 foreach (@Command) {
474 if ( m{^G(/.*)} ) { push @CommandData,$1; }
475 else { push @E,"<item><number>1901</number><message>Command $_ unsupported</message></item>"; }
476 }
477  
478 # Look for AC release authority in gridmapfile
479 my %allowed;
480 open(GMFILE,$context{mapfile}) or return {Errors => ErrWarn("Unable to open $context{mapfile}"), Warnings => \@warning };
481 foreach (<GMFILE>) { if ( /^\s*"$EECDN"\s+(.*)/ ) { debug ("Found Auth",$1); foreach (split /\s+/,$1) {$Allowed{$_}=1;} last;} }
482 close GMFILE;
483  
484 foreach (@CommandData) { if ( ! defined $Allowed{$_} ) {push @E,"<item><number>1902</number><message>$EECDN not authorised for $_</message></item>";} }
485  
486 if (@E) { $Data.="<error>"; foreach(@E) { $Data.=$_; } $Data.="</error>";} #Error codes are wrong
487 else {
488 my $acref = VOMS::Lite::AC::Create( { Cert => $EEC,
489 VOMSCert => $certs[0],
490 VOMSKey => $key,
491 Lifetime => $lifetime,
492 Server => $Server,
493 Port => $Port,
494 Serial => time(), #Reasonably different --- Could do better
495 Code => $Port,
496 Attribs => \@CommandData
497 } );
498 foreach (@$acref{Errors}) { debug("Error",join(",",@$_)) if (@$_); }
499 debug("AC",$$acref{AC});
500 my $CODEDAC=VOMS::Lite::Base64::Encode($$acref{AC},($Base==1)?"RFC3548":"VOMS");
501 # <bitstr>CODEDDATA</bitstr>
502  
503 if (@W) { $Data.="<error>"; foreach(@W) { $Data.=$_; } $Data.="</error>";}
504 $Data.="<ac>$CODEDAC</ac>";
505 $Data.="<version>4</version>";
506 }
507 $Data.="</vomsans>";
508  
509 # predata to stop TLS CBC IV attack
510 my $predata = Bin(&Encrypt(Bin("1703000000"),$KEYS{'SMAC'},$pad1sha,$pad2sha,$Sseq,$Scipher));
511 Write($sock,$predata.Bin(&Encrypt(Bin(recordLayer("17",Hex($Data))),$KEYS{'SMAC'},$pad1sha,$pad2sha,$Sseq,$Scipher)));
512  
513 return { Warnings => \@warning };
514 }
515  
516 #########################################
517  
518 sub Get {
519 my %context=%{ $_[0]};
520 my @error; my @warning;
521  
522 if ( $] < 5.004 ) { ErrWarn(\@warning, "Perl version is old; random seed is not good"); }
523  
524 if ( ! defined $context{'Server'} ) { ErrWarn(\@error, "Server not Specified"); }
525 if ( ! defined $context{'Port'} ) { ErrWarn(\@error, "Port not Specified"); }
526 if ( ! defined $context{'FQANs'} ) { ErrWarn(\@error, "No FQANs requested"); }
527 if ( ! defined $context{'Lifetime'} ) { ErrWarn(\@warning, "No Lifetime specified, requesting 12 hours"); }
528  
529 # IO::SOCKET::SSL may optionally use a cert and key on the file system, we too;
530 if ( ! defined $context{'Cert'} && ! defined $context{'CertFile'} ) { ErrWarn(\@error, "Certificate not Specified"); }
531 if ( ! defined $context{'Key'} && ! defined $context{'KeyFile'} ) { ErrWarn(\@error, "Key not Specified"); }
532 if ( ! defined $context{'Cert'} && defined $context{'CertFile'} && ! -r $context{'CertFile'} ) { ErrWarn(\@error, "Certificate file unreadable"); }
533 if ( ! defined $context{'Key'} && defined $context{'KeyFile'} && ! -r $context{'KeyFile'} ) { ErrWarn(\@error, "Key file unreadable"); }
534  
535 if (ref( $context{'FQANs'} ) ne 'ARRAY') { ErrWarn(\@error,"FQANs must be a reference to an array of FQANs."); }
536 if ( @error > 0 ) { return { Errors => \@error, Warnings => \@warning }; }
537  
538 my $Server = (($context{'Server'} =~ /^([a-z0-9_.-]+)$/) ? $& : undef);
539 my $Port = (($context{'Port'} =~ /^([0-9]{1,5})$/ && $context{'Port'} < 65536) ? $& : 7512);
540 my $lifetime = ((defined $context{'Lifetime'}) ? ( ($context{'Lifetime'} =~ /^([0-9]+)$/s ) ? $& : undef ) : 43200 );
541 my @FQANs = @{ $context{'FQANs'} };
542 foreach (@FQANs) { if (!m{^/[a-zA-Z0-9_.-]+(/[^/]+)*$}) { ErrWarn(\@error, "\"$_\" is not a valid FQAN."); } }
543  
544 # Barf if data is not good
545 if ( ! defined $Server ) { ErrWarn(\@error, "Bad VOMS server string"); }
546 if ( ! defined $Port ) { ErrWarn(\@error, "Bad Port"); }
547 if ( ! defined $lifetime ) { ErrWarn(\@error, "Invalid Lifetime $context{'Lifetime'}. Must be a positive integer. e.g. 43200 for 12h"); }
548  
549 my @certs; my $key;
550 if ( ref($context{'Cert'}) eq "ARRAY" ) { @certs = @{ $context{'Cert'} }; }
551 elsif ( defined($context{'Cert'}) and ref($context{'Cert'}) eq "" ) { @certs = ( $context{'Cert'} ); } #might consider a function to seperate concatenated DERs
552 elsif ( defined($context{'Cert'}) ) { ErrWarn(\@error, "Certs Argument was not a reference to an array nor a scalar"); }
553 else { @certs = ( readCert($context{'CertFile'}) );}
554 if ( ! @certs ) { ErrWarn(\@error, "Unable to get any user certs."); }
555 foreach my $i (0 .. $#certs) { if ( $certs[$i] !~ /^\x30/s ) { ErrWarn(\@error, "Supplied certificate (\@context{'Cert'}[$i]) $certs[$i] not in DER format"); } }
556  
557 if ( defined $context{'Key'} && $context{'Key'} !~ /^\x30/s ) { ErrWarn(\@error, "Supplied Key not in DER format"); }
558 if ( defined $context{'Key'} ) { $key=$context{'Key'}; }
559 else { $key=readPrivateKey($context{'KeyFile'}); }
560 if (! defined($key) ) { ErrWarn(\@error, "Unable to get user key."); }
561  
562 my @CAdirs;
563 if ( defined $context{'CAdirs'} ) {
564 if ( ref($context{'CAdirs'}) eq "ARRAY" ) { @CAdirs = @{ $context{'CAdirs'} }; }
565 elsif ( ref($context{'Cert'}) eq "" ) { @CAdirs = split(':',$context{'CAdirs'}); }
566 else { ErrWarn(\@error, "CAdirs Argument was not a reference to an array nor a scalar"); }
567 }
568  
569 foreach my $i (0 .. $#CAdirs) { if ( ! -d $CAdirs[$i] ) { ErrWarn(\@error, "Supplied CA directory (\@context{'CAdirs'}[$i]) is not a directory"); } }
570  
571 if ( @error > 0 ) { return { Errors => \@error, Warnings => \@warning }; }
572  
573 #Need CAdirs
574 #==========================================================
575 if ( ! @CAdirs and $ENV{X509_CERT_DIR} ) {
576 if ( -d $ENV{X509_CERT_DIR} and $ENV{X509_CERT_DIR} =~ /^(.*)$/) { push @CAdirs,$1; }
577 else { return { Errors => ErrWarn('X509_CERT_DIR defined but it is not a directory'), Warnings => \@warning }; }
578 }
579 elsif ( ! @CAdirs ) {
580 if ( -d $CAdir ) { push @CAdirs, $CAdir; ErrWarn(\@warning,"no CAdir specified Using $CAdir"); }
581 else { return { Errors => ErrWarn('No CAdir found'), Warnings => \@warning }; }
582 }
583  
584 # Get details from Cert and Key
585 my %certinfo = %{ VOMS::Lite::X509::Examine( $certs[0], { SubjectDN=>"", IssuerDN=>"" }) };
586 my %chain = %{ VOMS::Lite::CertKeyHelper::buildchain( { trustedCAdirs => \@CAdirs, suppliedcerts => \@certs } ) };
587 my @chain = @{ $chain{'Certs'} };
588 my $UserDN = $chain{'EndEntityDN'};
589 my $UserIDN = $chain{'EndEntityIssuerDN'};
590 my %keyinfo = %{ VOMS::Lite::KEY::Examine( $key, { Keymodulus=>"",KeyprivateExponent=>"" }) };
591 my $Keymod = Hex($keyinfo{'Keymodulus'});
592 my $Keyexp = Hex($keyinfo{'KeyprivateExponent'});
593 my $DN = $certinfo{'SubjectDN'};
594 my $IDN = $certinfo{'IssuerDN'};
595  
596 #Open a socket to the server
597 my $sock = new IO::Socket::INET( PeerAddr => $Server, PeerPort => $Port, Proto => 'tcp', Type => SOCK_STREAM);
598 if ( ! defined ($sock) ) { return { Errors => ErrWarn("Unable to establish a connection to $Server:$Port"), Warnings => \@warning }; }
599 $sock->autoflush(1);
600  
601 #######################################
602 #Construct Initial Components required for SSL
603 #Random
604 my $hextime = DecToHex(time);
605 my $time = Bin($hextime);
606 my $rnd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $rnd =~ s/./chr(int(rand 256))/ge;#not so good on Win32 32000 cycle reported
607 my $hexrnd = Hex($rnd);
608 my $hexrandom = $hextime.$hexrnd;
609 my $hexsession = "00"; #none - new session
610 my $hexcypher_vec = "000a"; #Ciphersuite TLS_RSA_WITH_3DES_EDE_CBC_SHA
611 my $hexcypher_suits = sprintf("%04s",DecToHex(length($hexcypher_vec)/2)).$hexcypher_vec;
612 my $hexcompression_vec = "00"; #CompressionMeth - Use none no need data minimal + this is a lite implementation
613 my $hexcompression = sprintf("%02s",DecToHex(length($hexcompression_vec)/2)).$hexcompression_vec;
614 my $hexssl_version = "0300";
615 my $hexhandshake_parts = $hexssl_version.$hexrandom.$hexsession.$hexcypher_suits.$hexcompression;
616 my $hexhello = handShake("01",$hexhandshake_parts);
617 my $clienthello = Bin($hexhello);
618 my $hexhellorecord = recordLayer("16",$hexhello);
619  
620 #######################################
621 #Send Client Hello Record
622 my $hellorecord = Bin($hexhellorecord); #Client Hello Record ready to send
623 Write($sock,$hellorecord);
624  
625 #######################################
626 # Listen for ServerHello
627 my $response=Read($sock);
628 my $hexserverhellorecord=Hex($response);
629 my $records="";
630 while (length($response) > 0) {
631 my $lenstr=substr($response,0,5,'');
632 my $len;
633 if ($lenstr =~ /^\x16\x03\x00(.)(.)/s ) { $len=ord($1)*256+ord($2); }
634 else { return { Errors => ErrWarn("Malformed SSL header from server while waiting for SSL ServerHello messages"), Warnings => \@warning }; }
635 $records.=substr($response,0,$len,'');
636 }
637 my $serverhello=$records;
638  
639 #######################################
640 # Decode ServerHandshake Messages
641 my %Hand = ParseRecords($records);
642  
643 # Get the host certificate - 1, Verify VOMS cert 2, key material for pre-master key exchange later
644 my $certcont = $Hand{11};
645 my $lcerts = substr($certcont,0,3,'');
646 my @HOSTcerts=();
647 while ( length($certcont)>3 && ($lcert=substr($certcont,0,3,''))) {
648 if ($lcert =~ /(.)(.)(.)/s ) { push @HOSTcerts, substr($certcont,0,(ord($1)*65536)+(ord($2)*256)+ord($3),''); }
649 }
650 return { Errors => ErrWarn("No cert returned from server"), Warnings => \@warning } unless (@HOSTcerts);
651  
652 # Build VOMS Server Chain Locally and check it's trusted
653 my %Chain = %{ buildchain( { trustedCAdirs => \@CAdirs, suppliedcerts => \@HOSTcerts } ) };
654 my @Trust = @{ $Chain{TrustedCA} };
655 my @Errors = @{ $Chain{Errors} };
656 my $EEC = $Chain{EndEntityCert};
657 ErrWarn(\@warning, "NO CRL Check implemented");
658 ErrWarn(\@warning, "NO Certificate Purpose Check implemented");
659 ErrWarn(\@warning, "NO CA signing policy check implemented");
660 for (my $i=0;$i < $#Errors;$i++ ) { if ( @{ $Errors[$i] } ) { ErrWarn(\@error,"Error verifying server's certificate chain (depth $i): ".join(", ",@{ $Errors[$i] })); } }
661 ErrWarn(\@error,"Server's Certificate is not trusted by client") unless ($Trust[-1]);
662 return { Errors => \@error, Warnings => \@warning } if (@error);
663  
664 # Extract Server Cert and Key details
665 my %ServerCertInfo= %{ VOMS::Lite::X509::Examine( $EEC, { SubjectDN=>"", IssuerDN=>"", Keymodulus=>"", KeypublicExponent=>"", subjectAltName=>"" }) };
666 my $ServerDN=$ServerCertInfo{'SubjectDN'};
667 my @SubjecyAltNames=@{ $ServerCertInfo{'subjectAltNameArray'} };
668 debug("Server DN",$ServerDN);
669 # Check server certificate matches ! Not matching against wildcards
670 if ($ServerDN !~ m#/CN=($Server)(/|$)#) {
671 my $match=0;
672 # Else Check Subject Alt Name matches
673 foreach (@SubjecyAltNames) { debug("AltName",$_); if ($_ eq "dNSName=$Server") {$match=1; ErrWarn(\@warning,"Using SubjectAltName to Match VOMS Server Certificate")} }
674 return { Errors => ErrWarn("Server Distinguished name mismatch expecting Certificate name containing CN=$Server got $ServerDN"), Warnings => \@warning }
675 if (!$match && $Server ne "localhost");
676 }
677  
678 # Get ServerHello bits and pieces
679 my $sHello = $Hand{2};
680 my $sHelloVer = substr($sHello,0,2,'');
681 my $sHelloTime = substr($sHello,0,4,'');
682 my $sHelloRand = substr($sHello,0,28,'');
683 my $sHelloIDlen = ord(substr($sHello,0,1,''));
684 my $sHelloSessionID = substr($sHello,0,$sHelloIDlen,'');
685 my $sHelloCypherSuite = substr($sHello,0,2,'');
686 my $sHelloCompressionMethod = substr($sHello,0,1,'');
687 debug("Session ID",$sHelloSessionID);
688  
689 # Get Certificate Request (request for authN)
690 my $sRequest=$Hand{13};
691 my $ReqTypesCount=ord(substr($sRequest,0,1,''));
692 my $RSAOK=0;
693 my @ReqTypes; for (my $a=0; $a<$ReqTypesCount; $a++) { push @ReqTypes,substr($sRequest,0,1,''); if ($ReqTypes[-1] eq "\x01") {$RSAOK=1;} }
694 my $ReqDNNamesLen=(ord(substr($sRequest,0,1,''))*256)+ord(substr($sRequest,0,1,''));
695 my $ReqDistinguishedNames=substr($sRequest,0,$ReqDNNamesLen,'');
696 my @ReqASN1DN;
697 while ( length($ReqDistinguishedNames) > 0 ) {
698 my $DNLen=(ord(substr($ReqDistinguishedNames,0,1,''))*256)+ord(substr($ReqDistinguishedNames,0,1,''));
699 push @ReqASN1DN,substr($ReqDistinguishedNames,0,$DNLen,'');
700 }
701  
702 # Get ServerHelloDone
703 my $sHelloDone=$Hand{14};
704  
705 # Check for RSA
706 if ($RSAOK==0) { return { Errors => ErrWarn("Server does not support RSA AuthN"), Warnings => \@warning }; }
707  
708 # 1, Check acceptable DNs for Certificates
709 my $GotCA=0;
710 foreach (@ReqASN1DN) {
711 my $X509subject=$_;
712 my @ASN1SubjectDNIndex=ASN1Index($X509subject);
713 shift @ASN1SubjectDNIndex;
714 my $SubjectDN="";
715 while (@ASN1SubjectDNIndex) {
716 my ($CLASS,$CONSTRUCTED,$TAG,$HEADSTART,$HEADLEN,$CHUNKLEN)=(0,0,0,0,0);
717 until ($TAG == 6 ) { ($CLASS,$CONSTRUCTED,$TAG,$HEADSTART,$HEADLEN,$CHUNKLEN) = @{shift @ASN1SubjectDNIndex}; }
718 my $OID=substr($X509subject,($HEADSTART+$HEADLEN),$CHUNKLEN);
719 ($CLASS,$CONSTRUCTED,$TAG,$HEADSTART,$HEADLEN,$CHUNKLEN) = @{shift @ASN1SubjectDNIndex};
720 my $Value=substr($X509subject,($HEADSTART+$HEADLEN),$CHUNKLEN);
721 $SubjectDN.="/".VOMS::Lite::CertKeyHelper::OIDtoDNattrib(ASN1OIDtoOID($OID))."=$Value";
722 }
723 if ($UserIDN eq $SubjectDN) { debug("MATCHED CA",$SubjectDN); $GotCA=1; }
724 else { debug(" CA:", $SubjectDN); }
725 }
726 if ( @ReqASN1DN == 0 ) { ErrWarn(\@warning, "VOMS server does not tell me what CAs are supported"); }
727 elsif ( $GotCA==0 ) { return { Errors => ErrWarn("VOMS server does not support your CA"), Warnings => \@warning }; }
728  
729 #########################################################
730 #Talk to the server again
731  
732 ##Construct Certificate Message Record
733 my $hexcertarray ="";
734 foreach my $cert (@chain) { $hexcertarray.=sprintf("%06s",DecToHex(length($cert))).Hex($cert);}
735 my $hexcertobj = sprintf("%06s",DecToHex(length($hexcertarray)/2)).$hexcertarray;
736 my $hexcertmesg = handShake("0b",$hexcertobj);
737 my $hexcertsmessagerecord=recordLayer("16",$hexcertmesg);
738 my $certmesg = pack("H*", $hexcertmesg);
739  
740 ##ClientKeyExchange
741 #PreMasterSecret
742 my $prernd='X' x 46; $prernd =~ s/./chr(int(rand 256))/ge;
743 my $hexpremastersecret='0300'.Hex($prernd);
744  
745 #Derive Key Material
746 my %KEYS=Keygen($hexpremastersecret,$hexrandom,Hex($sHelloTime.$sHelloRand));
747  
748 #Make Client Key Exchange
749 my $hexEncPMSecret = rsaencrypt($hexpremastersecret,Hex($ServerCertInfo{'KeypublicExponent'}),Hex($ServerCertInfo{'Keymodulus'}));
750 my $hexClientKeyExchange = handShake("10",$hexEncPMSecret); #### USE ME FOR CertificateVarify
751 my $hexClientKeyExchangeMessageRecord = recordLayer("16",$hexClientKeyExchange);
752 my $ClientKeyExchangeMessage = Bin($hexClientKeyExchange); #### ClientCertificate for handshakemessages needs to be without record layer
753  
754 #CertificateVerify
755 my $Hmsgs = $clienthello.$serverhello.$certmesg.$ClientKeyExchangeMessage;
756 my $verifymac = MAC($KEYS{'MS'},$Hmsgs);
757  
758 my $hexsignedcertificateverify = rsasign($verifymac,$Keyexp,$Keymod);
759 my $hexwrappedsignedcertificateverify = sprintf("%04s",DecToHex(length($hexsignedcertificateverify)/2)).$hexsignedcertificateverify;
760 my $hexcertificateverify = handShake('0f',$hexwrappedsignedcertificateverify);
761 my $certificateverify = Bin($hexcertificateverify);
762 my $hex_ssl_certificateverifyrecord = recordLayer("16",$hexcertificateverify);
763  
764 ##########################################################################
765 ## Switch to Encrypted Session -- change_cipher_spec message
766 #Select algorythm for key exchange -- Must be RSA
767 my $hexkeyselection="140300000101";
768  
769 # Switch to tripple des (the only one I support) and send finished message
770  
771 $Hmsgs.=$certificateverify;
772 my $unechexfinished=handShake("14",MAC($KEYS{'MS'},$Hmsgs."CLNT"));
773  
774 #Set up the Client and Server DES3-EDE sessions
775 my $Ccipher = Crypt::CBC->new( -literal_key => 1, -padding => 'null', -key => $KEYS{'CK'}, -iv => $KEYS{'CIV'}, -header => 'none', -cipher => 'DES_EDE3' );
776 my $Scipher = Crypt::CBC->new( -literal_key => 1, -padding => 'null', -key => $KEYS{'SK'}, -iv => $KEYS{'SIV'}, -header => 'none', -cipher => 'DES_EDE3' );
777 my $Cseq=0;
778 my $Sseq=0;
779  
780 my $hex_finishedrecord = &Encrypt(Bin(recordLayer("16",$unechexfinished)),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher);
781 my $hex_finished = $hex_finishedrecord;
782 $hex_finished =~ s/^..........//s;
783 my $finished = Bin($hex_finished);
784  
785 #############################################################################
786 #Send Records
787 Write($sock,Bin($hexcertsmessagerecord.$hexClientKeyExchangeMessageRecord.$hex_ssl_certificateverifyrecord.$hexkeyselection.$hex_finishedrecord));
788  
789 #############################################################################
790 #Receive Response
791 $response=Read($sock);
792 if ( $response =~ /^\x14\x03\x00\x00\x01\x01/ ) { $response =~ s/......//; } #Change Cypher Spec -- what we expect
793 else { return { Errors => ErrWarn("Error: Expecting SSL Change Cypher Spec Message, got something else."), Warnings => \@warning }; }
794 my $serverfinishedhex=Hex(&Decrypt($response,$KEYS{'SMAC'},$pad1sha,$pad2sha,$Sseq,$Scipher));
795  
796 # Check response from server is a valid finished message
797 $Hmsgs.=Bin($unechexfinished);
798 my $unencryptedfinishedmsg = handShake("14",MAC($KEYS{'MS'},$Hmsgs."SRVR"));
799 if ($unencryptedfinishedmsg ne $serverfinishedhex) { return { Errors => ErrWarn("Failed to decrypt Server Finished Message"), Warnings => \@warning }; }
800  
801 #########################
802 # Send no delegation byte
803 # predata and postdata to stop TLS CBC IV attack
804 my $predata = Bin(&Encrypt(Bin("1703000000"),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher));
805 my $msg='0';
806 my $emesg = &Encrypt(Bin(recordLayer("17",Hex($msg))),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher);
807 $senddata = Bin($emesg);
808 my $postdata = Bin(&Encrypt(Bin("1703000000"),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher));
809  
810 Write($sock,$predata.$senddata.$postdata);
811  
812 ##############
813 # Send request
814 #<xml version="1.0" encoding = "US-ASCII"?>
815 # <voms>
816 # <command>COMMAND</command>+
817 # <order>ORDER</order>?
818 # <targets>TARGETS</targets>?
819 # <lifetime>N</lifetime>?
820 # <base64>B</base64>?
821 # <version>V</version>?
822 # </voms>
823 # COMMAND: G/vo.name(/subgroup)* {All relevant} | Rrolename {All relevant} | B/vo.name(/subgroup)*:rolename | A {All} | M {List} | /vo.name(/subgroup)*/Role=rolename
824 # my $msg='<?xml version="1.0" encoding = "US-ASCII"?><voms><command>G/ngs.ac.uk/ops</command><base64>1</base64><version>4</version><lifetime>43200</lifetime></voms>';
825 # my $msg='<?xml version="1.0" encoding = "US-ASCII"?><voms><command>ROperations</command><base64>1</base64><version>4</version><lifetime>43200</lifetime></voms>';
826  
827 my $cmds = "";
828 foreach (@FQANs) {
829 s|/Capability=[^/]+||;
830 if ( m|^(.*?)/Role=([^/]+)$| ) {$cmds .= "<command>B$1:$2</command>";}
831 else { $cmds .= "<command>G$_</command>"; }
832 }
833  
834 $msg='<?xml version="1.0" encoding = "US-ASCII"?><voms>'.$cmds.'<base64>1</base64><version>4</version><lifetime>'.$lifetime.'</lifetime></voms>';
835 $emesg = &Encrypt(Bin(recordLayer("17",Hex($msg))),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher);
836 my $senddata2 = Bin($emesg);
837 Write($sock,$senddata2);
838  
839 ###############
840 # Read Response
841 $response=Read($sock);
842 if ( $response !~ /^\x17/ ) { return { Errors => ErrWarn("Expecting Encrypted Application Data, got something else"), Warnings => \@warning }; }
843 my $apdata=&Decrypt($response,$KEYS{'SMAC'},$pad1sha,$pad2sha,$Sseq,$Scipher);
844 my ($ac) = $apdata =~ /^.*<ac>([^<]*)<\/ac>.*$/;
845 $ac =~ s/[^a-zA-Z0-9_\+=\/\[\]-]//g;
846 $apdata =~ s|<error><item><number>[0-9]{4,}</number><message>([^<]*)</message></item></error>|ErrWarn(\@error,"Error from VOMS Server: \"$1\"")|ge;
847 $apdata =~ s|<error><item><number>[0-9]{1,3}</number><message>([^<]*)</message></item></error>|ErrWarn(\@warning,"Warning from VOMS Server: \"$1\"")|ge;
848 if ( @error > 0 ) { return { Errors => \@error, Warnings => \@warning }; }
849  
850 my $vomsac=Hex(VOMS::Lite::Base64::Decode($ac));
851 $vomsac=~ s/(..)/pack('C',hex($&))/ge;
852 close($sock);
853 return { AC=>encodeAC($vomsac), Warnings => \@warning };
854 }####Endof sub Get
855  
856  
857 sub List {
858 my %context=%{ $_[0]};
859 my @error; my @warning;
860 if ( $] < 5.004 ) { ErrWarn(\@warning, "Perl version is old; random seed is not good"); }
861  
862 if ( ! defined $context{'Server'} ) { ErrWarn(\@error, "Server not Specified"); }
863 if ( ! defined $context{'Port'} ) { ErrWarn(\@error, "Port not Specified"); }
864 if ( ! defined $context{'VO'} ) { ErrWarn(\@error, "VO not Specified"); }
865  
866 # IO::SOCKET::SSL may optionally use a cert and key on the file system, we too;
867 if ( ! defined $context{'Cert'} && ! defined $context{'CertFile'} ) { ErrWarn(\@error, "Certificate not Specified"); }
868 if ( ! defined $context{'Key'} && ! defined $context{'KeyFile'} ) { ErrWarn(\@error, "Key not Specified"); }
869 if ( ! defined $context{'Cert'} && defined $context{'CertFile'} && ! -r $context{'CertFile'} ) { ErrWarn(\@error, "Certificate file unreadable"); }
870 if ( ! defined $context{'Key'} && defined $context{'KeyFile'} && ! -r $context{'KeyFile'} ) { ErrWarn(\@error, "Key file unreadable"); }
871  
872 if ( @error > 0 ) { return { Errors => \@error, Warnings => \@warning }; }
873  
874 my $Server = (($context{'Server'} =~ /^([a-z0-9_.-]+)$/) ? $& : undef);
875 my $VO = (($context{'VO'} =~ /^([a-z0-9_.-]+)$/) ? $& : undef);
876 my $Port = (($context{'Port'} =~ /^([0-9]{1,5})$/ && $context{'Port'} < 65536) ? $& : 7512);
877  
878 # Barf if data is not good
879 if ( ! defined $Server ) { ErrWarn(\@error, "Bad VOMS server string"); }
880 if ( ! defined $VO ) { ErrWarn(\@error, "Bad VO string"); }
881 if ( ! defined $Port ) { ErrWarn(\@error, "Bad Port"); }
882  
883 my @certs; my $key;
884 if ( ref($context{'Cert'}) eq "ARRAY" ) { @certs = @{ $context{'Cert'} }; }
885 elsif ( defined($context{'Cert'}) and ref($context{'Cert'}) eq "" ) { @certs = ( $context{'Cert'} ); } #might consider a function to seperate concatenated DERs
886 elsif ( defined($context{'Cert'}) ) { ErrWarn(\@error, "Certs Argument was not a reference to an array nor a scalar"); }
887 else { @certs = ( readCert($context{'CertFile'}) );}
888 if ( ! @certs ) { ErrWarn(\@error, "Unable to get any user certs."); }
889 foreach my $i (0 .. $#certs) { if ( $certs[$i] !~ /^\x30/s ) { ErrWarn(\@error, "Supplied certificate (\@context{'Cert'}[$i]) $certs[$i] not in DER format"); } }
890  
891 if ( defined $context{'Key'} && $context{'Key'} !~ /^\x30/s ) { ErrWarn(\@error, "Supplied Key not in DER format"); }
892 if ( defined $context{'Key'} ) { $key=$context{'Key'}; }
893 else { $key=readPrivateKey($context{'KeyFile'}); }
894 if (! defined($key) ) { ErrWarn(\@error, "Unable to get user key."); }
895  
896 my @CAdirs;
897 if ( defined $context{'CAdirs'} ) {
898 if ( ref($context{'CAdirs'}) eq "ARRAY" ) { @CAdirs = @{ $context{'CAdirs'} }; }
899 elsif ( ref($context{'Cert'}) eq "" ) { @CAdirs = split(':',$context{'CAdirs'}); }
900 else { ErrWarn(\@error, "CAdirs Argument was not a reference to an array nor a scalar"); }
901 }
902  
903 foreach my $i (0 .. $#CAdirs) { if ( ! -d $CAdirs[$i] ) { ErrWarn(\@error, "Supplied CA directory (\@context{'CAdirs'}[$i]) is not a directory"); } }
904  
905 if ( @error > 0 ) { return { Errors => \@error, Warnings => \@warning }; }
906  
907 #Need CAdirs
908 #==========================================================
909 if ( ! @CAdirs and $ENV{X509_CERT_DIR} ) {
910 if ( -d $ENV{X509_CERT_DIR} and $ENV{X509_CERT_DIR} =~ /^(.*)$/) { push @CAdirs,$1; }
911 else { return { Errors => ErrWarn('X509_CERT_DIR defined but it is not a directory'), Warnings => \@warning }; }
912 }
913 elsif ( ! @CAdirs ) {
914 if ( -d $CAdir ) { push @CAdirs, $CAdir; ErrWarn(\@warning,"no CAdir specified Using $CAdir"); }
915 else { return { Errors => ErrWarn('No CAdir found'), Warnings => \@warning }; }
916 }
917  
918 # Get details from Cert and Key
919 my %certinfo = %{ VOMS::Lite::X509::Examine( $certs[0], { SubjectDN=>"", IssuerDN=>"" }) };
920 my %chain = %{ VOMS::Lite::CertKeyHelper::buildchain( { trustedCAdirs => \@CAdirs, suppliedcerts => \@certs } ) };
921 my @chain = @{ $chain{'Certs'} };
922 my $UserDN = $chain{'EndEntityDN'};
923 my $UserIDN = $chain{'EndEntityIssuerDN'};
924 my %keyinfo = %{ VOMS::Lite::KEY::Examine( $key, { Keymodulus=>"",KeyprivateExponent=>"" }) };
925 my $Keymod = Hex($keyinfo{'Keymodulus'});
926 my $Keyexp = Hex($keyinfo{'KeyprivateExponent'});
927 my $DN = $certinfo{'SubjectDN'};
928 my $IDN = $certinfo{'IssuerDN'};
929  
930 #Open a socket to the server
931 my $sock = new IO::Socket::INET( PeerAddr => $Server, PeerPort => $Port, Proto => 'tcp', Type => SOCK_STREAM);
932 if ( ! defined ($sock) ) { return { Errors => ErrWarn("Unable to establish a connection to $Server:$Port"), Warnings => \@warning }; }
933 $sock->autoflush(1);
934  
935 #######################################
936 #Construct Initial Components required for SSL
937 #Random
938 my $hextime = DecToHex(time);
939 my $time = Bin($hextime);
940 my $rnd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $rnd =~ s/./chr(int(rand 256))/ge;#not so good on Win32 32000 cycle reported
941 my $hexrnd = Hex($rnd);
942 my $hexrandom = $hextime.$hexrnd;
943 my $hexsession = "00"; #none - new session
944 my $hexcypher_vec = "000a"; #Ciphersuite TLS_RSA_WITH_3DES_EDE_CBC_SHA
945 my $hexcypher_suits = sprintf("%04s",DecToHex(length($hexcypher_vec)/2)).$hexcypher_vec;
946 my $hexcompression_vec = "00"; #CompressionMeth - Use none no need data minimal + this is a lite implementation
947 my $hexcompression = sprintf("%02s",DecToHex(length($hexcompression_vec)/2)).$hexcompression_vec;
948 my $hexssl_version = "0300";
949 my $hexhandshake_parts = $hexssl_version.$hexrandom.$hexsession.$hexcypher_suits.$hexcompression;
950 my $hexhello = handShake("01",$hexhandshake_parts);
951 my $clienthello = Bin($hexhello);
952 my $hexhellorecord = recordLayer("16",$hexhello);
953  
954 #######################################
955 #Send Client Hello Record
956 my $hellorecord = Bin($hexhellorecord); #Client Hello Record ready to send
957 Write($sock,$hellorecord);
958  
959 #######################################
960 # Listen for ServerHello
961 my $response=Read($sock);
962 my $hexserverhellorecord=Hex($response);
963 my $records="";
964 while (length($response) > 0) {
965 my $lenstr=substr($response,0,5,'');
966 my $len;
967 if ($lenstr =~ /^\x16\x03\x00(.)(.)/s ) { $len=ord($1)*256+ord($2); }
968 else { return { Errors => ErrWarn("Malformed SSL header from server while waiting for SSL ServerHello messages"), Warnings => \@warning }; }
969 $records.=substr($response,0,$len,'');
970 }
971 my $serverhello=$records;
972  
973 #######################################
974 # Decode ServerHandshake Messages
975 my %Hand = ParseRecords($records);
976  
977 # Get the host certificate - 1, Verify VOMS cert 2, key material for pre-master key exchange later
978 my $certcont = $Hand{11};
979 my $lcerts = substr($certcont,0,3,'');
980 my @HOSTcerts=();
981 while ( length($certcont)>3 && ($lcert=substr($certcont,0,3,''))) {
982 if ($lcert =~ /(.)(.)(.)/s ) { push @HOSTcerts, substr($certcont,0,(ord($1)*65536)+(ord($2)*256)+ord($3),''); }
983 }
984 return { Errors => ErrWarn("No cert returned from server"), Warnings => \@warning } unless (@HOSTcerts);
985  
986 # Build VOMS Server Chain Locally and check it's trusted
987 my %Chain = %{ buildchain( { trustedCAdirs => \@CAdirs, suppliedcerts => \@HOSTcerts } ) };
988 my @Trust = @{ $Chain{TrustedCA} };
989 my @Errors = @{ $Chain{Errors} };
990 my $EEC = $Chain{EndEntityCert};
991 ErrWarn(\@warning, "NO CRL Check implemented");
992 ErrWarn(\@warning, "NO Certificate Purpose Check implemented");
993 ErrWarn(\@warning, "NO CA signing policy check implemented");
994 for (my $i=0;$i < $#Errors;$i++ ) { if ( @{ $Errors[$i] } ) { ErrWarn(\@error,"Error verifying server's certificate chain (depth $i): ".join(", ",@{ $Errors[$i] })); } }
995 ErrWarn(\@error,"Server's Certificate is not trusted by client") unless ($Trust[-1]);
996 return { Errors => \@error, Warnings => \@warning } if (@error);
997  
998 # Extract Server Cert and Key details
999 my %ServerCertInfo= %{ VOMS::Lite::X509::Examine( $EEC, { SubjectDN=>"", IssuerDN=>"", Keymodulus=>"", KeypublicExponent=>"", subjectAltName=>"" }) };
1000 my $ServerDN=$ServerCertInfo{'SubjectDN'};
1001 my @SubjecyAltNames=@{ $ServerCertInfo{'subjectAltNameArray'} };
1002 debug("Server DN",$ServerDN);
1003 # Check server certificate matches ! Not matching against wildcards
1004 if ($ServerDN !~ m#/CN=($Server)(/|$)#) {
1005 my $match=0;
1006 # Else Check Subject Alt Name matches
1007 foreach (@SubjecyAltNames) { debug("AltName",$_); if ($_ eq "dNSName=$Server") {$match=1; ErrWarn(\@warning,"Using SubjectAltName to Match VOMS Server Certificate")} }
1008 return { Errors => ErrWarn("Server Distinguished name mismatch expecting Certificate name containing CN=$Server got $ServerDN"), Warnings => \@warning }
1009 if (!$match && $Server ne "localhost");
1010 }
1011  
1012 # Get ServerHello bits and pieces
1013 my $sHello = $Hand{2};
1014 my $sHelloVer = substr($sHello,0,2,'');
1015 my $sHelloTime = substr($sHello,0,4,'');
1016 my $sHelloRand = substr($sHello,0,28,'');
1017 my $sHelloIDlen = ord(substr($sHello,0,1,''));
1018 my $sHelloSessionID = substr($sHello,0,$sHelloIDlen,'');
1019 my $sHelloCypherSuite = substr($sHello,0,2,'');
1020 my $sHelloCompressionMethod = substr($sHello,0,1,'');
1021 debug("Session ID",$sHelloSessionID);
1022  
1023 # Get Certificate Request (request for authN)
1024 my $sRequest=$Hand{13};
1025 my $ReqTypesCount=ord(substr($sRequest,0,1,''));
1026 my $RSAOK=0;
1027 my @ReqTypes; for (my $a=0; $a<$ReqTypesCount; $a++) { push @ReqTypes,substr($sRequest,0,1,''); if ($ReqTypes[-1] eq "\x01") {$RSAOK=1;} }
1028 my $ReqDNNamesLen=(ord(substr($sRequest,0,1,''))*256)+ord(substr($sRequest,0,1,''));
1029 my $ReqDistinguishedNames=substr($sRequest,0,$ReqDNNamesLen,'');
1030 my @ReqASN1DN;
1031 while ( length($ReqDistinguishedNames) > 0 ) {
1032 my $DNLen=(ord(substr($ReqDistinguishedNames,0,1,''))*256)+ord(substr($ReqDistinguishedNames,0,1,''));
1033 push @ReqASN1DN,substr($ReqDistinguishedNames,0,$DNLen,'');
1034 }
1035  
1036 # Get ServerHelloDone
1037 my $sHelloDone=$Hand{14};
1038  
1039 # Check for RSA
1040 if ($RSAOK==0) { return { Errors => ErrWarn("Server does not support RSA AuthN"), Warnings => \@warning }; }
1041  
1042 # 1, Check acceptable DNs for Certificates
1043 my $GotCA=0;
1044 foreach (@ReqASN1DN) {
1045 my $X509subject=$_;
1046 my @ASN1SubjectDNIndex=ASN1Index($X509subject);
1047 shift @ASN1SubjectDNIndex;
1048 my $SubjectDN="";
1049 while (@ASN1SubjectDNIndex) {
1050 my ($CLASS,$CONSTRUCTED,$TAG,$HEADSTART,$HEADLEN,$CHUNKLEN)=(0,0,0,0,0);
1051 until ($TAG == 6 ) { ($CLASS,$CONSTRUCTED,$TAG,$HEADSTART,$HEADLEN,$CHUNKLEN) = @{shift @ASN1SubjectDNIndex}; }
1052 my $OID=substr($X509subject,($HEADSTART+$HEADLEN),$CHUNKLEN);
1053 ($CLASS,$CONSTRUCTED,$TAG,$HEADSTART,$HEADLEN,$CHUNKLEN) = @{shift @ASN1SubjectDNIndex};
1054 my $Value=substr($X509subject,($HEADSTART+$HEADLEN),$CHUNKLEN);
1055 $SubjectDN.="/".VOMS::Lite::CertKeyHelper::OIDtoDNattrib(ASN1OIDtoOID($OID))."=$Value";
1056 }
1057 if ($UserIDN eq $SubjectDN) { debug("MATCHED CA",$SubjectDN); $GotCA=1; }
1058 else { debug(" CA:", $SubjectDN); }
1059 }
1060 if ( @ReqASN1DN == 0 ) { ErrWarn(\@warning, "VOMS server does not tell me what CAs are supported"); }
1061 elsif ( $GotCA==0 ) { return { Errors => ErrWarn("VOMS server does not support your CA"), Warnings => \@warning }; }
1062  
1063 #########################################################
1064 #Talk to the server again
1065  
1066 ##Construct Certificate Message Record
1067 my $hexcertarray ="";
1068 foreach my $cert (@chain) { $hexcertarray.=sprintf("%06s",DecToHex(length($cert))).Hex($cert);}
1069 my $hexcertobj = sprintf("%06s",DecToHex(length($hexcertarray)/2)).$hexcertarray;
1070 my $hexcertmesg = handShake("0b",$hexcertobj);
1071 my $hexcertsmessagerecord=recordLayer("16",$hexcertmesg);
1072 my $certmesg = pack("H*", $hexcertmesg);
1073  
1074 ##ClientKeyExchange
1075 #PreMasterSecret
1076 my $prernd='X' x 46; $prernd =~ s/./chr(int(rand 256))/ge;
1077 my $hexpremastersecret='0300'.Hex($prernd);
1078  
1079 #Derive Key Material
1080 my %KEYS=Keygen($hexpremastersecret,$hexrandom,Hex($sHelloTime.$sHelloRand));
1081  
1082 #Make Client Key Exchange
1083 my $hexEncPMSecret = rsaencrypt($hexpremastersecret,Hex($ServerCertInfo{'KeypublicExponent'}),Hex($ServerCertInfo{'Keymodulus'}));
1084 my $hexClientKeyExchange = handShake("10",$hexEncPMSecret); #### USE ME FOR CertificateVarify
1085 my $hexClientKeyExchangeMessageRecord = recordLayer("16",$hexClientKeyExchange);
1086 my $ClientKeyExchangeMessage = Bin($hexClientKeyExchange); #### ClientCertificate for handshakemessages needs to be without record layer
1087  
1088 #CertificateVerify
1089 my $Hmsgs = $clienthello.$serverhello.$certmesg.$ClientKeyExchangeMessage;
1090 my $verifymac = MAC($KEYS{'MS'},$Hmsgs);
1091  
1092 my $hexsignedcertificateverify = rsasign($verifymac,$Keyexp,$Keymod);
1093 my $hexwrappedsignedcertificateverify = sprintf("%04s",DecToHex(length($hexsignedcertificateverify)/2)).$hexsignedcertificateverify;
1094 my $hexcertificateverify = handShake('0f',$hexwrappedsignedcertificateverify);
1095 my $certificateverify = Bin($hexcertificateverify);
1096 my $hex_ssl_certificateverifyrecord = recordLayer("16",$hexcertificateverify);
1097  
1098 ##########################################################################
1099 ## Switch to Encrypted Session -- change_cipher_spec message
1100 #Select algorythm for key exchange -- Must be RSA
1101 my $hexkeyselection="140300000101";
1102  
1103 # Switch to tripple des (the only one I support) and send finished message
1104  
1105 $Hmsgs.=$certificateverify;
1106 my $unechexfinished=handShake("14",MAC($KEYS{'MS'},$Hmsgs."CLNT"));
1107  
1108 #Set up the Client and Server DES3-EDE sessions
1109 my $Ccipher = Crypt::CBC->new( -literal_key => 1, -padding => 'null', -key => $KEYS{'CK'}, -iv => $KEYS{'CIV'}, -header => 'none', -cipher => 'DES_EDE3' );
1110 my $Scipher = Crypt::CBC->new( -literal_key => 1, -padding => 'null', -key => $KEYS{'SK'}, -iv => $KEYS{'SIV'}, -header => 'none', -cipher => 'DES_EDE3' );
1111 my $Cseq=0;
1112 my $Sseq=0;
1113  
1114 my $hex_finishedrecord = &Encrypt(Bin(recordLayer("16",$unechexfinished)),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher);
1115 my $hex_finished = $hex_finishedrecord;
1116 $hex_finished =~ s/^..........//s;
1117 my $finished = Bin($hex_finished);
1118  
1119 #############################################################################
1120 #Send Records
1121 Write($sock,Bin($hexcertsmessagerecord.$hexClientKeyExchangeMessageRecord.$hex_ssl_certificateverifyrecord.$hexkeyselection.$hex_finishedrecord));
1122  
1123 #############################################################################
1124 #Receive Response
1125 $response=Read($sock);
1126 if ( $response =~ /^\x14\x03\x00\x00\x01\x01/ ) { $response =~ s/......//; } #Change Cypher Spec -- what we expect
1127 else { return { Errors => ErrWarn("Error: Expecting SSL Change Cypher Spec Message, got something else."), Warnings => \@warning }; }
1128 my $serverfinishedhex=Hex(&Decrypt($response,$KEYS{'SMAC'},$pad1sha,$pad2sha,$Sseq,$Scipher));
1129  
1130 # Check response from server is a valid finished message
1131 $Hmsgs.=Bin($unechexfinished);
1132 my $unencryptedfinishedmsg = handShake("14",MAC($KEYS{'MS'},$Hmsgs."SRVR"));
1133 if ($unencryptedfinishedmsg ne $serverfinishedhex) { return { Errors => ErrWarn("Failed to decrypt Server Finished Message"), Warnings => \@warning }; }
1134  
1135 #########################
1136 # Send no delegation byte
1137 # predata and postdata to stop TLS CBC IV attack
1138 my $predata = Bin(&Encrypt(Bin("1703000000"),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher));
1139 my $msg='0';
1140 my $emesg = &Encrypt(Bin(recordLayer("17",Hex($msg))),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher);
1141 $senddata = Bin($emesg);
1142 my $postdata = Bin(&Encrypt(Bin("1703000000"),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher));
1143  
1144 Write($sock,$predata.$senddata.$postdata);
1145  
1146 ##############
1147 # Send request
1148 #<xml version="1.0" encoding = "US-ASCII"?>
1149 # <voms>
1150 # <command>COMMAND</command>+
1151 # <order>ORDER</order>?
1152 # <targets>TARGETS</targets>?
1153 # <lifetime>N</lifetime>?
1154 # <base64>B</base64>?
1155 # <version>V</version>?
1156 # </voms>
1157 # COMMAND: G/vo.name(/subgroup)* {All relevant} | Rrolename {All relevant} | B/vo.name(/subgroup)*:rolename | A {All} | M {List} | /vo.name(/subgroup)*/Role=rolename
1158 # my $msg='<?xml version="1.0" encoding = "US-ASCII"?><voms><command>G/ngs.ac.uk/ops</command><base64>1</base64><version>4</version><lifetime>43200</lifetime></voms>';
1159 # my $msg='<?xml version="1.0" encoding = "US-ASCII"?><voms><command>ROperations</command><base64>1</base64><version>4</version><lifetime>43200</lifetime></voms>';
1160  
1161 my $cmds = "<command>N</command>";
1162  
1163 # $msg='<?xml version="1.0" encoding = "US-ASCII"?><voms>'.$cmds.'<base64>1</base64><version>4</version><lifetime>'.$lifetime.'</lifetime></voms>';
1164 $msg='<?xml version="1.0" encoding = "US-ASCII"?><voms>'.$cmds.'</voms>';
1165 $emesg = &Encrypt(Bin(recordLayer("17",Hex($msg))),$KEYS{'CMAC'},$pad1sha,$pad2sha,$Cseq,$Ccipher);
1166 my $senddata2 = Bin($emesg);
1167 Write($sock,$senddata2);
1168  
1169 ###############
1170 # Read Response
1171 $response=Read($sock);
1172 if ( $response !~ /^\x17/ ) { return { Errors => ErrWarn("Expecting Encrypted Application Data, got something else"), Warnings => \@warning }; }
1173 my $apdata=&Decrypt($response,$KEYS{'SMAC'},$pad1sha,$pad2sha,$Sseq,$Scipher);
1174 my ($bitstr) = $apdata =~ /^.*<bitstr>([^<]*)<\/bitstr>.*$/;
1175 $bitstr =~ s/[^a-zA-Z0-9_\+=\/\[\]-]//g;
1176 $apdata =~ s|<error><item><number>[0-9]{4,}</number><message>([^<]*)</message></item></error>|ErrWarn(\@error,"Error from VOMS Server: \"$1\"")|ge;
1177 $apdata =~ s|<error><item><number>[0-9]{1,3}</number><message>([^<]*)</message></item></error>|ErrWarn(\@warning,"Warning from VOMS Server: \"$1\"")|ge;
1178 if ( @error > 0 ) { return { Errors => \@error, Warnings => \@warning }; }
1179  
1180 my $details=VOMS::Lite::Base64::Decode($bitstr,"VOMS");
1181 close($sock);
1182  
1183 my @FQANs = grep { /^\// } split(/\n/s,$details);
1184 my @details = grep { /^\/$VO/ } @FQANs;
1185 my @others = grep { ! /^\/$VO/ } @FQANs;
1186 if (@others) { my ($badvo) = $others[0] =~ m|^/([^/]+)|; push @warning => "The server seems to support a different VO: $badvo"; }
1187 for (my $i=0;$i<@details;$i++) {
1188 $details[$i] =~ s/\/(?:Capability=NULL|Role=NULL)$//;
1189 $details[$i] =~ s/\/(?:Capability=NULL|Role=NULL)$//;
1190 }
1191  
1192 return { FQANs=>\@details, Warnings => \@warning };
1193 }####Endof sub List
1194  
1195 ######################################################################
1196 sub Encrypt { #this routine modifies $_[4,5] Encrypt($rec,$MACSecret,$pad1sha,$pad2sha,$seq,$cipher)
1197 my ($rec,$MACSecret,$pad1sha,$pad2sha)=@_;
1198 debug("Encrypting",length($rec)." Bytes"); debug("MAC Secret",$MACSecret); debug("Sequence",$_[4]);
1199 my $type=substr($rec,0,1,''); # First Byte is the Record Type
1200 my $version=substr($rec,0,2,''); # Next 2 bytes are SSL Version
1201 my $len=substr($rec,0,2,''); # Length of the unencrypted Record
1202 my $seq=Bin(Seq($_[4]++)); #update this out of scope
1203 my $mac=sha1($MACSecret.$pad2sha.sha1($MACSecret.$pad1sha.$seq.$type.$len.$rec));
1204 my $data=$rec.$mac;
1205 #enc
1206 my $padnum=7-(length($data)%8); ###Argh I hate padding: SSL should cope with 080808080808080808 (== 00)
1207 # my $padnum=8-((length($data)+1)%8); # How much padding is required to bring data up to blocksize
1208 my $pad=chr($padnum) x ($padnum+1) ; # paddingValue x number . paddingNumber 0101, 020202, 03030303, ...
1209 debug("IV",$_[5]->get_initialization_vector(),1); debug("MAC",$mac,1); debug("Data",$rec); debug("Padding",$pad,1);
1210 my $edata=$_[5]->encrypt($data.$pad); # Encrypt data
1211 debug("Encrypted data",$edata,1);
1212 $_[5]->set_initialization_vector(substr($edata,-8,8)); #make ready for next enc.
1213 return recordLayer(Hex($type),Hex($edata));
1214 }
1215  
1216  
1217 ######################################################################
1218 sub Decrypt { #this routine modifies $_[4],[5] Decrypt($rec,$MACSecret,$pad1sha,$pad2sha,$seq,$cipher)
1219 my ($rec,$MACSecret,$pad1sha,$pad2sha)=@_;
1220 #unpack
1221 debug("Decrypting",length($rec)." bytes"); debug("Encrypted data",$rec,1); debug("MAC Secret",$MACSecret,1); debug("Sequence",$_[4]);
1222  
1223 my $data="";
1224  
1225 #Loop over all Records in $rec Allow for openssl's defence against TLS CBC IV attack
1226 while ($rec) {
1227 my $type=substr($rec,0,1,''); my $version=substr($rec,0,2,''); my $recordlength=substr($rec,0,2,'');
1228 debug("Message type",$type); debug("version",$version); debug("record length",$recordlength);
1229 my @rl = $recordlength =~ /(.)(.)/; my $rl=ord($rl[0])*256+ord($rl[1]);
1230 debug("RL Decimal",$rl);
1231 my $minirec=substr($rec,0,$rl,'');
1232 #decrypt
1233 my $minidata=$_[5]->decrypt($minirec);
1234 #Update
1235 my $iv=substr($minirec,-8,8);
1236 $_[5]->set_initialization_vector($iv);
1237 #unpad -- ought to be this but have seen examples otherwise...
1238 #... 0707070707070707, 06060606060606, 050505050505, 0404040404, 03030303, 020202, 0101 -- SSL
1239 # 01, 0202, 030303,... -- (PKCS#5, rfc2898)
1240 # openssl has option for random padding / no padding - have seen VOMS server use both :-S
1241 # spec says we can have up to 255 bytes of padding if these are random we'd have to assume padding is always present
1242 # our hands are tied because these are not selfconsistant -- so:
1243 # If padlen byte is 0x01 - 0x08 treat as random/SSL padding, otherwise assume SSL padding and rely upon xml message always ending in '>' i.e. 0x3e and not 0x01-0x08
1244 my $padchar=substr($minidata,-1,1,'');
1245 my $padlen=ord($padchar);
1246 my $pad;
1247 if ( ( $padlen <= 8 && $padlen > 0 ) or ( $padlen > 8 && $minidata =~ /${padchar}{$padlen}$/s ) ) {
1248 $pad=substr($minidata,(0-$padlen),$padlen,'');
1249 debug("Depadded","$padlen (+1) bytes"); debug("Padding",$pad,1);
1250 }
1251 else { $minidata.=$padchar; }
1252 #get mac
1253 my $mac=substr($minidata,-20,20,'');
1254 #verify
1255 my $len=Bin(sprintf("%04s",DecToHex(length($minidata))));
1256 my $seq=Bin(Seq($_[4]++));
1257 my $calcmac=sha1($MACSecret.$pad2sha.sha1($MACSecret.$pad1sha.$seq.$type.$len.$minidata));
1258 debug("IV",$iv); debug("MAC expected",$mac,1); debug("MAC derived",$calcmac,1); debug("Data",$minidata);
1259 $data.=$minidata;
1260 }
1261 return ($calcmac eq $mac)?$data:undef;
1262 }
1263  
1264  
1265 1;
1266  
1267 __END__