#!/usr/bin/perl
#
# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
# Yokogawa Electric Corporation.
# All rights reserved.
# 
# Redistribution and use of this software in source and binary
# forms, with or without modification, are permitted provided that
# the following conditions and disclaimer are agreed and accepted
# by the user:
# 
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with
#    the distribution.
# 
# 3. Neither the names of the copyrighters, the name of the project
#    which is related to this software (hereinafter referred to as
#    "project") nor the names of the contributors may be used to
#    endorse or promote products derived from this software without
#    specific prior written permission.
# 
# 4. No merchantable use may be permitted without prior written
#    notification to the copyrighters.
# 
# 5. The copyrighters, the project and the contributors may prohibit
#    the use of this software at any time.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHTERS, THE PROJECT AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING
# BUT NOT LIMITED THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.  IN NO EVENT SHALL THE
# COPYRIGHTERS, THE PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# $Id: IKEv2-SGW-I-1-1-10-1-A.seq,v 1.4 2008/11/28 10:16:24 doo Exp $
#
################################################################

BEGIN
{
	push(@INC, '..');
}

END {}

use IKEv2;
use strict;



my $remote	= 'common_remote_index';
my $selector	= 'common_selector_index_outbound';



my $session	= undef;
my $ret	= undef;
my $str = undef;
my $ike_sa_init_req_param	= undef;
my $ike_sa_init_resp_param	= undef;
my $ike_auth_req_param	= undef;
my $ike_auth_resp_param	= undef;
my $dh	= undef;
my $material	= undef;
my $child_sa_material = undef;


kLogHTML('<FONT COLOR="#FF0000" SIZE="+1"><U><B>TEST SETUP</B></U></FONT>');

my $tn = 'SGW';
my $nut = 'SGW';


#------------------------------#
# register IKEv2.pm            #
#------------------------------#
unless(IKEv2initialize($tn, $nut)) {
	IKEv2exitFatal('<FONT COLOR="#ff0000">IKEv2 module initializing failure</FONT>');
}



#---------------------------------#
# switch Support or Not Support   #
#---------------------------------#
unless ($config_pl->{'advanced_support_cert'}) {
       IKEv2exitNS('Not support ' . "'advanced_support_cert'");
}



#------------------------------#
# configure TN                 #
#------------------------------#
unless(IKEv2setupTN()) {
	IKEv2exitFatal('<FONT COLOR="#ff0000">TN setup failure</FONT>');
}



#------------------------------#
# configure NUT                #
#------------------------------#
unless(IKEv2setupNUT()) {
	IKEv2exitFatal('<FONT COLOR="#ff0000">NUT setup failure</FONT>');
}



kLogHTML('<FONT COLOR="#FF0000" SIZE="+1"><U><B>TEST PROCEDURE</B></U></FONT>');


#------------------------------#
# prepare session handler      #
#------------------------------#
$session = IKEv2create_session($remote);
unless(defined($session)) {
	IKEv2exitFatal('<FONT COLOR="#ff0000">IKEv2 session creation failure</FONT>');
}



$str  = '<PRE>';
$str .= "    (I)             (R)\n";
$str .= "    NUT             TN1\n";
$str .= "     |               |\n";
$str .= "     |-------------->| IKE_SA_INIT request (HDR, SAi1, KEi, Ni)\n";
$str .= "     |               |\n";
$str .= "     V               V";
$str .= '</PRE>';

kLogHTML($str);



#--------------------------------------#
# invoke IKE_SA_INIT request           #
#--------------------------------------#
unless(IKEv2initiateNUT($selector)) {
	IKEv2exitFatal('<FONT COLOR="#ff0000">NUT initiation failure</FONT>');
}



#--------------------------------------#
# receive IKE_SA_INIT request          #
#--------------------------------------#
$ike_sa_init_req_param = devel_IKEv2receive_IKE_SA_INIT_request($session, $remote);
unless(defined($ike_sa_init_req_param)) {
	kLogHTML(kDump_Common_Error());
	kLogHTML('<FONT COLOR="#ff0000">Can\'t observe IKE_SA_INIT request.</FONT>');
	IKEv2exitFail();
}



$str  = '<PRE>';
$str .= "    (I)             (R)\n";
$str .= "    NUT             TN1\n";
$str .= "     |               |\n";
$str .= "     |<--------------| IKE_SA_INIT response (HDR, SAr1, KEr, Nr, CERTREQ)\n";
$str .= "     |               |\n";
$str .= "     V               V";
$str .= '</PRE>';

kLogHTML($str);



#--------------------------------------#
# prepare IKE_SA_INIT response         #
#--------------------------------------#
my $certreq_payload = {
	'self'		=> 'CERTREQ',	# *** MUST BE HERE ***
	'nexttype'	=> undef,	# Next Payload
	'critical'	=> undef,	# Critical
	'reserved'	=> undef,	# RESERVED
	'length'	=> undef,	# Payload Length
	'cert_encoding'	=> 'X.509 Certificate - Signature',
	#'cert_authority'=> '',
	'cert_authority'=> undef,
};
my $common_ike_sa_init_resp = $gen_ike_sa_init_resp->{'common_remote_index'};
my @local_ike_sa_init_resp = @{$common_ike_sa_init_resp};
push(@local_ike_sa_init_resp, $certreq_payload);

my $index = 'sending_cert.1';
$gen_ike_sa_init_resp->{$index} = \@local_ike_sa_init_resp;


#--------------------------------------#
# send IKE_SA_INIT response            #
#--------------------------------------#
$ike_sa_init_resp_param = devel_IKEv2send_IKE_SA_INIT_response($session,
							       $index,
#							       $remote,
							       $ike_sa_init_req_param);
unless(defined($ike_sa_init_resp_param)) {
	kLogHTML(kDump_Common_Error());
	IKEv2exitFatal('<FONT COLOR="#ff0000">Can\'t send IKE_SA_INIT response.</FONT>');
}



#--------------------------------------#
# generate keying material             #
#--------------------------------------#
$material = devel_IKEv2gen_keymat(0, $ike_sa_init_req_param, $ike_sa_init_resp_param);
unless(defined($material)) {
	kLogHTML(kDump_Common_Error());
	IKEv2exitFatal('<FONT COLOR="#ff0000">Can\'t generate keying material.</FONT>');
}



#--------------------------------------#
# prepare IKE_AUTH request             #
#--------------------------------------#
my $cert_data = der2hexstr('./cert/NUTcert.der');
my $cert_payload =
{       # Certificate Payload
	'self'		=> 'CERT',	# *** MUST BE HERE ***
	'nexttype'	=> undef,	# Next Payload
	'critical'	=> '0',		# Critical
	'reserved'	=> '0',		# RESERVED
	'length'	=> 5 + length($cert_data) / 2,	# Payload Length #852
	'cert_encoding'	=> 'X.509 Certificate - Signature',
	'cert_data'	=> $cert_data,
};
my $common_ike_auth_req = $exp_ike_auth_req->{'common_remote_index'};
my @local_ike_auth_req = @{$common_ike_auth_req};
foreach my $payload1 (@local_ike_auth_req) {
	if ($payload1->{'self'} eq 'E') {
		# insert CERT and modify AUTH
		for (my $i = 0; $i < scalar(@{$payload1->{'innerPayloads'}}); $i++) {
			my $inner = ${$payload1->{'innerPayloads'}}[$i];

			if ($inner->{'self'} eq 'IDi') {
				splice(@{$payload1->{'innerPayloads'}}, $i+1, 0, $cert_payload);
			}
			if ($inner->{'self'} eq 'AUTH') {
				$inner->{'method'} = 'RSA_DS';
			}
		}

		#set correct nexttype
		$payload1->{'innerType'} = @{$payload1->{'innerPayloads'}}[0]->{'self'};
		for (my $i = 0; $i < scalar(@{$payload1->{'innerPayloads'}}); $i++) {
			my $inner = ${$payload1->{'innerPayloads'}}[$i];
			my $next = ${$payload1->{'innerPayloads'}}[$i+1];
			if (defined($next)) {
				$inner->{'nexttype'} = $next->{'self'};
			}
			else {
				$inner->{'nexttype'} = '0';
			}
		}
	}
}
$index = 'sending_cert.2';
$exp_ike_auth_req->{$index} = \@local_ike_auth_req;


#--------------------------------------#
# receive IKE_AUTH request             #
#--------------------------------------#
$str  = '<PRE>';
$str .= "    (I)             (R)\n";
$str .= "    NUT             TN1\n";
$str .= "     |               |\n";
$str .= "     |-------------->| IKE_AUTH request (HDR, SK {IDi, CERT, AUTH, SAi2, TSi, TSr})\n";
$str .= "     |               |\n";
$str .= "     V               V";
$str .= '</PRE>';

kLogHTML($str);



$ike_auth_req_param = devel_IKEv2receive_IKE_AUTH_request($session,
							  $index,
							  $ike_sa_init_req_param,
							  $ike_sa_init_resp_param,
							  $material);
unless(defined($ike_auth_req_param)) {
	kLogHTML(kDump_Common_Error());
	kLogHTML('<FONT COLOR="#ff0000">Can\'t observe IKE_AUTH request.</FONT>');
	IKEv2exitFail();
}



#--------------------------------------#
# exit with cleanup                    #
#--------------------------------------#
IKEv2exitPass();



#
# perldoc
#
########################################################################
__END__

=head1 Title

  Test IKEv2.SGW.I.1.1.10.1: Sending CERT Payload
  Part A: (ADVANCED)

=head1 Purpose
    
  To verify an IKEv2 device handles CERTREQ payload and transmits CERT payload properly.

=head1 References

  * [RFC 4306] - Sections 1.2 and 3.8

=head1 Test Setup

  * Network Topology
      Connect the devices according to the Common Topology.
  * Configuration
      In each part, configure the devices according to the following IKE peer configuration.

=begin html 

<BLOCKQUOTE>
<TABLE BORDER>
<TR>
<TD></TD>
<TD>Authentication Method</TD>
</TR>
<TR>
<TD>Remote</TD>
<TD>X.509 Certificate - Signature</TD>  
</TR>
</TABLE>
</BLOCKQUOTE>
<br>

=end html

  * Pre-Sequence and Cleanup Sequence
      IKEv2 on the NUT is disabled after each part.

=head1 Procedure

=begin html

<BLOCKQUOTE>
<PRE>
  
   NUT                  TN1
  (SGW)                (SGW)
    |                    |
    |------------------->| IKE_SA_INIT request (HDR, SAi1, KEi, Ni)
    |                    | (Judgement #1)
    |<-------------------| IKE_SA_INIT Response (HDR, SAr1, KEr, Nr, CERTREQ)
    |                    | (Packet #1)
    |                    |
    |------------------->| IKE_AUTH request (HDR, SK {IDi, CERT, AUTH, SAi2, TSi, TSr})
    |                    | (Judgement #2)
    |                    |
    V                    V
<br>
</PRE>
</BLOCKQUOTE>

<BLOCKQUOTE>
<TABLE BORDER>
<TR>
<TD><TT>Packet #1</TT></TD>
<TD><TT>See below</TT></TD>
</TR>
</TABLE>
</BLOCKQUOTE>

<br>
<BLOCKQUOTE>
Packet #1: IKE_SA_INIT response
<TABLE BORDER>
<TR>
<TD>IPv6 Header</TD>
<TD colspan="2">Same as the Common Packet #2</TD>
</TR>
<TR>
<TD>UDP Header</TD>
<TD colspan="2">Same as the Common Packet #2</TD>
</TR>
<TR>
<TD>IKEv2 Header</TD>
<TD colspan="2">Same as the Common Packet #2</TD>
</TR>
<TR>
<TD>SA Payload</TD>
<TD colspan="2">Same as the Common Packet #2</TD>
</TR>
<TR>
<TD>KE Payload</TD>
<TD colspan="2">Same as the Common Packet #2</TD>
</TR>
<TR>
<TD rowspan="2">Nr Payload</TD>
<TD>Next Payload</TD>
<TD>38 (CERTREQ)</TD>
</TR>
<TR>
<TD colspan="2">Other fields are same as the Common Packet #2</TD>
</TR>
<TR>
<TD>CERTREQ Payload</TD>
<TD colspan="2">See below</TD>
</TR>
</TABLE>
</BLOCKQUOTE>
<br>

<BLOCKQUOTE>
<TABLE BORDER>
<TR>
<TD rowspan="6">CERTREQ Payload</TD>
<TD>Next Payload</TD>
<TD>0</TD>
</TR>
<TR>
<TD>Critical</TD>
<TD>0</TD>
</TR>
<TR>
<TD>Reserved</TD>
<TD>0</TD>
</TR>
<TR>
<TD>Payload Length</TD>
<TD>Any</TD>
</TR>
<TR>
<TD>Certificate Encoding</TD>
<TD>4 (X.509 Certificate - Signature)</TD>
</TR>
<TR>
<TD>Certificate Authority</TD>
<TD>Any</TD>
</TR>
</TABLE>
</BLOCKQUOTE>

=end html

  Part A: (ADVANCED)
     1. NUT starts to negotiate with TN1 by sending IKE_SA_INIT request.
     2. Observe the messages transmitted on Link A.
     3. After reception of IKE_SA_INIT request from the NUT, TN1 responds with an
         IKE_SA_INIT response with a CERTREQ payload to the NUT.
     4. Observe the messages transmitted on Link A.

=head1 Observable Result
    
  Part A
       Step 2: Judgment #1
       The NUT transmits an IKE_SA_INIT request including "ENCR_3DES",
       "PRF_HMAC_SHA1", "AUTH_HMAC_SHA1_96" and "D-H group 2" as proposed
       algorithms.

       Step 4: Judgment #2
       The NUT transmits an IKE_AUTH request with a CERT payload which contains 4 (X.509
       Certificate - Signature) as Certificate Encoding and the NUT's certificate as Certificate Data.

=head1 Possible Problems

  * None.

=cut 


