// ***************************************************************************
// @copyright   Copyright Notification
//   No part may be reproduced except as authorized by written permission.
//   The copyright and the foregoing restriction extend to reproduction in all media.
//   Trademark 2010, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC).
//   All rights reserved.
// @version: IWD_10wk37
// * $Date: 2010-09-13 18:44:47 +0200 (Mon, 13 Sep 2010) $
// * $Rev: 3862 $
// ***************************************************************************

module NAS_Security {

  import from EUTRA_RRC_ASN1_Definitions language "ASN.1:1997" all;
  import from EUTRA_Component all;
  import from Parameters all;
  import from CommonDefs all;
  import from EUTRA_CommonDefs all;
  import from EUTRA_RRC_Templates all;
  import from EUTRA_SRB_Templates all;
  import from EUTRA_AspCommon_Templates all;
  import from EUTRA_SecurityFunctions all;
  import from EUTRA_SecuritySteps all;
  import from EUTRA_CommonProcedures all;
  import from NAS_CommonTypeDefs all;
  import from EPS_NAS_TypeDefs all;
  import from EPS_NAS_Constants all;
  import from EPS_NAS_Templates all;
  import from NAS_CommonTemplates all;
  import from EPS_NAS_MsgContainers all;
  import from EUTRA_NASSteps all;
  import from EUTRA_ConfigurationSteps all;
  import from UpperTesterFunctions all;
  import from NAS_AuxiliaryDefsAndFunctions all;
  import from EUTRA_AuxiliaryFunctions all;
  import from EUTRA_Timing all;
  
  
  group AlgorithmConstants {
  
  const B3_Type tsc_EPS_Integerity_Snow3G := '001'B;            /* @status    APPROVED */
  const B3_Type tsc_EPS_Integerity_AES := '010'B;               /* @status    APPROVED */
  const B3_Type tsc_EPS_Encryption_Snow3G := '001'B;            /* @status    APPROVED */
  const B3_Type tsc_EPS_Encryption_AES := '010'B;               /* @status    APPROVED */
  
  } //group AlgorithmConstants
  
  group LocalFunction9_4 {

  /*
   * @desc      step 1..12 of test cases 9.4.*
   * @param     p_NAS_IntegrityProtAlgorithm
   * @status    APPROVED
   */
  function fl_TC_9_4_Integrity (B3_Type p_NAS_IntegrityProtAlgorithm) runs on EUTRA_PTC
  {
    timer t_WaitTimer := f_EUTRA_SetTimerToleranceMin(eutra_CellA, 5.0) ; //5 seconds timer acc. to the test case prose
    // Initialise the integrity algorithm to test
    f_EUTRA_NAS_IntegrityAlgorithm_Set (p_NAS_IntegrityProtAlgorithm);
    //steps 1 to 10
    fl_TC_9_4_Steps1To10();
    
    //+   The SS Transmits an IDENTITY REQUEST message [Not integrity protected] <- IDENTITY REQUEST
    //@siclog "Step 11" siclog@
    SRB.send(cas_SRB2_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection,
                                                cs_IDENTITY_REQUEST(tsc_IdType_IMEI))));
    //+   Check: Does the UE transmit an IDENTIY RESPONSE message
    //+   in 5 seonds ? -> IDENTITY RESPONSE [2,F]
    //@siclog "Step 12" siclog@
    t_WaitTimer.start;
    alt {
      []SRB.receive(car_SRB2_NasPdu_IND(eutra_CellA,
                                        cr_NAS_Indication(?,
                                                          cr_IDENTITY_RESPONSE(f_Imei2MobileIdentity(px_IMEI_Def)))))
        {
          t_WaitTimer.stop;
          f_EUTRA_SetVerdictFailOrInconc (__FILE__, __LINE__, "Step 12: UE is responding to non integrity protected SMC");
        }
      [] t_WaitTimer.timeout {}
    };
    
  }; //function fl_TC_9_4_Integrity
  
  /*
   * @desc      step 1..10 of test cases 9.4.*
   * @status    APPROVED
   */
  function fl_TC_9_4_Steps1To10() runs on EUTRA_PTC
  {
    var HalfOctet_Type v_EpsBearerId := tsc_EpsDefaultBearerId;
    var ProcedureTransactionIdentifier v_EpsPti := tsc_PTI_1;
    var GutiParameters_Type v_GutiParams := f_EUTRA_CellInfo_GetGuti(eutra_CellA);   // get all data which are required for a GUTI
    var NAS_MSG_Indication_Type v_NasInd;                                            // temporary variable which is used when receiving NAS ASPs
    // initialize security parameters
    var NasCount_Type v_NasCountUL;
    var EUTRA_SecurityParams_Type v_SecurityParams := f_EUTRA_Security_Get();
    //v_AdditionalUpdateType is defined to follow TTCN3 v411 standard
    var template AdditionalUpdateType v_AdditionalUpdateType := f_GetAdditionalUpdateType (); // @sic R5-103681 sic@
    var NAS_AttDetValue_Type v_AttachType := f_GetEAttachType(); //used to follow TTCN3 v411 standard
    var template (omit) AccessPointName v_APN := omit;
    var template (omit) ProtocolConfigOptions v_Pco := omit;
  
    //+   The UE is switched on.
    //@siclog "Step 1" siclog@
    f_UT_SwitchOnUE(UT, false); /* no USIM insertion */
    
    //+   The UE transmits an ATTACH REQUEST message --> ATTACH REQUEST
    //@siclog "Step 2" siclog@
    v_NasInd := f_EUTRA_RRC_ConnEst_DefWithNas(eutra_CellA,
                                               tsc_RRC_TI_Def,
                                               cr_EstablishmentCause_Any,
                                               cr_NAS_IndicationWithPiggybacking(tsc_SHT_IntegrityProtected,
                                                                                 cr_508_ATTACH_REQUEST(v_AttachType, v_AdditionalUpdateType), // @sic R5-103681 sic@
                                                                                 cr_508_PDN_CONNECTIVITY_REQUEST(tsc_PdnRequest_InitialAttach,
                                                                                                                 f_GetPdnType())));
    v_EpsPti := v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST.procedureTransactionIdentifier; // Use this value in SS responses
    if (ispresent( v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST.protocolConfigurationOptions)) { // @sic R5s100084 sic@
      v_Pco := v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST.protocolConfigurationOptions;
    }
    //+   The SS transmits an AUTHENTICATION REQUEST message to initiate
    //+   the EPS authentication and AKA procedure. <-- AUTHENTICATION
    //+   REQUEST
    //+   The UE transmits an AUTHENTICATION RESPONSE message and
    //+   establishes mutual authentication. --> AUTHENTICATION RESPONSE
    //@siclog "Steps 3 - 4" siclog@
    v_SecurityParams := f_EUTRA_NAS_Authentication(eutra_CellA, tsc_SRB1,
                                                   v_SecurityParams,
                                                   tsc_SHT_IntegrityProtected_Ciphered, //  @sic R5-102226 sic@,
                                                   tsc_SHT_IntegrityProtected_Ciphered, //  @sic R5-102226 sic@,
                                                   f_Asn2Nas_PlmnId(v_GutiParams.PLMN_Identity));
    
    //+   The SS transmits a SECURITY MODE COMMAND message to activate NAS
    //+   security. It is integrity protected and includes request to
    //+   include IMEISV <-- SECURITY MODE COMMAND
    //+   Check: Does the UE transmit a SECURITY MODE COMPLETE message and
    //+   does it establish the initial security configuration? -->
    //+   SECURITY MODE COMPLETE [1,P]
    //@siclog "Steps 5 - 6" siclog@
    v_NasCountUL := f_EUTRA_NAS_ActivateSecurity(eutra_CellA, v_SecurityParams);
    f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 6");
    
    //@siclog "Steps 6a1 - 6a2" siclog@
    if (f_CheckEsmInfoTransferFlag(v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST)) {
      v_APN := f_ESM_InformationTransfer_GetAPN (eutra_CellA, v_EpsPti);
    }
    
    v_SecurityParams := f_EUTRA_RRC_ActivateSecurity(eutra_CellA,
                                                     v_SecurityParams,
                                                     v_NasCountUL);
    f_EUTRA_Security_Set(v_SecurityParams);

    //+   The SS transmits an ATTACH ACCEPT message.  <-- ATTACH ACCEPT
    //@siclog "Step 7" siclog@
    f_EUTRA_RRCConnectionReconfigurationWithAttachAcceptAllParams(eutra_CellA,
                                                                  v_EpsBearerId,
                                                                  tsc_RRC_TI_Def,
                                                                  v_EpsPti,
                                                                  tsc_EAttachType_EpsOnly,
                                                                  f_GetPDNAddress (f_CheckPCOforIPallocationViaNas (v_Pco)),
                                                                  f_GutiParameters2MobileIdentity(tsc_IEI_Guti, v_GutiParams),
                                                                  cs_TrackingAreaIdListDef_lv,
                                                                  omit,
                                                                  omit,
                                                                  omit,
                                                                  v_APN,
                                                                  f_GetDefPCOforPCSCFAddress (v_Pco), // @sic R5-104703 sic@
                                                                  v_NasInd.Pdu.Msg.aTTACH_REQUEST.addUpdateType); // @sic R5-103681 sic@
    
    //+   The UE transmits an ATTACH COMPLETE message --> ATTACH COMPLETE
    //@siclog "Step 8" siclog@
    f_EUTRA_NAS_AttachComplete(eutra_CellA, v_EpsBearerId);

    //+   The SS Transmits an IDENTITY REQUEST message [Security
    //+   protected] <- IDENTITY REQUEST
    //@siclog "Step 9" siclog@
    SRB.send(cas_SRB2_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_IntegrityProtected_Ciphered,
                                                cs_IDENTITY_REQUEST(tsc_IdType_IMSI))));
    //+   Check: Does the UE transmit an IDENTIY RESPONSE message
    //+   [Security Protected]? -> IDENTITY RESPONSE [1,P]
    //@siclog "Step 10" siclog@
    SRB.receive(car_SRB2_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_IntegrityProtected_Ciphered,
                                                      cr_IDENTITY_RESPONSE(f_Imsi2MobileIdentity(px_IMSI_Def)))));
    f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 10");
    
  }; //function fl_TC_9_4_Steps1To10
 
  }//group LocalFunction9_4

  
  //////////////////////////////////////////////////////////////////
  // TC 9.4.1
  //////////////////////////////////////////////////////////////////
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.4.1
   * @status    APPROVED
   */
  function f_TC_9_4_1_EUTRA() runs on EUTRA_PTC
  {
    //@desc Integrity protection: Correct functionality of EPS NAS integrity algorithm (SNOW3G)
    
    // ((1)
    //with { succesful completion of EPS authentication and key agreement (AKA) procedure }
    //ensure that {
    //  when { UE receives a an integrity protected SECURITY MODE COMMAND message instructing to start integrity protection using algorithm SNOW3G }
    //   then { UE transmits an integrity protected SECURITY MODE COMPLETE using SNOW3G and starts applying the NAS Integrity protection in both UL and DL }
    //(2)
    //with { Integrity protection succesfull started by executing Security Mode Procedure}
    //ensure that {
    //  when { UE receives an IDENTITY REQUEST message without integrity protected }
    //   then { UE foes not transmit an IDENTITY RESPONSE message }
    //}
    
    
    // Pre-test conditions
    // -------------------
    // System Simulator:
    //   - Cell 1
    
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    
    // Preamble: The UE is in state Switched OFF (state 1)
    // ==========================================================================
    f_EUTRA_Preamble(eutra_CellA, STATE2_IDLEUPDATE);
    f_EUTRA_UE_Detach_SwitchOffUe(eutra_CellA, RRC_IDLE);
    f_EUTRA_TestBody_Set(true);
    
    fl_TC_9_4_Integrity(tsc_EPS_Integerity_Snow3G);
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED); // R5-103847
  } // function f_TC_9_4_1_EUTRA
  
  //////////////////////////////////////////////////////////////////
  // TC 9.4.2
  //////////////////////////////////////////////////////////////////
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.4.2
   * @status    APPROVED
   */
  function f_TC_9_4_2_EUTRA() runs on EUTRA_PTC
  {
    //@desc Integrity protection: Correct functionality of EPS NAS integrity algorithm (AES)
    
    // ((1)
    //with { succesful completion of EPS authentication and key agreement (AKA) procedure }
    //ensure that {
    //  when { UE receives a an integrity protected SECURITY MODE COMMAND message instructing to start integrity protection using algorithm AES }
    //   then { UE transmits an integrity protected SECURITY MODE COMPLETE using AES and starts applying the NAS Integrity protection in both UL and DL }
    //(2)
    //with { Integrity protection succesfull started by executing Security Mode Procedure}
    //ensure that {
    //  when { UE receives an IDENTITY REQUEST message without integrity protected }
    //   then { UE foes not transmit an IDENTITY RESPONSE message }
    //}
    
    
    // Pre-test conditions
    // -------------------
    // System Simulator:
    //   - Cell 1
    
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    
    // Preamble: The UE is in state Switched OFF (state 1)
    // ==========================================================================
    f_EUTRA_Preamble(eutra_CellA, STATE2_IDLEUPDATE);
    f_EUTRA_UE_Detach_SwitchOffUe(eutra_CellA, RRC_IDLE);
    f_EUTRA_TestBody_Set(true);
    
    fl_TC_9_4_Integrity(tsc_EPS_Integerity_AES);
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED); // R5-103847
  } // function f_TC_9_4_1_EUTRA
  
  //////////////////////////////////////////////////////////////////
  // TC 9.4.3
  //////////////////////////////////////////////////////////////////
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.4.3
   * @status    APPROVED
   */
  function f_TC_9_4_3_EUTRA() runs on EUTRA_PTC
  {
    //@desc Ciphering and Deciphering: Correct functionality of EPS NAS encryption algorithm (SNOW3G)
    
    //(1)
    //with { succesful completion of EPS authentication and key agreement (AKA) procedure }
    //ensure that {
    //  when { UE receives a SECURITY MODE COMMAND instructing to start ciphering using algorithm SNOW3G }
    //   then { UE sends a SECURITY MODE COMPLETE message ciphered with SNOW3G  and starts applying the NAS ciphering in both UL and DL}
    //}
    
    // Pre-test conditions
    
    // System Simulator:
    //   - Cell 1
    
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    
    // Preamble: The UE is in state Switched OFF (state 1)
    // ==========================================================================
    f_EUTRA_Preamble(eutra_CellA, STATE2_IDLEUPDATE);
    f_EUTRA_UE_Detach_SwitchOffUe(eutra_CellA, RRC_IDLE);
    f_EUTRA_TestBody_Set(true);
    f_EUTRA_NAS_CipheringAlgorithm_Set(tsc_EPS_Encryption_Snow3G);
    fl_TC_9_4_Steps1To10();
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED); // R5-103847
  } // function f_TC_9_4_3_EUTRA


  //////////////////////////////////////////////////////////////////
  // TC 9.4.4
  //////////////////////////////////////////////////////////////////
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.4.4
   * @status    APPROVED
   */
  function f_TC_9_4_4_EUTRA() runs on EUTRA_PTC
  {
    //@desc Ciphering and Deciphering: Correct functionality of EPS NAS encryption algorithm (AES)
    
    //(1)
    //with { succesful completion of EPS authentication and key agreement (AKA) procedure }
    //ensure that {
    //  when { UE receives a SECURITY MODE COMMAND instructing to start ciphering using algorithm AES }
    //   then { UE sends a SECURITY MODE COMPLETE message ciphered with AES  and starts applying the NAS ciphering in both UL and DL}
    //}
    
    // Pre-test conditions
    // -------------------
    // System Simulator:
    //   - Cell 1
    
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    
    // Preamble: The UE is in state Switched OFF (state 1)
    // ==========================================================================
    f_EUTRA_Preamble(eutra_CellA, STATE2_IDLEUPDATE);
    f_EUTRA_UE_Detach_SwitchOffUe(eutra_CellA, RRC_IDLE);
    f_EUTRA_TestBody_Set(true);
    f_EUTRA_NAS_CipheringAlgorithm_Set(tsc_EPS_Encryption_AES);
    fl_TC_9_4_Steps1To10();
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED); // R5-103847
  } // function f_TC_9_4_4_EUTRA
    
} // module NAS_SecurityMode
