// ***************************************************************************
// @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-16 14:08:29 +0200 (Thu, 16 Sep 2010) $
// * $Rev: 3933 $
// ***************************************************************************

module NAS_Authentication {

  import from EUTRA_RRC_ASN1_Definitions language "ASN.1:1997" all;
  import from EUTRA_Component all;
  import from EUTRA_CellInfo all;
  import from EUTRA_ASP_SrbDefs all;
  import from Parameters all;
  import from CommonDefs all;
  import from EUTRA_CommonDefs all;
  import from EUTRA_RRCSteps 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 EUTRA_Paging all;
  import from NAS_CommonTypeDefs all;
  import from EPS_NAS_Constants all;
  import from EPS_NAS_TypeDefs all;
  import from EPS_NAS_Templates all;
  import from EUTRA_NASCommonFunctions all;
  import from NAS_CommonTemplates all;
  import from EUTRA_NASCommonTemplates all;
  import from EPS_NAS_MsgContainers all;
  import from EUTRA_NASSteps all;
  import from UpperTesterFunctions all;
  import from EUTRA_AuxiliaryFunctions all;
  import from NAS_AuxiliaryDefsAndFunctions all;
  import from EUTRA_ConfigurationSteps all;
  import from EUTRA_Timing all;
  
  group LocalFunctions {
  /*
   * @desc      Calculation is done according to 34.108, clause 8.1.2 and 33.102, clause 6.8.1.2
   *            Generation of Ck, Ik, AUTN and XRES, and intentionally makes MAC error
   * @param     p_Auth_Params
   * @return    Common_AuthenticationParams_Type
   * @status    APPROVED
   */
  function fl_AuthenticationInit_MACerror(Common_AuthenticationParams_Type p_Auth_Params) return Common_AuthenticationParams_Type
  {
    var Common_AuthenticationParams_Type v_Auth_Params := p_Auth_Params;
    var B128_Type v_XDOut;
    var B80_Type v_AUTN_2;
    var B64_Type v_CDOut;
    var B64_Type v_XDOut_Half;
    var B64_Type v_MAC;
    var B48_Type v_AK;
    var B48_Type v_AUTN_1;
    var B48_Type v_AuthSQN := '000000000000000000000000000000000000000000000000'B;
    var integer v_ErrorInit := 5;
    //v_Auth_Params.KSIasme:= int2bit(((bit2int(v_Auth_Params.KSIasme)+1) mod 8), 3);
    v_XDOut := p_Auth_Params.RandValue xor4b px_AuthK;
    v_CDOut := v_AuthSQN & px_AuthAMF;
    v_XDOut_Half := substr( v_XDOut, 0, 64);
    v_AK := substr( v_XDOut, 24, 48);
    v_AUTN_1 := v_AuthSQN xor4b v_AK;
    v_MAC := int2bit((bit2int(v_XDOut_Half xor4b v_CDOut) + v_ErrorInit), 64);  // now MAC is wrong in the AUTN
    v_AUTN_2 := px_AuthAMF & v_MAC;
    v_Auth_Params.AUTN   := v_AUTN_1 & v_AUTN_2;
    // v_IKey := 128 bits of v_XDOut, wrapped, starting from offset 16
    v_Auth_Params.IK := substr( v_XDOut, 16, (128 - 16)) & substr( v_XDOut, 0, 16);
    // v_CKey := 128 bits of v_XDOut, wrapped, starting from offset 8
    v_Auth_Params.CK   := substr( v_XDOut, 8, (128 - 8)) & substr( v_XDOut, 0, 8);
    // old code v_Auth_Params.XRES := substr( v_XDOut, 0, (px_AuthN + 1));
    v_Auth_Params.XRES := v_XDOut;
    // ((CK1 XOR CK2) XOR (IK1 XOR IK2))
    return (v_Auth_Params);
  };
  
  /*
   * @desc      Calculation is done according to 34.108, clause 8.1.2 and 33.102, clause 6.8.1.2
   *            Generation of Ck, Ik, AUTN and XRES, and intentionally set AMF field to AMF_resynch so as to cause SQN failure
   * @param     p_Auth_Params
   * @return    Common_AuthenticationParams_Type
   * @status    APPROVED
   */
  function fl_AuthenticationInit_SQNFailure(Common_AuthenticationParams_Type p_Auth_Params) return Common_AuthenticationParams_Type
  {
    var Common_AuthenticationParams_Type v_Auth_Params := p_Auth_Params;
    var B128_Type v_XDOut;
    var B80_Type v_AUTN_2;
    var B64_Type v_CDOut;
    var B64_Type v_XDOut_Half;
    var B64_Type v_MAC;
    var B48_Type v_AK;
    var B48_Type v_AUTN_1;
    var B48_Type v_AuthSQN := '000000000000000000000000000000000000000000000000'B;
    var B16_Type v_AuthAMF := '1111111111111111'B;      //AMF_resynch value
    //v_Auth_Params.KSIasme:= int2bit(((bit2int(v_Auth_Params.KSIasme)+1) mod 8), 3);
    v_XDOut := p_Auth_Params.RandValue xor4b px_AuthK;
    v_CDOut := v_AuthSQN & v_AuthAMF;
    v_XDOut_Half := substr( v_XDOut, 0, 64);
    v_AK := substr( v_XDOut, 24, 48);
    v_AUTN_1 := v_AuthSQN xor4b v_AK;
    v_MAC := v_XDOut_Half xor4b v_CDOut;
    v_AUTN_2 := v_AuthAMF & v_MAC;
    v_Auth_Params.AUTN   := v_AUTN_1 & v_AUTN_2;
    // v_IKey := 128 bits of v_XDOut, wrapped, starting from offset 16
    v_Auth_Params.IK := substr( v_XDOut, 16, (128 - 16)) & substr( v_XDOut, 0, 16);
    // v_CKey := 128 bits of v_XDOut, wrapped, starting from offset 8
    v_Auth_Params.CK   := substr( v_XDOut, 8, (128 - 8)) & substr( v_XDOut, 0, 8);
    // old code v_Auth_Params.XRES := substr( v_XDOut, 0, (px_AuthN + 1));
    v_Auth_Params.XRES := v_XDOut;
    
    // ((CK1 XOR CK2) XOR (IK1 XOR IK2))
    return (v_Auth_Params);
  };
  
  } // group LocalFunctions
  
  group Testcases {
  
  // ==========================TC 9.1.2.1 =====================================
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.1.2.1
   * @status    APPROVED
   */
  function f_TC_9_1_2_1_EUTRA() runs on EUTRA_PTC
  { /* @desc Attach procedure for EPS services. Attach Procedure / Success (valid GUTI).
     * Test Purpose (TP)
     * (1)
     * with { a NAS signalling connection existing }
     * ensure that {
     *   when { the UE receives an AUTHENTICATION REQUEST message }
     *     then { the UE responds with a correct AUTHENTICATION RESPONSE message and establishes correct EPS security context }
     *             }
     *
     * Pre-test conditions
     *    System Simulator:
     *     -   Cell A
     *    UE:
     *     -   The test USIM contains a valid GUTI-1 and TAI-1, and EPS update status is "EU1: UPDATED"; EPS security context has been established and taken into use.
     *    Preamble:
     *     -   UE in state Switched OFF (State 1) according to [18].
     */
    
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    
    // Preamble: UE is in state Switched OFF (state 1)
    // ==========================================================================
    // make sure that UE has a valid GUTI before starting with actual test steps
    f_EUTRA_Preamble (eutra_CellA, STATE2_IDLEUPDATE);
    f_EUTRA_UE_Detach_SwitchOffUe ( eutra_CellA, RRC_IDLE );
    f_EUTRA_TestBody_Set(true);
    
    fl_TC_9_1_2_1_Body();
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED);//@sic R5-103875 sic@
  }
  
  /*
   * @desc      testbody of TC_9_1_2_1
   * @status    APPROVED
   */
  function fl_TC_9_1_2_1_Body() runs on EUTRA_PTC
  {
    // ==========================================================================
    // initialize constant test case data structures
    // ==========================================================================
    var HalfOctet_Type v_EPS_Bearer_Id := tsc_EpsDefaultBearerId;
    var ProcedureTransactionIdentifier v_EPS_TI := '00'O;
    var RRC_TransactionIdentifier v_RRC_TI := tsc_RRC_TI_Def;
    var ReleaseCause v_RRC_ReleaseCause := other;
    var B3_Type v_PDNValue := f_GetPdnType();
    var NAS_KsiValue v_KSIasme;
    var NAS_AttDetValue_Type v_AttachType := f_GetEAttachType();
    var B32_128_Type v_ReceivedRES;
    var NasCount_Type v_NasCountUL;
    var GutiParameters_Type v_GutiParams := f_EUTRA_CellInfo_GetGuti(eutra_CellA);
    var NAS_Lac v_LAC := f_EUTRA_CellInfo_GetLocationAreaCode(eutra_CellA);
    var NAS_PlmnId v_PLMN := f_Asn2Nas_PlmnId (v_GutiParams.PLMN_Identity);
    var template (omit) LocAreaId v_LAI := f_GetLAI(v_PLMN,v_LAC);
    var template AdditionalUpdateType v_AdditionalUpdateType := f_GetAdditionalUpdateType ();  //used to follow TTCN3 v411 standard
    var template (omit) MobileIdentity v_MSId := f_GetMSId ();// @sic R5-103673 sic@ @sic R5-103673 sic@
    var template (omit) AccessPointName v_APN := omit;
    var EUTRA_SecurityParams_Type v_SecurityParams := f_EUTRA_Security_Get();
    var template (omit) ProtocolConfigOptions v_Pco := omit;
    var template (omit) ESM_Cause v_ESM_Cause := omit; // @sic R5-104703 sic@
    
    // temporary variable which is used when receiving NAS ASPs
    var NAS_MSG_Indication_Type v_NasInd;
    var SRB_COMMON_IND v_ReceivedAsp;
    
    timer t_T3460 :=  f_EUTRA_SetTimerToleranceMax (eutra_CellA, 6.0);
    
    //+   The UE is switched on.
    //@siclog "Step 1" siclog@
    f_UT_SwitchOnUE (UT, false); /* no USIM insertion */
    
    //+   The UE transmit an ATTACH REQUEST including a GUTI and a PDN CONNECTIVITY REQUEST message
    //@siclog "Step 2" siclog@
    v_NasInd:= f_EUTRA_RRC_ConnEst_DefWithNas(eutra_CellA,
                                              v_RRC_TI,
                                              cr_EstablishmentCause_Any,
                                              cr_NAS_IndicationWithPiggybacking(tsc_SHT_IntegrityProtected,
                                                                                cr_508_ATTACH_REQUEST(v_AttachType,v_AdditionalUpdateType),
                                                                                cr_508_PDN_CONNECTIVITY_REQUEST(tsc_PdnRequest_InitialAttach,
                                                                                                                v_PDNValue)));
    v_EPS_TI := 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)) {
      v_Pco := v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST.protocolConfigurationOptions;
    }
    
    //+   SS transmits an AUTHENTICATION REQUEST message, KSIASME value
    //    is different to the KSIASME value provided in the ATTACH REQUEST
    //+   Evaluate Authentication parameters and generate new keys
    v_SecurityParams := f_EUTRA_Authentication_InitNAS(v_SecurityParams, v_PLMN);
    v_KSIasme := v_SecurityParams.KSIasme; // store this value for checking against later in the Service Request
    
    //@siclog "Step 3" siclog@
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_IntegrityProtected_Ciphered,
                                                cs_AUTHENTICATION_REQUEST(v_SecurityParams.KSIasme,
                                                                          v_SecurityParams.AuthParams.RandValue,
                                                                          v_SecurityParams.AuthParams.AUTN))));
    //+   Check: Check: Does the UE respond with AUTHENTICATION RESPONSE
    //    message within 6 seconds and the included RES is equal to the XRES calculated in the SS?
    
    //@siclog "Step 4" siclog@
    t_T3460.start;
    alt {
      [] SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                         cr_NAS_Indication(tsc_SHT_IntegrityProtected_Ciphered,
                                                           cr_AUTHENTICATION_RESPONSE)))
        -> value v_ReceivedAsp {
        t_T3460.stop;
        v_ReceivedRES := v_ReceivedAsp.Signalling.Nas[0].Pdu.Msg.aUTHENTICATION_RESPONSE.authenticationResponseParameter.res;
        if (v_ReceivedRES == substr(v_SecurityParams.AuthParams.XRES, 0, lengthof(v_ReceivedRES)))
          {
            f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 4");
          }
        else
          {
            f_EUTRA_SetVerdictFailOrInconc (__FILE__, __LINE__, "Step 4");
          }
      }
      [] t_T3460.timeout
        {
          f_EUTRA_SetVerdictFailOrInconc(__FILE__, __LINE__, "Step 4");
        }
    }
    
    //+ Step 5 :   SS transmits a NAS SECURITY MODE COMMAND message including the KSIASME of the
    //             new EPS security context (as provided in step 3)
    //  Step 6:   Check: Does the UE respond with NAS SECURITY MODE COMPLETE message
    //            integrity protected and ciphered with the new EPS security context identified by the
    //            KSIASME received in the SECURITY MODE COMMAND message in step 5?
    //@siclog "Steps 5 - 6" siclog@
    v_NasCountUL := f_EUTRA_NAS_ActivateSecurity(eutra_CellA, v_SecurityParams);
    f_EUTRA_PreliminaryPass (__FILE__, __LINE__, "Step 6");
    
    //EXCEPTION: Steps 7a1 to 7a2 describe behaviour that depends on UE configuration; the "lower case letter" identifies a step sequence
    //           that take place if the UE has ESM information which needs to be transferred.
    //+ Step 7a1: IF the UE sets the ESM information transfer flag in the last PDN CONNECTIVITY REQUEST message THEN the SS transmits an
    //             ESM INFORMATION REQUEST message to initiate exchange of protocol configuration options and/or APN.
    //Step 7a2:  The UE transmits an ESM INFORMATION RESPONSE message to transfer protocol configuration options and/or APN.
    //@siclog "Steps 7a1 - 7a2" siclog@
    if (f_CheckEsmInfoTransferFlag(v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST)) {
      v_APN := f_ESM_InformationTransfer_GetAPN (eutra_CellA, v_EPS_TI);
    }
    
    // Now have to do AS Security too @sic R5s100169 sic@
    v_SecurityParams := f_EUTRA_Authentication_InitAS(v_SecurityParams, v_NasCountUL);
    v_SecurityParams := f_EUTRA_RRC_ActivateSecurity(eutra_CellA,v_SecurityParams,v_NasCountUL);
    f_EUTRA_Security_Set ( v_SecurityParams );
    
    //+   SS responds with ATTACH ACCEPT message. The ACTIVATE DEFAULT EPS BEARER CONTEXT REQUEST message is piggybacked in ATTACH ACCEPT message
    //@siclog "Step 8" siclog@
    f_EUTRA_RRCConnectionReconfigurationWithAttachAcceptAllParams(eutra_CellA,
                                                                  v_EPS_Bearer_Id,
                                                                  v_RRC_TI,
                                                                  v_EPS_TI,
                                                                  v_AttachType,
                                                                  f_GetPDNAddress (f_CheckPCOforIPallocationViaNas (v_Pco)),
                                                                  f_GutiParameters2MobileIdentity(tsc_IEI_Guti, v_GutiParams),
                                                                  cs_TrackingAreaIdListDef_lv,
                                                                  v_LAI,
                                                                  v_MSId,
                                                                  v_ESM_Cause,
                                                                  v_APN,
                                                                  f_GetDefPCOforPCSCFAddress (v_Pco), // @sic R5-104703 sic@
                                                                  v_NasInd.Pdu.Msg.aTTACH_REQUEST.addUpdateType);  // @sic R5s100084 sic@ @sic R5-103681 sic@
    
    //+   The UE transmits an ATTACH COMPLETE message including an ACTIVATE DEFAULT EPS BEARER CONTEXT ACCEPT message
    //@siclog "Step 9" siclog@
    f_EUTRA_NAS_AttachComplete(eutra_CellA, v_EPS_Bearer_Id);
    
    //@siclog "Step 10a1 Void" siclog@

    //+   The SS releases the RRC connection.
    //@siclog "Step 11" siclog@
    f_EUTRA_RRC_ConnectionRelease(eutra_CellA, v_RRC_TI, v_RRC_ReleaseCause);
    
    //+  SS pages the UE using S-TMSI with CN domain indicator set to "PS".
    //@siclog "Step 12" siclog@
    f_EUTRA_UE_Page ( eutra_CellA,
                      cs_NasPaging_OneRecord ( cs_PagingUE_Identity_S_TMSI ( v_GutiParams.MME_Code,
                                                                             v_GutiParams.M_TMSI )));
    
    //+   Check: Does the UE respond with SERVICE REQUEST
    //    message providing KSIASME value that equals the value provided
    //    in the AUTHENTICATION REQUEST message in Step 3, and, integrity protected with new EPS security context?
    //@siclog "Step 13" siclog@
    v_NasInd := f_EUTRA_RRC_ConnEst_DefWithNas ( eutra_CellA,
                                                 v_RRC_TI,
                                                 cr_EstablishmentCause_mt_Access,  cr_NAS_Indication(tsc_SHT_IntegrityProtected,
                                                                                                     cr_508_SERVICE_REQUEST(v_SecurityParams.KSIasme)));
    f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 13");
    
    
    // @sic R5-102180 sic@
    // Steps 6 to 9 of the generic radio bearer establishment procedure (TS 36.508 5.4.3.3-1) are executed
    // to successfully complete the service request procedure
    //@siclog "Steps 14 - 17" siclog@
    f_EUTRA_ServiceReqPostamble_508Steps6_9 (eutra_CellA, v_NasInd);
          

    
    // ==========================================================================
  } // function fl_tc_9_1_2_1_Body
  
  
  // ==========================TC 9.1.2.3 =====================================
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.1.2.3
   * @status    APPROVED
   */
  function f_TC_9_1_2_3_EUTRA() runs on EUTRA_PTC
  {
    // @desc: Attach procedure for EPS services. Authentication not accepted by the network, GUTI used,
    //         authentication reject and re-authentication.
    /* Test Purpose (TP)
       (1)
       with { UE having sent an initial NAS message with type of identity GUTI }
       ensure that {
       when { as a result of failure of an Authentication procedure intiated by the network the UE receives an AUTHENTICATION REJECT message }
       then { the UE shall set the update status to EU3 ROAMING NOT ALLOWED, delete the stored GUTI, TAI list, last visited registered TAI and KSIASME and enter state EMM-DEREGISTERED }
       }
       Pre-test conditions:
       System Simulator:
       -   Cell A
       UE:
       -   The test USIM contains a valid GUTI-1 and TAI-1, and EPS update status is "EU1: UPDATED"; EPS security context has been established and taken into use.
       Preamble:
       -   The UE is in state Switched OFF (state 1) according to [18].
       
    */
    
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    
    // Preamble: 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_1_2_3_Body();
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED);//@sic R5-103875 sic@
  }

  /*
   * @desc      test body of TC_9_1_2_3
   * @status    APPROVED
   */
  function fl_TC_9_1_2_3_Body() runs on EUTRA_PTC
  {
    // ==========================================================================
    // initialize constant test case data structures
    // ==========================================================================
    var ProcedureTransactionIdentifier v_EPS_TI := '00'O;
    var RRC_TransactionIdentifier v_RRC_TI := tsc_RRC_TI_Def;
    var ReleaseCause v_RRC_ReleaseCause := other;
    var B3_Type v_PDNValue := f_GetPdnType();
    var NAS_AttDetValue_Type v_AttachType := f_GetEAttachType();
    var float v_NoReactionTime := 3.0;
    var GutiParameters_Type v_GutiParams := f_EUTRA_CellInfo_GetGuti(eutra_CellA);
    var NAS_PlmnId v_PLMN := f_Asn2Nas_PlmnId (v_GutiParams.PLMN_Identity);
    var template AdditionalUpdateType v_AdditionalUpdateType := f_GetAdditionalUpdateType ();  //used to follow TTCN3 v411 standard
    var EUTRA_SecurityParams_Type v_SecurityParams := f_EUTRA_Security_Get();
    var template (omit) ProtocolConfigOptions v_Pco := omit;
    var NAS_MSG_Indication_Type v_NasInd;
      
    //+   The UE is switched on.
    //@siclog "Step 1" siclog@
    f_UT_SwitchOnUE (UT, false); /* no USIM insertion */
    
    //+   The UE transmit an ATTACH REQUEST message including a GUTI and a PDN CONNECTIVITY REQUEST message
    //@siclog "Step 2" siclog@
    v_NasInd := f_EUTRA_RRC_ConnEst_DefWithNas(eutra_CellA,
                                               v_RRC_TI,
                                               cr_EstablishmentCause_Any,
                                               cr_NAS_IndicationWithPiggybacking(tsc_SHT_IntegrityProtected,
                                                                                 cr_508_ATTACH_REQUEST(v_AttachType,v_AdditionalUpdateType),
                                                                                 cr_508_PDN_CONNECTIVITY_REQUEST(tsc_PdnRequest_InitialAttach,
                                                                                                                 v_PDNValue)));
    //+   SS transmits an AUTHENTICATION REQUEST message
    v_SecurityParams := f_EUTRA_Authentication_InitNAS(v_SecurityParams, v_PLMN);
    
    //@siclog "Step 3" siclog@
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection,  // @sic R5-103833r1 sic@
                                                cs_AUTHENTICATION_REQUEST(v_SecurityParams.KSIasme,
                                                                          v_SecurityParams.AuthParams.RandValue,
                                                                          v_SecurityParams.AuthParams.AUTN))));
    //+    the UE respond with a  AUTHENTICATION RESPONSE message
    //@siclog "Step 4" siclog@
    SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication((tsc_SHT_IntegrityProtected, tsc_SHT_NoSecurityProtection), // @sic R5-103085 sic@ @sic R5-100279 change 15 sic@
                                                      cr_AUTHENTICATION_RESPONSE)));
    //+ SS transmits an AUTHENTICATION REJECT
    //@siclog "Step 5" siclog@
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection,
                                                cs_508_AUTHENTICATION_REJECT)));
    //   The SS releases RRC connection.
    //@siclog "Step 6" siclog@
    f_EUTRA_RRC_ConnectionRelease(eutra_CellA, v_RRC_TI, v_RRC_ReleaseCause);
       
    //+ Does the UE transmit an ATTACH REQUEST message in the next 30 seconds?
    //@siclog "Step 7" siclog@
    f_EUTRA_CheckNoAttachOn1Cell (eutra_CellA, 30.0, "Step 7");
    
    //+ Check: Does the test result of CALL generic procedure "Test procedure for no response to paging (for NAS testing)" clause
    //         6.4.2.5 [18] indicates that the UE responds to paging when paged with GUTI-1 and with CN domain indicator set to "PS"?
    
    //@siclog "Step 8" siclog@
    f_EUTRA_508Check_NASNoResponse ( eutra_CellA,
                                     cs_NasPaging_OneRecord(cs_PagingUE_Identity_S_TMSI(v_GutiParams.MME_Code, v_GutiParams.M_TMSI)),
                                     v_NoReactionTime );
    
    //+ Check: Does the test result of CALL generic procedure "Test procedure for no response to paging (for NAS testing)"
    //         clause 6.4.2.5 [18] indicates that the UE responds to paging when paged with IMSI and with CN domain indicator set to "PS"?
    //@siclog "Step 9" siclog@
    f_EUTRA_508Check_NASNoResponse ( eutra_CellA,
                                     cs_NasPaging_OneRecord(cs_PagingUE_Identity_IMSI(f_ConvertImsi2ASN(px_IMSI_Def))),
                                     v_NoReactionTime );
    //+   The UE is switched off.
    //@siclog "Step 10" siclog@
    f_UT_SwitchOffUE(UT, false);
    
    //+   The UE is switched on.
    //@siclog "Step 11" siclog@
    f_UT_SwitchOnUE(UT, false);
    
    //+   Check: Does UE transmit a NOT integrity protected ATTACH REQUEST message including
    //             IMSI and a PDN CONNECTIVITY REQUEST message?
    //@siclog "Step 12" siclog@
    v_NasInd:= f_EUTRA_RRC_ConnEst_DefWithNas(eutra_CellA,
                                              v_RRC_TI,
                                              cr_EstablishmentCause_Any,
                                              cr_NAS_IndicationWithPiggybacking(tsc_SHT_NoSecurityProtection,
                                                                                cdr_ATTACH_REQUEST_WithOldMobileIdNoTAI(v_AttachType,
                                                                                                                        v_AdditionalUpdateType,
                                                                                                                        f_Imsi2MobileIdentity(px_IMSI_Def)),
                                                                                cr_508_PDN_CONNECTIVITY_REQUEST(tsc_PdnRequest_InitialAttach,
                                                                                                                v_PDNValue)));
    f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 12");
    v_EPS_TI := 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)) {
      v_Pco := v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST.protocolConfigurationOptions;
    }
    
    //@siclog "Step 13-24" siclog@
    f_EUTRA_IdleUpdated_Step5_17 (eutra_CellA, STATE2_IDLEUPDATE, NORMAL, v_NasInd, false); // R5-105005
    // ==========================================================================
  } // function fl_tc_9_1_2_3_Body
  
  
  
  // ==========================TC 9.1.2.4 =====================================
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.1.2.4
   * @status    APPROVED
   */
  function f_TC_9_1_2_4_EUTRA() runs on EUTRA_PTC
  {
    // @desc: Authentication not accepted by the UE, MAC code failure
    /*
      Test Purpose (TP)
      (1)
      with { UE in EMM-REGISTERED state / EMM-CONNECTED mode}
      ensure that {
      when { the UE receives an AUTHENTICATION REQUEST message with invalid MAC code }
      then { the UE shall send an AUTHENTICATION FAILURE message to the network, with the reject cause #20 "MAC failure" }
      }
      Pre-test conditions
      System Simulator:
      -   Cell A
      UE:
      -   None.
      Preamble:
      -   UE is in state Switched OFF (State 1)
    */
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    
    // Preamble: UE is in state Switched OFF (state 1)
    // ==========================================================================
    
    f_EUTRA_Preamble_Reject(eutra_CellA, tsc_EmmCause_IllegalMe);
    f_EUTRA_TestBody_Set(true);
    
    fl_TC_9_1_2_4_Body();
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED);//@sic R5-103875 sic@
  }
  
  /*
   * @desc      test body of TC_9_1_2_4
   * @status    APPROVED
   */
  function fl_TC_9_1_2_4_Body() runs on EUTRA_PTC
  {
    // ==========================================================================
    // initialize constant test case data structures
    // ==========================================================================
    var HalfOctet_Type v_EPS_Bearer_Id := tsc_EpsDefaultBearerId;
    var ProcedureTransactionIdentifier v_EPS_TI := '00'O;
    var RRC_TransactionIdentifier v_RRC_TI := tsc_RRC_TI_Def;
    var B3_Type v_PDNValue := f_GetPdnType();
    var NAS_AttDetValue_Type v_AttachType := f_GetEAttachType();
    var B32_128_Type v_ReceivedRES;
    var NasCount_Type v_NasCountUL;
    
    // ==========================================================================
    // initialize component specific data structures
    // ==========================================================================
    // get all data which are required for a GUTI, LAI and MS Id
    var GutiParameters_Type v_GutiParams := f_EUTRA_CellInfo_GetGuti(eutra_CellA);
    var NAS_Lac v_LAC := f_EUTRA_CellInfo_GetLocationAreaCode(eutra_CellA);
    var NAS_PlmnId v_PLMN := f_Asn2Nas_PlmnId (v_GutiParams.PLMN_Identity);
    var template (omit) LocAreaId v_LAI := f_GetLAI(v_PLMN,v_LAC);
    var template (omit) MobileIdentity v_MSId := f_GetMSId ();// @sic R5-103673 sic@
    var template (omit) AccessPointName v_APN := omit;
    var template AdditionalUpdateType v_AdditionalUpdateType := f_GetAdditionalUpdateType (); //used to follow TTCN3 v411 standard
    // get initial security parameters
    var EUTRA_SecurityParams_Type v_SecurityParams := f_EUTRA_Security_Get();
    var template (omit) ProtocolConfigOptions v_Pco := omit;
    var template (omit) ESM_Cause v_ESM_Cause := omit; // @sic R5-104703 sic@
    var NAS_MSG_Indication_Type v_NasInd;
    var SRB_COMMON_IND v_ReceivedAsp;
    var NAS_IdType v_IdentityType := tsc_IdType_IMSI;
    // ==========================================================================
    
    //+   The UE is switched on.
    //@siclog "Step 1" siclog@
    f_UT_SwitchOnUE (UT, false); /* no USIM insertion */
    
    //+   The UE transmits an ATTACH REQUEST message including a PDN CONNECTIVITY REQUEST message
    //@siclog "Step 2" siclog@
    v_NasInd:= f_EUTRA_RRC_ConnEst_DefWithNas(eutra_CellA,
                                              v_RRC_TI,
                                              cr_EstablishmentCause_Any,
                                              cr_NAS_IndicationWithPiggybacking(tsc_SHT_NoSecurityProtection, // @sic R5s100169 sic@
                                                                                cr_508_ATTACH_REQUEST(v_AttachType,v_AdditionalUpdateType),
                                                                                cr_508_PDN_CONNECTIVITY_REQUEST(tsc_PdnRequest_InitialAttach,
                                                                                                                v_PDNValue)));
    v_EPS_TI := 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)) {
      v_Pco := v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST.protocolConfigurationOptions;
    }
    
    //+  SS transmits an AUTHENTICATION REQUEST message which contains an invalid MAC code
    //+   Evaluate Authentication parameters and generate new keys
    v_SecurityParams := f_EUTRA_Authentication_InitNAS(v_SecurityParams,
                                                       v_PLMN,
                                                       fl_AuthenticationInit_MACerror(v_SecurityParams.AuthParams));  /* @sic R5s100086 cl. 5.3.2 sic@ */
    //@siclog "Step 3" siclog@
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection, // @sic R5s100169 sic@
                                                cs_AUTHENTICATION_REQUEST(v_SecurityParams.KSIasme,
                                                                          v_SecurityParams.AuthParams.RandValue,
                                                                          v_SecurityParams.AuthParams.AUTN))));
    //+   Check: Does the UE respond with a AUTHENTICATION FAILURE message, with reject cause "MAC failure"?
    //@siclog "Step 4" siclog@
    SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_NoSecurityProtection, // @sic R5s100169 sic@
                                                      cdr_AUTHENTICATION_FAIL_mac)));
    f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 4");
    
    //+ SS transmits an IDENTITY REQUEST
    //@siclog "Step 5" siclog@
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection,
                                                cs_IDENTITY_REQUEST(v_IdentityType))));
    
    //+ SS receives an IDENTITY RESPONSE
    //@siclog "Step 6" siclog@
    SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_NoSecurityProtection,
                                                      cr_IDENTITY_RESPONSE(f_Imsi2MobileIdentity(px_IMSI_Def)))));
    // using the default IMSI ? this depends on which USIM card is used
    
    //+  SS transmits a correct AUTHENTICATION REQUEST message, RAND different to the one send in Step 3
    v_SecurityParams.AuthParams.RandValue  := int2bit((bit2int(px_eAuthRAND) + 1), 128);  // now RAND value is different to the value in step3
    v_SecurityParams := f_EUTRA_Authentication_InitNAS(v_SecurityParams, v_PLMN);
    //@siclog "Step 7" siclog@
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection,
                                                cs_AUTHENTICATION_REQUEST(v_SecurityParams.KSIasme,
                                                                          v_SecurityParams.AuthParams.RandValue,
                                                                          v_SecurityParams.AuthParams.AUTN))));
    //+  Check: Does the UE respond with a correct AUTHENTICATION RESPONSE message with RES that is equal to the XRES
    //   calculated in the SS?
    //@siclog "Step 8" siclog@
    SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_NoSecurityProtection,
                                                      cr_AUTHENTICATION_RESPONSE)))
      -> value v_ReceivedAsp;
    v_ReceivedRES := v_ReceivedAsp.Signalling.Nas[0].Pdu.Msg.aUTHENTICATION_RESPONSE.authenticationResponseParameter.res;
    if (v_ReceivedRES == substr(v_SecurityParams.AuthParams.XRES, 0, lengthof(v_ReceivedRES)))
      {
        f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 8");
      }
    else
      {
        f_EUTRA_SetVerdictFailOrInconc (__FILE__, __LINE__, "Step 8");
      }
    
    //+  SS transmits a SECURITY MODE COMMAND message including the KSIASME of the new EPS security contextcontext (as provided in step 8)
    //   UE transmits a SECURITY MODE COMPLETE message integrity protected and ciphered with the new EPS security context
    //   identified by the KSIASME received in the SECURITY MODE COMMAND message in step 9
    //@siclog "Steps 9 - 10" siclog@
    v_NasCountUL := f_EUTRA_NAS_ActivateSecurity(eutra_CellA, v_SecurityParams);
    f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 10");

    //EXCEPTION: Steps 11a1 to 11a2 describe behaviour that depends on UE configuration; the "lower case letter" identifies a step sequence
    //           that take place if the UE has ESM information which needs to be transferred.
    //+ Step 11a1: IF the UE sets the ESM information transfer flag in the last PDN CONNECTIVITY REQUEST message THEN the SS transmits an
    //             ESM INFORMATION REQUEST message to initiate exchange of protocol configuration options and/or APN.
    //Step 11a2:  The UE transmits an ESM INFORMATION RESPONSE message to transfer protocol configuration options and/or APN.
    //@siclog "Steps 11a1 - 11a2" siclog@
    if (f_CheckEsmInfoTransferFlag(v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST)) {
      v_APN := f_ESM_InformationTransfer_GetAPN (eutra_CellA, v_EPS_TI);
    }
    
    // Now have to do AS Security too @sic R5s100169 sic@
    v_SecurityParams := f_EUTRA_Authentication_InitAS(v_SecurityParams, v_NasCountUL);
    v_SecurityParams := f_EUTRA_RRC_ActivateSecurity(eutra_CellA,v_SecurityParams,v_NasCountUL);
    f_EUTRA_Security_Set ( v_SecurityParams );
    
    // SS responds with ATTACH ACCEPT. The ACTIVATE DEFAULT EPS BEARER CONTEXT REQUEST message is
    // piggybacked in ATTACH ACCEPT message
    //@siclog "Step 12" siclog@
    f_EUTRA_RRCConnectionReconfigurationWithAttachAcceptAllParams(eutra_CellA,
                                                                  v_EPS_Bearer_Id,
                                                                  v_RRC_TI,
                                                                  v_EPS_TI,
                                                                  v_AttachType,
                                                                  f_GetPDNAddress (f_CheckPCOforIPallocationViaNas(v_Pco)),
                                                                  f_GutiParameters2MobileIdentity(tsc_IEI_Guti, v_GutiParams),
                                                                  cs_TrackingAreaIdListDef_lv,
                                                                  v_LAI,
                                                                  v_MSId,
                                                                  v_ESM_Cause,
                                                                  v_APN,
                                                                  f_GetDefPCOforPCSCFAddress (v_Pco), // @sic R5-104703 sic@
                                                                  v_NasInd.Pdu.Msg.aTTACH_REQUEST.addUpdateType);  // @sic R5-096464 sic@ @sic R5-103681 sic@
    
    //+   The UE transmits an ATTACH COMPLETE message
    //@siclog "Step 13" siclog@
    f_EUTRA_NAS_AttachComplete(eutra_CellA, v_EPS_Bearer_Id);
     
    //@siclog "Step 14a1 Void" siclog@
    
    // ==========================================================================
  } // function fl_tc_9_1_2_4_EUTRA_Body
  

  // ==========================TC 9.1.2.5 =====================================
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.1.2.5
   * @status    APPROVED
   */
  function f_TC_9_1_2_5_EUTRA() runs on EUTRA_PTC
  {
    // @desc: Authentication not accepted by the UE, SQN failure
    /*
      Test Purpose (TP)
      (1)
      with { { a NAS signalling connection existing }}
      ensure that {
      when { the UE receives an AUTHENTICATION REQUEST message with SQN out of range }
      then { the UE sends an AUTHENTICATION FAILURE message to the network, with EMM cause "synch failure" and a re-synchronization token }
      }
      
      (2)
      with { UE having sent an AUTHENTICATION FAILURE message to the network, with EMM cause "synch failure" }
      ensure that {
      when { the UE receives a new correct AUTHENTICATION REQUEST message while T3420 is running }
      then { the UE sends a corect AUTHENTICATION RESPONSE message }
      }
      Pre-test conditions
      System Simulator:
      -   Cell A
      UE:
      -   None
      Preamble:
      -   The UE is in state Switched OFF (State 1) according to [18].
      
    */
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    
    // Preamble: UE is in state Switched OFF (state 1)
    // ==========================================================================
    
    f_EUTRA_Preamble_Reject(eutra_CellA, tsc_EmmCause_IllegalMe);
    f_EUTRA_TestBody_Set(true);
    
    fl_TC_9_1_2_5_Body();
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED);//@sic R5-103875 sic@
  }
  
  /*
   * @desc      test body of TC_9_1_2_5
   * @status    APPROVED
   */
  function fl_TC_9_1_2_5_Body() runs on EUTRA_PTC
  {
    var HalfOctet_Type v_EPS_Bearer_Id := tsc_EpsDefaultBearerId;
    var ProcedureTransactionIdentifier v_EPS_TI := '00'O;
    var RRC_TransactionIdentifier v_RRC_TI := tsc_RRC_TI_Def;
    var B3_Type v_PDNValue := f_GetPdnType();
    var NAS_AttDetValue_Type v_AttachType := f_GetEAttachType();
    var B32_128_Type v_ReceivedRES;
    var NasCount_Type v_NasCountUL;
    var GutiParameters_Type v_GutiParams := f_EUTRA_CellInfo_GetGuti(eutra_CellA);
    var NAS_Lac v_LAC := f_EUTRA_CellInfo_GetLocationAreaCode(eutra_CellA);
    var NAS_PlmnId v_PLMN := f_Asn2Nas_PlmnId (v_GutiParams.PLMN_Identity);
    var template (omit) LocAreaId v_LAI := f_GetLAI(v_PLMN,v_LAC);
    var template (omit) MobileIdentity v_MSId := f_GetMSId (); //@sic R5-103673 sic@
    var template (omit) AccessPointName v_APN := omit;
    var EUTRA_SecurityParams_Type v_SecurityParams := f_EUTRA_Security_Get();
    var NAS_MSG_Indication_Type v_NasInd;
    var SRB_COMMON_IND v_ReceivedAsp;
    var NAS_IdType v_IdentityType := tsc_IdType_IMSI;
    var template AdditionalUpdateType v_AdditionalUpdateType := f_GetAdditionalUpdateType ();  //used to follow TTCN3 v411 standard
    var template (omit) ProtocolConfigOptions v_Pco := omit;
    var template (omit) ESM_Cause v_ESM_Cause := omit; // @sic R5-104703 sic@

    timer t_T3420 := f_EUTRA_SetTimerToleranceMin(eutra_CellA, 15.0);
    
    //+   The UE is switched on.
    //@siclog "Step 1" siclog@
    f_UT_SwitchOnUE (UT, false); /* no USIM insertion */
    
    //+   the UE transmits an ATTACH REQUEST message including a PDN CONNECTIVITY REQUEST message
    //@siclog "Step 2" siclog@
    v_NasInd:= f_EUTRA_RRC_ConnEst_DefWithNas(eutra_CellA,
                                              v_RRC_TI,
                                              cr_EstablishmentCause_Any,
                                              cr_NAS_IndicationWithPiggybacking(tsc_SHT_NoSecurityProtection, // @sic R5s100169 sic@
                                                                                cr_508_ATTACH_REQUEST(v_AttachType,v_AdditionalUpdateType),
                                                                                cr_508_PDN_CONNECTIVITY_REQUEST(tsc_PdnRequest_InitialAttach,
                                                                                                                v_PDNValue)));
    v_EPS_TI := 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)) {
      v_Pco := v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST.protocolConfigurationOptions;
    }
    
    //+  SS transmits a AUTHENTICATION REQUEST message
    //   With the AMF field in the IE "Authentication parameter AUTN" set to "AMFRESYNCH",value to trigger SQN re-synchronisation procedure in test USIM.
    //@siclog "Step 3" siclog@
    v_SecurityParams := f_EUTRA_Authentication_InitNAS(v_SecurityParams,
                                                       v_PLMN,
                                                       fl_AuthenticationInit_SQNFailure(v_SecurityParams.AuthParams));
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection, // @sic R5s100169 sic@
                                                cs_AUTHENTICATION_REQUEST(v_SecurityParams.KSIasme,
                                                                          v_SecurityParams.AuthParams.RandValue,
                                                                          v_SecurityParams.AuthParams.AUTN))));
    //+   Check: Does the UE respond with a AUTHENTICATION FAILURE message, with reject cause "synch failure"?
    //@siclog "Step 4" siclog@
    SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_NoSecurityProtection, // @sic R5s100169 sic@
                                                      cdr_AUTHENTICATION_FAIL_synch)));
    f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 4");
    t_T3420.start;
    
    //+ SS transmits an IDENTITY REQUEST
    //@siclog "Step 5" siclog@
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection,
                                                cs_IDENTITY_REQUEST(v_IdentityType))));
    
    //+ SS receives an IDENTITY RESPONSE
    //@siclog "Step 6" siclog@
    SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_NoSecurityProtection,
                                                      cr_IDENTITY_RESPONSE(f_Imsi2MobileIdentity(px_IMSI_Def)))));
    // using the default IMSI ? this depends on which USIM card is used
    
    //+  SS transmits a AUTHENTICATION REQUEST message,
    //@siclog "Step 7" siclog@
    v_SecurityParams.AuthParams.RandValue  := int2bit((bit2int(px_eAuthRAND) + 1), 128);  // now RAND value is different to the value in step3
    v_SecurityParams := f_EUTRA_Authentication_InitNAS(v_SecurityParams, v_PLMN);
    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_NoSecurityProtection,
                                                cs_AUTHENTICATION_REQUEST(v_SecurityParams.KSIasme,
                                                                          v_SecurityParams.AuthParams.RandValue,
                                                                          v_SecurityParams.AuthParams.AUTN))));
    if (not t_T3420.running)
      {
        f_EUTRA_SetVerdictFailOrInconc(__FILE__, __LINE__, "Step 7");
      }
    else {
      t_T3420.stop;
    }
    
    //+  Check: Does the UE respond with a correct AUTHENTICATION RESPONSE message with RES that is equal to the XRES
    //   calculated in the SS?
    //@siclog "Step 8" siclog@
    SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_NoSecurityProtection,
                                                      cr_AUTHENTICATION_RESPONSE)))
      -> value v_ReceivedAsp;
    v_ReceivedRES := v_ReceivedAsp.Signalling.Nas[0].Pdu.Msg.aUTHENTICATION_RESPONSE.authenticationResponseParameter.res;
    if (v_ReceivedRES == substr(v_SecurityParams.AuthParams.XRES, 0, lengthof(v_ReceivedRES)))
      {
        f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 8");
      }
    else
      {
        f_EUTRA_SetVerdictFailOrInconc (__FILE__, __LINE__, "Step 8");
      }
    
    //+  SS transmits a SECURITY MODE COMMAND message including the KSIASME of the new EPS security context
    //   UE transmits a SECURITY MODE COMPLETE message integrity protected and ciphered with the new EPS security context
    //   identified by the KSIASME received in the SECURITY MODE COMMAND message in step 9
    //@siclog "Steps 9 - 10" siclog@
    v_NasCountUL := f_EUTRA_NAS_ActivateSecurity(eutra_CellA, v_SecurityParams);

    //EXCEPTION: Steps 11a1 to 11a2 describe behaviour that depends on UE configuration; the "lower case letter" identifies a step sequence
    //           that take place if the UE has ESM information which needs to be transferred.
    //+ Step 11a1: IF the UE sets the ESM information transfer flag in the last PDN CONNECTIVITY REQUEST message THEN the SS transmits an
    //             ESM INFORMATION REQUEST message to initiate exchange of protocol configuration options and/or APN.
    //Step 11a2:  The UE transmits an ESM INFORMATION RESPONSE message to transfer protocol configuration options and/or APN.
    //@siclog "Steps 11a1 - 11a2" siclog@
    if (f_CheckEsmInfoTransferFlag(v_NasInd.Pdu.Msg.pDN_CONNECTIVITY_REQUEST)) {
      v_APN := f_ESM_InformationTransfer_GetAPN(eutra_CellA, v_EPS_TI);
    }
    
    // Now have to do AS Security too @sic R5s100169 sic@
    v_SecurityParams := f_EUTRA_Authentication_InitAS(v_SecurityParams, v_NasCountUL);
    v_SecurityParams := f_EUTRA_RRC_ActivateSecurity(eutra_CellA,v_SecurityParams,v_NasCountUL);
    f_EUTRA_Security_Set ( v_SecurityParams );
    
    //+   SS responds with ATTACH ACCEPT message.The ACTIVATE DEFAULT EPS BEARER CONTEXT REQUEST message is piggybacked in ATTACH ACCEPT message
    //@siclog "Step 12" siclog@
    f_EUTRA_RRCConnectionReconfigurationWithAttachAcceptAllParams(eutra_CellA,
                                                                  v_EPS_Bearer_Id,
                                                                  v_RRC_TI,
                                                                  v_EPS_TI,
                                                                  v_AttachType,
                                                                  f_GetPDNAddress(f_CheckPCOforIPallocationViaNas (v_Pco)),
                                                                  f_GutiParameters2MobileIdentity(tsc_IEI_Guti, v_GutiParams),
                                                                  cs_TrackingAreaIdListDef_lv,
                                                                  v_LAI,
                                                                  v_MSId,
                                                                  v_ESM_Cause,
                                                                  v_APN,
                                                                  f_GetDefPCOforPCSCFAddress (v_Pco), // @sic R5-104703 sic@
                                                                  v_NasInd.Pdu.Msg.aTTACH_REQUEST.addUpdateType);  // @sic R5-096464 sic@
    
    //+   The UE transmits an ATTACH COMPLETE message including an ACTIVATE DEFAULT EPS BEARER CONTEXT ACCEPT message
    //@siclog "Step 13" siclog@
    f_EUTRA_NAS_AttachComplete(eutra_CellA, v_EPS_Bearer_Id);
    
    //@siclog "Step 14a1 Void" siclog@
    
    // ==========================================================================
  } // function fl_tc_9_1_2_5_EUTRA_Body
 
 
  // ==========================TC 9.1.2.6 =====================================
  function f_TC_9_1_2_6_EUTRA() runs on EUTRA_PTC
  {
    // @desc: Abnormal cases / Network failing the authentication check
    /*
      Test Purpose (TP)
      (1)
        with { UE in EMM-REGISTERED state / EMM-CONNECTED mode}
        ensure that {
          when { UE receives an AUTHENTICATION REQUEST message but UE deems that the network failed the authentication check }
            then { UE locally release the RRC connection and treat the active cell as barred }
                    }

      Pre-test conditions
    System Simulator:
    -    Cell A and Cell I are configured according to Table 6.3.2.2-1 in [18].
    -   Cell A and Cell I belong to different PLMNs and different Frequencies.
    UE:
    -   None
    Preamble:
    -   The UE is in state Switched OFF (state 1) according to clause [18].

      
    */
    f_EUTRA_NAS_Init(LTE_CellsOnDifferentPLMN,LTEmulticell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def(eutra_CellA);
    f_EUTRA_CellConfig_Def(eutra_CellI);
    // Preamble: 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_1_2_6_Body();
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellI, E2_CONNECTED);//@sic R5-103875 sic@
  }
  
  function fl_TC_9_1_2_6_Body() runs on EUTRA_PTC
  {
    var ProcedureTransactionIdentifier v_EPS_TI := '00'O;
    var RRC_TransactionIdentifier v_RRC_TI := tsc_RRC_TI_Def;
    var GutiParameters_Type v_GutiParams := f_EUTRA_CellInfo_GetGuti(eutra_CellA);
    var NAS_PlmnId v_PLMN := f_Asn2Nas_PlmnId (v_GutiParams.PLMN_Identity);
    var EUTRA_SecurityParams_Type v_SecurityParams := f_EUTRA_Security_Get();
    var EUTRA_SecurityParams_Type v_SecurityParams_MACerror;
    var NAS_MSG_Indication_Type v_NasInd;
    var template (omit) ProtocolConfigOptions v_Pco := omit;
    var template AdditionalUpdateType v_AdditionalUpdateType := f_GetAdditionalUpdateType ();
    var NAS_AttDetValue_Type v_AttachType := f_GetEAttachType(  ); // R5-103673

    timer t_T3418 :=  f_EUTRA_SetTimerToleranceMin (eutra_CellA, 20.0 );
    timer t_Wait :=f_EUTRA_SetTimerToleranceMin (eutra_CellA, 30.0 );

    //The SS configures:- Cell A as the "Serving cell".- Cell I as a " Suitable cell".
    //@siclog "Step 1" siclog@
    f_EUTRA_SetCellPower(eutra_CellA, tsc_ServingCellRS_EPRE, cs_TimingInfo_Now);
    f_EUTRA_SetCellPower(eutra_CellI, tsc_SuitableCellRS_EPRE, cs_TimingInfo_Now);

    //The following messages are to be observed on Cell A unless explicitly stated otherwise.
    //+   The UE is switched on.
    //@siclog "Step 2" siclog@
    f_UT_SwitchOnUE (UT, false);
    
    //+   the UE transmits an ATTACH REQUEST message including a PDN CONNECTIVITY REQUEST message
    //@siclog "Step 3" siclog@
    v_NasInd:= f_EUTRA_RRC_ConnEst_DefWithNas(eutra_CellA,
                                              v_RRC_TI,
                                              cr_EstablishmentCause_Any,
                                              cr_NAS_IndicationWithPiggybacking(tsc_SHT_IntegrityProtected,
                                                                                cr_508_ATTACH_REQUEST(v_AttachType, v_AdditionalUpdateType),
                                                                                cr_508_PDN_CONNECTIVITY_REQUEST(tsc_PdnRequest_InitialAttach,
                                                                                                                f_GetPdnType())));
    v_EPS_TI := 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)) {
      v_Pco := v_NasInd.Pdu.PiggybackedPduList[0].Msg.pDN_CONNECTIVITY_REQUEST.protocolConfigurationOptions;
    }
    
    //+  SS transmits an AUTHENTICATION REQUEST message which contains an invalid MAC code
    //@siclog "Step 4" siclog@
    v_SecurityParams_MACerror := f_EUTRA_Authentication_InitNAS(v_SecurityParams,
                                                       v_PLMN,
                                                       fl_AuthenticationInit_MACerror(v_SecurityParams.AuthParams));  /* @sic R5s100086 cl. 5.3.2 sic@ */

    SRB.send(cas_SRB1_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_IntegrityProtected_Ciphered,
                                                cs_AUTHENTICATION_REQUEST(v_SecurityParams_MACerror.KSIasme,
                                                                          v_SecurityParams_MACerror.AuthParams.RandValue,
                                                                          v_SecurityParams_MACerror.AuthParams.AUTN))));
    //+  UE responds with an AUTHENTICATION FAILURE message, with reject cause "MAC failure" .
    //@siclog "Step 5" siclog@
    SRB.receive(car_SRB1_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_IntegrityProtected_Ciphered,
                                                      cdr_AUTHENTICATION_FAIL_mac)));
    
    
    //+ SS responds nothing and wait for the expiration of T3418.
    //@siclog "Step 6" siclog@
    t_T3418.start;
    t_T3418.timeout;
    
    // The following messages are to be observed on Cell I unless explicitly stated otherwise.
    
    //+  Check: Does the UE transmit an ATTACH REQUEST message including a PDN CONNECTIVITY REQUEST message in the next 30 seconds after T3418 expired?
    //@siclog "Step 7" siclog@
    t_Wait.start;
    alt {
     []  SRB.receive(car_SRB0_RrcPdu_IND(eutra_CellI, cr_RRCConnectionRequest(cr_EstablishmentCause_Any)))
      {
        t_Wait.stop;

       // send RRC Connection Setup on SRB0 (CCCH) and switch on UL grant assignments:
        f_EUTRA_RRC_ConnectionSetup_Def (eutra_CellI, cs_TimingInfo_Now, v_RRC_TI);

       // receive RRC Connection Setup Complete with piggy-backed NAS message on SRB1 (DCCH):
        SRB.receive(car_SRB1_RrcNasPdu_IND(eutra_CellI,
                 cr_508_RRCConnectionSetupComplete(v_RRC_TI, ?),
                 cr_NAS_IndicationWithPiggybacking(tsc_SHT_IntegrityProtected,
                                                   cr_508_ATTACH_REQUEST(v_AttachType, v_AdditionalUpdateType),
                                                   cr_508_PDN_CONNECTIVITY_REQUEST(tsc_PdnRequest_InitialAttach, f_GetPdnType()))));
        f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 7");
      }
     []  t_Wait.timeout
      {
        f_EUTRA_SetVerdictFailOrInconc(__FILE__, __LINE__, "Step 7");
      }
  }
    
    //@siclog "Steps 8 - 19" siclog@
    f_EUTRA_IdleUpdated_Step5_17 (eutra_CellA, STATE2_IDLEUPDATE, NORMAL, v_NasInd, false); // R5-105005
} // function fl_tc_9_1_2_6_EUTRA_Body
  

  ///////////////////////////////////////////////////////////////////////////////
  // TC 9.1.4.2
  ///////////////////////////////////////////////////////////////////////////////
  /*
   * @desc      REFERENCE TS 36.523-1 clause 9.1.4.2
   * @status    APPROVED
   */
  function f_TC_9_1_4_2_EUTRA() runs on EUTRA_PTC
  {
    /// @desc Identification procedure, IMEI requested
    
    // Purpose
    //  with { UE in EMM-REGISTERED state / EMM-CONNECTED mode}
    //  ensure that {
    //    when { UE receives an IDENTITY REQUEST message with IMEI in the IE Identity type }
    //      then { UE sends an IDENTITY RESPONSE message providing its IMEI }
    
    // Pre-test conditions
    // System Simulator:
    //   - Cell A
    //   UE is in state Generic RB established (state 3) on Cell A according to [18].
    
    f_EUTRA_NAS_Init(LTE_AllCellsOnSamePLMN, LTEsinglecell);
    
    // create cell and send out system information
    f_EUTRA_CellConfig_Def (eutra_CellA);
    
    // Preamble:
    //   - UE is in state Generic RB established (state 3) on Cell A
    // ==========================================================================
    f_EUTRA_Preamble(eutra_CellA, STATE2_IDLEUPDATE);
    f_EUTRA_RbEst_Def(eutra_CellA);
    f_EUTRA_TestBody_Set(true);
    
    fl_TC_9_1_4_2_Body();
    
    // Postamble
    f_EUTRA_TestBody_Set(false);
    f_EUTRA_Postamble(eutra_CellA, E2_CONNECTED);//@sic R5-103875 sic@
    
  } // function f_TC_9_1_4_2_EUTRA
  
  
  /*
   * @desc      test body of TC_9_1_4_2
   * @status    APPROVED
   */
  function fl_TC_9_1_4_2_Body() runs on EUTRA_PTC
  {
    
    var template (present) MobileIdentity v_MobIdIMEI := f_Imei2MobileIdentity(px_IMEI_Def); // @sic R5s100092 sic@

    //+   SS transmits an IDENTITY REQUEST message requesting IMEI in the IE Identity type.
    //@siclog "Step 1" siclog@
    SRB.send(cas_SRB2_NasPdu_REQ(eutra_CellA,
                                 cs_TimingInfo_Now,
                                 cs_NAS_Request(tsc_SHT_IntegrityProtected_Ciphered,
                                                cs_IDENTITY_REQUEST(tsc_IdType_IMEI))));
    
    //+   Check: Does the UE respond with an IDENTITY RESPONSE message providing its IMEI? [1,P]
    //@siclog "Step 2" siclog@
    SRB.receive(car_SRB2_NasPdu_IND(eutra_CellA,
                                    cr_NAS_Indication(tsc_SHT_IntegrityProtected_Ciphered,
                                                      cr_IDENTITY_RESPONSE(v_MobIdIMEI))));
    f_EUTRA_PreliminaryPass(__FILE__, __LINE__, "Step 2");
    
  } // function fl_TC_9_1_4_2_Body
  
  
  } // group Testcases

} // module NAS_Authentication
