Authentication.c 41.5 KB
Newer Older
gauthier's avatar
 
gauthier committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*******************************************************************************
    OpenAirInterface
    Copyright(c) 1999 - 2014 Eurecom

    OpenAirInterface is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.


    OpenAirInterface is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with OpenAirInterface.The full GNU General Public License is
   included in this distribution in the file called "COPYING". If not,
   see <http://www.gnu.org/licenses/>.

  Contact Information
  OpenAirInterface Admin: openair_admin@eurecom.fr
  OpenAirInterface Tech : openair_tech@eurecom.fr
24
  OpenAirInterface Dev  : openair4g-devel@lists.eurecom.fr
gauthier's avatar
 
gauthier committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

  Address      : Eurecom, Compus SophiaTech 450, route des chappes, 06451 Biot, France.

 *******************************************************************************/
/*****************************************************************************
Source      Authentication.c

Version     0.1

Date        2013/03/04

Product     NAS stack

Subsystem   EPS Mobility Management

Author      Frederic Maurel

Description Defines the authentication EMM procedure executed by the
        Non-Access Stratum.

        The purpose of the EPS authentication and key agreement (AKA)
        procedure is to provide mutual authentication between the user
        and the network and to agree on a key KASME. The procedure is
        always initiated and controlled by the network. However, the
        UE can reject the EPS authentication challenge sent by the
        network.

        A partial native EPS security context is established in the
        UE and the network when an EPS authentication is successfully
        performed. The computed key material KASME is used as the
        root for the EPS integrity protection and ciphering key
        hierarchy.

*****************************************************************************/

#include <stdlib.h> // malloc, free
#include <string.h> // memcpy, memcmp, memset
#include <arpa/inet.h> // htons

#include "emm_proc.h"
#include "nas_log.h"
#include "nas_timer.h"

#include "emmData.h"

#include "emm_sap.h"
#include "emm_cause.h"

#include "usim_api.h"
#include "secu_defs.h"


/****************************************************************************/
/****************  E X T E R N A L    D E F I N I T I O N S  ****************/
/****************************************************************************/

/*
 * Retransmission timer handlers
 */
extern void *_emm_attach_t3410_handler(void *);
extern void *_emm_service_t3417_handler(void *);
extern void *_emm_detach_t3421_handler(void *);
extern void *_emm_tau_t3430_handler(void *);

89
90
extern uint8_t usim_test;

gauthier's avatar
 
gauthier committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/****************************************************************************/
/*******************  L O C A L    D E F I N I T I O N S  *******************/
/****************************************************************************/

/*
 * --------------------------------------------------------------------------
 *  Internal data handled by the authentication procedure in the UE
 * --------------------------------------------------------------------------
 */
/*
 * Timer handlers
 */
static void *_authentication_t3416_handler(void *);
static void *_authentication_t3418_handler(void *);
static void *_authentication_t3420_handler(void *);

/*
 * Internal data used for authentication procedure
 */
static struct {
  uint8_t rand[AUTH_RAND_SIZE];   /* Random challenge number  */
  uint8_t res[AUTH_RES_SIZE];     /* Authentication response  */
  uint8_t ck[AUTH_CK_SIZE];       /* Ciphering key        */
  uint8_t ik[AUTH_IK_SIZE];       /* Integrity key        */
#define AUTHENTICATION_T3410    0x01
#define AUTHENTICATION_T3417    0x02
#define AUTHENTICATION_T3421    0x04
#define AUTHENTICATION_T3430    0x08
  unsigned char timers;       /* Timer restart bitmap     */
#define AUTHENTICATION_COUNTER_MAX 3
  unsigned char mac_count:2;  /* MAC failure counter (#20)        */
  unsigned char umts_count:2; /* UMTS challenge failure counter (#26) */
  unsigned char sync_count:2; /* Sync failure counter (#21)       */
} _authentication_data;

/*
 * Abnormal case authentication procedure
 */
static int _authentication_abnormal_cases_cde(int emm_cause,
    const OctetString *auts);
static int _authentication_abnormal_case_f(void);

static int _authentication_stop_timers(void);
static int _authentication_start_timers(void);
static int _authentication_kasme(const OctetString *autn,
                                 const OctetString *ck, const OctetString *ik, const plmn_t *plmn,
                                 OctetString *kasme);

/*
 * --------------------------------------------------------------------------
 *  Internal data handled by the authentication procedure in the MME
 * --------------------------------------------------------------------------
 */

/****************************************************************************/
/******************  E X P O R T E D    F U N C T I O N S  ******************/
/****************************************************************************/

/*
 * --------------------------------------------------------------------------
 *      Authentication procedure executed by the UE
 * --------------------------------------------------------------------------
 */
/****************************************************************************
 **                                                                        **
 ** Name:    emm_proc_authentication_request()                         **
 **                                                                        **
 ** Description: Performs the MME requested authentication procedure.      **
 **                                                                        **
 **              3GPP TS 24.301, section 5.4.2.3                           **
 **      Upon receiving the AUTHENTICATION REQUEST message, the UE **
 **      shall store the received RAND together with the RES re-   **
 **      turned from the USIM in the volatile memory of the ME, to **
 **      avoid a synchronisation failure. The UE shall process the **
 **      authentication challenge data and respond with an AUTHEN- **
 **      TICATION RESPONSE message to the network.                 **
 **                                                                        **
 ** Inputs:  native_ksi:    TRUE if the security context is of type    **
 **             native (for KSIASME)                       **
 **      ksi:       The NAS ket sey identifier                 **
 **      rand:      Authentication parameter RAND              **
 **      autn:      Authentication parameter AUTN              **
 **      Others:    _emm_data, _authentication_data            **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    RETURNok, RETURNerror                      **
 **      Others:    _emm_data, _authentication_data, T3416,    **
 **             T3418, T3420                               **
 **                                                                        **
 ***************************************************************************/
int emm_proc_authentication_request(int native_ksi, int ksi,
                                    const OctetString *rand,
                                    const OctetString *autn)
{
  LOG_FUNC_IN;

  int rc = RETURNerror;

  LOG_TRACE(INFO, "EMM-PROC  - Authentication requested ksi type = %s, ksi = %d", native_ksi ? "native" : "mapped", ksi);

  /* 3GPP TS 24.301, section 5.4.2.1
   * The UE shall proceed with an EPS authentication challenge only if a
   * USIM is present
   */
  if (!_emm_data.usim_is_valid) {
    LOG_TRACE(WARNING, "EMM-PROC  - USIM is not present or not valid");
    LOG_FUNC_RETURN (RETURNerror);
  }

  /* Stop timer T3418, if running */
  if (T3418.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3418 (%d)", T3418.id);
    T3418.id = nas_timer_stop(T3418.id);
  }

  /* Stop timer T3420, if running */
  if (T3420.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3420 (%d)", T3420.id);
    T3420.id = nas_timer_stop(T3420.id);
  }

  /* Setup security keys */
  OctetString ck = {AUTH_CK_SIZE, _authentication_data.ck};
  OctetString ik = {AUTH_IK_SIZE, _authentication_data.ik};
  OctetString res = {AUTH_RES_SIZE, _authentication_data.res};

  if (memcmp(_authentication_data.rand, rand->value, AUTH_CK_SIZE) != 0) {
    /*
     * There is no valid stored RAND in the ME or the stored RAND is
     * different from the new received value in the AUTHENTICATION
     * REQUEST message
     */
    OctetString auts;
    auts.length = 0;
    auts.value = (uint8_t *)malloc(AUTH_AUTS_SIZE);

    if (auts.value == NULL) {
      LOG_TRACE(WARNING, "EMM-PROC  - Failed to allocate AUTS parameter");
      LOG_FUNC_RETURN (RETURNerror);
    }

    /* 3GPP TS 33.401, section 6.1.1
     * Get the "separation bit" of the AMF field of AUTN */
    int sbit = AUTH_AMF_SEPARATION_BIT(autn->value[AUTH_AMF_INDEX]);

    if (sbit != 0) {
      /* LW: only 64 bits from the response field are used for the authentication response for this algorithms */
      res.length = 8; /* Bytes */

      /*
       * Perform EPS authentication challenge to check the authenticity
       * of the core network by means of the received AUTN parameter and
       * request the USIM to compute RES, CK and IK for given RAND
       */
245
246
247
248
249
250
251
252
      if(usim_test == 0)
      {
        rc = usim_api_authenticate(rand, autn, &auts, &res, &ck, &ik);
      }
      else
      {
        rc = usim_api_authenticate_test(rand, autn, &auts, &res, &ck, &ik); // XOR algo for autentication on usim test mode
      }
gauthier's avatar
 
gauthier committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
    }

    if (rc != RETURNok) {
      /*
       * Network authentication not accepted by the UE
       */
      LOG_TRACE(WARNING, "EMM-PROC  - Network authentication failed (%s)",
                (auts.length > 0) ? "SQN failure" :
                (sbit == 0) ? "Non-EPS authentication unacceptable" :
                "MAC code failure");
      /* Delete any previously stored RAND and RES and stop timer T3416 */
      (void) emm_proc_authentication_delete();

      /* Proceed authentication abnormal cases procedure */
      if (auts.length > 0) {
        /* 3GPP TS 24.301, section 5.4.2.6, case e
         * SQN failure */
        rc = _authentication_abnormal_cases_cde(
               EMM_CAUSE_SYNCH_FAILURE, &auts);
      } else if (sbit == 0) {
        /* 3GPP TS 24.301, section 5.4.2.6, case d
         * Non-EPS authentication unacceptable */
        rc = _authentication_abnormal_cases_cde(
               EMM_CAUSE_NON_EPS_AUTH_UNACCEPTABLE, NULL);
      } else {
        /* 3GPP TS 24.301, section 5.4.2.6, case c
         * MAC code failure */
        rc = _authentication_abnormal_cases_cde(
               EMM_CAUSE_MAC_FAILURE, NULL);
      }

      /* Free the AUTS parameter */
      free(auts.value);
      LOG_FUNC_RETURN (rc);
    }

    /* Free the AUTS parameter */
    free(auts.value);

    /* Store the new RAND in the volatile memory */
    if (rand->length <= AUTH_RAND_SIZE) {
      memcpy(_authentication_data.rand, rand->value, rand->length);
    }

    /* Start, or reset and restart timer T3416 */
    if (T3416.id != NAS_TIMER_INACTIVE_ID) {
      LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3416 (%d)", T3416.id);
      T3416.id = nas_timer_stop(T3416.id);
    }

    T3416.id = nas_timer_start(T3416.sec, _authentication_t3416_handler, NULL);
    LOG_TRACE(INFO, "EMM-PROC  - Timer T3416 (%d) expires in  %ld seconds",
              T3416.id, T3416.sec);
  }

  /*
   * The stored RAND value is equal to the new received value in the
   * AUTHENTICATION REQUEST message, or the UE has successfully checked
   * the authenticity of the core network
   */
  /* Start any retransmission timers */
  rc = _authentication_start_timers();

  if (rc != RETURNok) {
    LOG_TRACE(WARNING, "EMM-PROC  - Failed to start retransmission timers");
    LOG_FUNC_RETURN (RETURNerror);
  }

  /* Setup EMM procedure handler to be executed upon receiving
   * lower layer notification */
  rc = emm_proc_lowerlayer_initialize(NULL, NULL, NULL, NULL);

  if (rc != RETURNok) {
    LOG_TRACE(WARNING,
              "EMM-PROC  - Failed to initialize EMM procedure handler");
    LOG_FUNC_RETURN (RETURNerror);
  }

  /*
   * Notify EMM-AS SAP that Authentication Response message has to be sent
   * to the network
   */
  emm_sap_t emm_sap;
  emm_sap.primitive = EMMAS_SECURITY_RES;
  emm_sap.u.emm_as.u.security.guti = _emm_data.guti;
  emm_sap.u.emm_as.u.security.ueid = 0;
  emm_sap.u.emm_as.u.security.msgType = EMM_AS_MSG_TYPE_AUTH;
  emm_sap.u.emm_as.u.security.emm_cause = EMM_CAUSE_SUCCESS;
  emm_sap.u.emm_as.u.security.res = &res;
  /* Setup EPS NAS security data */
  emm_as_set_security_data(&emm_sap.u.emm_as.u.security.sctx,
                           _emm_data.security, FALSE, TRUE);
  rc = emm_sap_send(&emm_sap);

  if (rc != RETURNerror) {
    /* Reset the authentication failure counters */
    _authentication_data.mac_count = 0;
    _authentication_data.umts_count = 0;
    _authentication_data.sync_count = 0;

    /* Create non-current EPS security context */
    if (_emm_data.non_current == NULL) {
      _emm_data.non_current =
        (emm_security_context_t *)malloc(sizeof(emm_security_context_t));
    }

    if (_emm_data.non_current) {
      memset(_emm_data.non_current, 0, sizeof(emm_security_context_t));

      /* Set the security context type */
      if (native_ksi) {
        _emm_data.non_current->type = EMM_KSI_NATIVE;
      } else {
        _emm_data.non_current->type = EMM_KSI_MAPPED;
      }

      /* Set the EPS key set identifier */
      _emm_data.non_current->eksi = ksi;
      /* Derive the Kasme from the authentication challenge using
       * the PLMN identity of the selected PLMN */
      _emm_data.non_current->kasme.length = AUTH_KASME_SIZE;
      _emm_data.non_current->kasme.value  = malloc(32);
      _authentication_kasme(autn, &ck, &ik, &_emm_data.splmn,
                            &_emm_data.non_current->kasme);
      /* NAS integrity and cyphering keys are not yet available */
    }
  }

  LOG_FUNC_RETURN (rc);
}

/****************************************************************************
 **                                                                        **
 ** Name:    emm_proc_authentication_reject()                          **
 **                                                                        **
 ** Description: Performs the authentication procedure not accepted by the **
 **      network.                                                  **
 **                                                                        **
 **              3GPP TS 24.301, section 5.4.2.5                           **
 **      Upon receiving an AUTHENTICATION REJECT message, the UE   **
 **      shall abort any EMM signalling procedure, stop any of the **
 **      timers T3410, T3417 or T3430 (if running) and enter state **
 **      EMM-DEREGISTERED.                                         **
 **                                                                        **
 ** Inputs:  None                                                      **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    RETURNok, RETURNerror                      **
 **      Others:    _emm_data, _authentication_data, T3410,    **
 **             T3417, T3430                               **
 **                                                                        **
 ***************************************************************************/
int emm_proc_authentication_reject(void)
{
  LOG_FUNC_IN;

  emm_sap_t emm_sap;
  int rc;

  LOG_TRACE(WARNING, "EMM-PROC  - Authentication not accepted by the network");

  /* Delete any previously stored RAND and RES and stop timer T3416 */
  (void) emm_proc_authentication_delete();

  /* Set the EPS update status to EU3 ROAMING NOT ALLOWED */
  _emm_data.status = EU3_ROAMING_NOT_ALLOWED;
  /* Delete the stored GUTI */
  _emm_data.guti = NULL;
  /* Delete the TAI list */
  _emm_data.ltai.n_tais = 0;
  /* Delete the last visited registered TAI */
  _emm_data.tai = NULL;

  /* Delete the eKSI */
  if (_emm_data.security) {
    _emm_data.security->type = EMM_KSI_NOT_AVAILABLE;
  }

  /* Consider the USIM invalid */
  _emm_data.usim_is_valid = FALSE;

  /* Stop timer T3410 */
  if (T3410.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3410 (%d)", T3410.id);
    T3410.id = nas_timer_stop(T3410.id);
  }

  /* Stop timer T3417 */
  if (T3417.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3417 (%d)", T3417.id);
    T3417.id = nas_timer_stop(T3417.id);
  }

  /* Stop timer T3430 */
  if (T3430.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3430 (%d)", T3430.id);
    T3430.id = nas_timer_stop(T3430.id);
  }

  /* Abort any EMM signalling procedure (prevent the retransmission timers to
   * be restarted) */
  _authentication_data.timers = 0x00;

  /*
   * Notify EMM that authentication is not accepted by the network
   */
  emm_sap.primitive = EMMREG_AUTH_REJ;
  rc = emm_sap_send(&emm_sap);

  LOG_FUNC_RETURN (rc);
}

/****************************************************************************
 **                                                                        **
 ** Name:    emm_proc_authentication_delete()                          **
 **                                                                        **
 ** Description: Deletes the RAND and RES values stored into the volatile  **
 **      memory of the Mobile Equipment and stop timer T3416, if   **
 **      running, upon receipt of a SECURITY MODE COMMAND, SERVICE **
 **      REJECT, TRACKING AREA UPDATE REJECT, TRACKING AREA UPDATE **
 **      ACCEPT or AUTHENTICATION REJECT message; upon expiry of   **
 **      timer  T3416; or if the UE  enters  the  EMM  state  EMM- **
 **      DEREGISTERED or EMM-NULL.                                 **
 **                                                                        **
 **              3GPP TS 24.301, section 5.4.2.3                           **
 **                                                                        **
 ** Inputs:  None                                                      **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    RETURNok, RETURNerror                      **
 **      Others:    _authentication_data, T3416                **
 **                                                                        **
 ***************************************************************************/
int emm_proc_authentication_delete(void)
{
  LOG_FUNC_IN;

  LOG_TRACE(INFO, "EMM-PROC  - Delete authentication data RAND and RES");

  /* Stop timer T3416, if running */
  if (T3416.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3416 (%d)", T3416.id);
    T3416.id = nas_timer_stop(T3416.id);
  }

  /* Delete any previously stored RAND and RES */
  memset(_authentication_data.rand, 0, AUTH_RAND_SIZE);
  memset(_authentication_data.res, 0, AUTH_RES_SIZE);

  LOG_FUNC_RETURN (RETURNok);
}


/****************************************************************************/
/*********************  L O C A L    F U N C T I O N S  *********************/
/****************************************************************************/

/*
 * --------------------------------------------------------------------------
 *              Timer handlers
 * --------------------------------------------------------------------------
 */

/****************************************************************************
 **                                                                        **
 ** Name:    _authentication_t3416_handler()                           **
 **                                                                        **
 ** Description: T3416 timeout handler                                     **
 **      Upon T3416 timer expiration, the RAND and RES values sto- **
 **      red in the ME shall be deleted.                           **
 **                                                                        **
 **              3GPP TS 24.301, section 5.4.2.3                           **
 **                                                                        **
 ** Inputs:  args:      handler parameters                         **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    None                                       **
 **      Others:    T3416                                      **
 **                                                                        **
 ***************************************************************************/
static void *_authentication_t3416_handler(void *args)
{
  LOG_FUNC_IN;

  LOG_TRACE(WARNING, "EMM-PROC  - T3416 timer expired");

  /* Stop timer T3416 */
  T3416.id = nas_timer_stop(T3416.id);
  /* Delete previouly stored RAND and RES authentication data */
  (void) emm_proc_authentication_delete();

  LOG_FUNC_RETURN (NULL);
}

/****************************************************************************
 **                                                                        **
 ** Name:    _authentication_t3418_handler()                           **
 **                                                                        **
 ** Description: T3418 timeout handler                                     **
 **      Upon T3418 timer expiration, the UE shall deem that the   **
 **      source of the  authentication  challenge is not  genuine  **
 **      (authentication not accepted by the UE).                  **
 **                                                                        **
 **              3GPP TS 24.301, section 5.4.2.7, case c                   **
 **                                                                        **
 ** Inputs:  args:      handler parameters                         **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    None                                       **
 **      Others:    _authentication_data, T3418                **
 **                                                                        **
 ***************************************************************************/
static void *_authentication_t3418_handler(void *args)
{
  LOG_FUNC_IN;

  int rc;

  LOG_TRACE(WARNING, "EMM-PROC  - T3418 timer expired");

  /* Stop timer T3418 */
  T3418.id = nas_timer_stop(T3418.id);
  /* Reset the MAC failure and UMTS challenge failure counters */
  _authentication_data.mac_count = 0;
  _authentication_data.umts_count = 0;
  /* 3GPP TS 24.301, section 5.4.2.7, case f */
  rc = _authentication_abnormal_case_f();

  if (rc != RETURNok) {
    LOG_TRACE(WARNING, "EMM-PROC  - Failed to proceed abnormal case f");
  }

  LOG_FUNC_RETURN (NULL);
}

/****************************************************************************
 **                                                                        **
 ** Name:    _authentication_t3420_handler()                           **
 **                                                                        **
 ** Description: T3420 timeout handler                                     **
 **      Upon T3420 timer expiration, the UE shall deem that the   **
 **      network has failed the authentication check.              **
 **                                                                        **
 **              3GPP TS 24.301, section 5.4.2.7, case e                   **
 **                                                                        **
 ** Inputs:  args:      handler parameters                         **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    None                                       **
 **      Others:    _authentication_data, T3420                **
 **                                                                        **
 ***************************************************************************/
static void *_authentication_t3420_handler(void *args)
{
  LOG_FUNC_IN;

  int rc;

  LOG_TRACE(WARNING, "EMM-PROC  - T3420 timer expired");

  /* Stop timer T3420 */
  T3420.id = nas_timer_stop(T3420.id);
  /* Reset the sync failure counter */
  _authentication_data.sync_count = 0;
  /* 3GPP TS 24.301, section 5.4.2.7, case f */
  rc = _authentication_abnormal_case_f();

  if (rc != RETURNok) {
    LOG_TRACE(WARNING, "EMM-PROC  - Failed to proceed abnormal case f");
  }

  LOG_FUNC_RETURN (NULL);
}

/*
 * --------------------------------------------------------------------------
 *              Abnormal cases in the UE
 * --------------------------------------------------------------------------
 */

/****************************************************************************
 **                                                                        **
 ** Name:    _authentication_abnormal_cases_cde()                      **
 **                                                                        **
 ** Description: Performs the abnormal case authentication procedure.      **
 **                                                                        **
 **      3GPP TS 24.301, section 5.4.2.7, cases c, d and e         **
 **                                                                        **
 ** Inputs:  emm_cause: EMM cause code                             **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    RETURNok, RETURNerror                      **
 **      Others:    _authentication_data, T3418, T3420         **
 **                                                                        **
 ***************************************************************************/
static int _authentication_abnormal_cases_cde(int emm_cause,
    const OctetString *auts)
{
  LOG_FUNC_IN;

  int rc;

  LOG_TRACE(WARNING, "EMM-PROC  - "
            "Abnormal case, authentication counters c/d/e = %d/%d/%d",
            _authentication_data.mac_count, _authentication_data.umts_count,
            _authentication_data.sync_count);

  /*
   * Notify EMM-AS SAP that Authentication Failure message has to be sent
   * to the network
   */
  emm_sap_t emm_sap;
  emm_sap.primitive = EMMAS_SECURITY_RES;
  emm_sap.u.emm_as.u.security.guti = _emm_data.guti;
  emm_sap.u.emm_as.u.security.ueid = 0;
  emm_sap.u.emm_as.u.security.msgType = EMM_AS_MSG_TYPE_AUTH;
  emm_sap.u.emm_as.u.security.emm_cause = emm_cause;
  emm_sap.u.emm_as.u.security.auts = auts;
  /* Setup EPS NAS security data */
  emm_as_set_security_data(&emm_sap.u.emm_as.u.security.sctx,
                           _emm_data.security, FALSE, TRUE);
  rc = emm_sap_send(&emm_sap);

  if (rc != RETURNerror) {
    /*
     * Update the authentication failure counters
     */
    switch (emm_cause) {
    case EMM_CAUSE_MAC_FAILURE:
      /* 3GPP TS 24.301, section 5.4.2.6, case c
       * Update the MAC failure counter */
      _authentication_data.mac_count += 1;
      /* Start timer T3418 */
      T3418.id = nas_timer_start(T3418.sec,
                                 _authentication_t3418_handler, NULL);
      LOG_TRACE(INFO,"EMM-PROC  - Timer T3418 (%d) expires in "
                "%ld seconds", T3418.id, T3418.sec);
      break;

    case EMM_CAUSE_NON_EPS_AUTH_UNACCEPTABLE:
      /* 3GPP TS 24.301, section 5.4.2.6, case d
       * Update the UMTS challenge failure counter */
      _authentication_data.umts_count += 1;
      /* Start timer T3418 */
      T3418.id = nas_timer_start(T3418.sec,
                                 _authentication_t3418_handler, NULL);
      LOG_TRACE(INFO,"EMM-PROC  - Timer T3418 (%d) expires in "
                "%ld seconds", T3418.id, T3418.sec);
      break;

    case EMM_CAUSE_SYNCH_FAILURE:
      /* 3GPP TS 24.301, section 5.4.2.6, case e
       * Update the synch failure counter */
      _authentication_data.sync_count += 1;
      /* Start timer T3420 */
      T3420.id = nas_timer_start(T3420.sec,
                                 _authentication_t3420_handler, NULL);
      LOG_TRACE(INFO,"EMM-PROC  - Timer T3420 (%d) expires in "
                "%ld seconds", T3420.id, T3420.sec);
      break;

    default:
      LOG_TRACE(WARNING, "EMM cause code is not valid (%d)",
                emm_cause);
      LOG_FUNC_RETURN (RETURNerror);
    }

    /*
     * Stop any retransmission timers that are running
     */
    rc = _authentication_stop_timers();

    if (rc != RETURNok) {
      LOG_TRACE(WARNING, "EMM-PROC  - "
                "Failed to stop retransmission timers");
      LOG_FUNC_RETURN (RETURNerror);
    }

    /*
     * Check whether the network has failed the authentication check
     */
    int failure_counter = 0;

    if (emm_cause == EMM_CAUSE_MAC_FAILURE) {
      failure_counter = _authentication_data.mac_count
                        + _authentication_data.sync_count;
    } else if (emm_cause == EMM_CAUSE_SYNCH_FAILURE) {
      failure_counter = _authentication_data.mac_count
                        + _authentication_data.umts_count
                        + _authentication_data.sync_count;
    }

    if (failure_counter >= AUTHENTICATION_COUNTER_MAX) {
      /* 3GPP TS 24.301, section 5.4.2.6, case f */
      rc = _authentication_abnormal_case_f();

      if (rc != RETURNok) {
        LOG_TRACE(WARNING, "EMM-PROC  - "
                  "Failed to proceed abnormal case f");
      }
    }
  }

  LOG_FUNC_RETURN (rc);
}

/****************************************************************************
 **                                                                        **
 ** Name:    _authentication_abnormal_case_f()                         **
 **                                                                        **
 ** Description: Performs the abnormal case authentication procedure.      **
 **                                                                        **
 **      3GPP TS 24.301, section 5.4.2.7, case f                   **
 **                                                                        **
 ** Inputs:  None                                                      **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    RETURNok, RETURNerror                      **
 **      Others:    None                                       **
 **                                                                        **
 ***************************************************************************/
static int _authentication_abnormal_case_f(void)
{
  LOG_FUNC_IN;

  int rc;

  LOG_TRACE(WARNING, "EMM-PROC  - Authentication abnormal case f");

  /*
   * Request RRC to locally release the RRC connection and treat
   * the active cell as barred
   */
  emm_sap_t emm_sap;
  emm_sap.primitive = EMMAS_RELEASE_REQ;
  emm_sap.u.emm_as.u.release.guti = _emm_data.guti;
  emm_sap.u.emm_as.u.release.cause = EMM_AS_CAUSE_AUTHENTICATION;
  rc = emm_sap_send(&emm_sap);

  if (rc != RETURNerror) {
    /* Start any retransmission timers (e.g. T3410, T3417, T3421 or
     * T3430), if they were running and stopped when the UE received
     * the first AUTHENTICATION REQUEST message containing an invalid
     * MAC or SQN */
    rc = _authentication_start_timers();
  }

  LOG_FUNC_RETURN (rc);
}

/*
 * --------------------------------------------------------------------------
 *              UE specific local functions
 * --------------------------------------------------------------------------
 */

/****************************************************************************
 **                                                                        **
 ** Name:    _authentication_stop_timers()                             **
 **                                                                        **
 ** Description: Stops any retransmission timers (e.g. T3410, T3417, T3421 **
 **      or T3430) that are running                                **
 **                                                                        **
 ** Inputs:  None                                                      **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    RETURNok, RETURNerror                      **
 **      Others:    _authentication_data, T3410, T3417, T3421, **
 **             T3430                                      **
 **                                                                        **
 ***************************************************************************/
static int _authentication_stop_timers(void)
{
  LOG_FUNC_IN;

  /* Stop attach timer */
  if (T3410.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3410 (%d)", T3410.id);
    T3410.id = nas_timer_stop(T3410.id);
    _authentication_data.timers |= AUTHENTICATION_T3410;
  }

  /* Stop service request timer */
  if (T3417.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3417 (%d)", T3417.id);
    T3417.id = nas_timer_stop(T3417.id);
    _authentication_data.timers |= AUTHENTICATION_T3417;
  }

  /* Stop detach timer */
  if (T3421.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3421 (%d)", T3421.id);
    T3421.id = nas_timer_stop(T3421.id);
    _authentication_data.timers |= AUTHENTICATION_T3421;
  }

  /* Stop tracking area update timer */
  if (T3430.id != NAS_TIMER_INACTIVE_ID) {
    LOG_TRACE(INFO, "EMM-PROC  - Stop timer T3430 (%d)", T3430.id);
    T3430.id = nas_timer_stop(T3430.id);
    _authentication_data.timers |= AUTHENTICATION_T3430;
  }

  LOG_FUNC_RETURN (RETURNok);
}

/****************************************************************************
 **                                                                        **
 ** Name:    _authentication_start_timers()                            **
 **                                                                        **
 ** Description: Starts any retransmission timers (e.g. T3410, T3417,      **
 **      T3421 or T3430), if they were running and stopped when    **
 **      the UE received the first AUTHENTICATION REQUEST message  **
 **      containing an invalid MAC or SQN                          **
 **                                                                        **
 **      3GPP TS 24.301, section 5.4.2.7, case f                   **
 **                                                                        **
 ** Inputs:  None                                                      **
 **      Others:    _authentication_data                       **
 **                                                                        **
 ** Outputs:     None                                                      **
 **      Return:    RETURNok, RETURNerror                      **
 **      Others:    T3410, T3417, T3421, T3430                 **
 **                                                                        **
 ***************************************************************************/
static int _authentication_start_timers(void)
{
  LOG_FUNC_IN;

  if (_authentication_data.timers & AUTHENTICATION_T3410) {
    /* Start attach timer */
    T3410.id = nas_timer_start(T3410.sec, _emm_attach_t3410_handler, NULL);
    LOG_TRACE(INFO,"EMM-PROC  - Timer T3410 (%d) expires in "
              "%ld seconds", T3410.id, T3410.sec);
  }

  if (_authentication_data.timers & AUTHENTICATION_T3417) {
    /* Start service request timer */
    T3417.id = nas_timer_start(T3417.sec, _emm_service_t3417_handler, NULL);
    LOG_TRACE(INFO,"EMM-PROC  - Timer T3417 (%d) expires in "
              "%ld seconds", T3417.id, T3417.sec);
  }

  if (_authentication_data.timers & AUTHENTICATION_T3421) {
    /* Start detach timer */
    T3421.id = nas_timer_start(T3421.sec, _emm_detach_t3421_handler, NULL);
    LOG_TRACE(INFO,"EMM-PROC  - Timer T3421 (%d) expires in "
              "%ld seconds", T3421.id, T3421.sec);
  }

  if (_authentication_data.timers & AUTHENTICATION_T3430) {
    /* Start tracking area update timer */
    T3430.id = nas_timer_start(T3430.sec, _emm_tau_t3430_handler, NULL);
    LOG_TRACE(INFO,"EMM-PROC  - Timer T3430 (%d) expires in "
              "%ld seconds", T3430.id, T3430.sec);
  }

  LOG_FUNC_RETURN (RETURNok);
}

/****************************************************************************
 **                                                                        **
 ** Name:    _authentication_kasme()                                   **
 **                                                                        **
 ** Description: Computes the Key Access Security Management Entity Kasme  **
 **      from the provided authentication challenge data.          **
 **                                                                        **
 **              3GPP TS 33.401, Annex A.2                                 **
 **                                                                        **
 ** Inputs:  autn:      Authentication token                       **
 **      ck:        Cipherig key                               **
 **      ik:        Integrity key                              **
 **      plmn:      Identifier of the currently selected PLMN  **
 **      Others:    None                                       **
 **                                                                        **
 ** Outputs:     kasme:     Key Access Security Management Entity      **
 **      Return:    RETURNok, RETURNerror                      **
 **      Others:    None                                       **
 **                                                                        **
 ***************************************************************************/
static int _authentication_kasme(const OctetString *autn,
                                 const OctetString *ck, const OctetString *ik,
                                 const plmn_t *plmn, OctetString *kasme)
{
  LOG_FUNC_IN;

  LOG_TRACE(INFO,"EMM-PROC  _authentication_kasme INPUT CK %s",
            dump_octet_string(ck));
  LOG_TRACE(INFO,"EMM-PROC  _authentication_kasme INPUT IK %s",
            dump_octet_string(ik));
  LOG_TRACE(INFO,"EMM-PROC  _authentication_kasme INPUT AUTN %s",
            dump_octet_string(autn));
  LOG_TRACE(INFO,"EMM-PROC  _authentication_kasme INPUT KASME LENGTH %u",
            kasme->length);

  /* Compute the derivation key KEY = CK || IK */
957
  uint8_t key[ck->length + ik->length];
gauthier's avatar
 
gauthier committed
958
959
960
961
962
963
  memcpy(key, ck->value, ck->length);
  memcpy(key + ck->length, ik->value, ik->length);

  /* Compute the KDF input_s parameter
   * S = FC(0x10) || SNid(MCC, MNC) || 0x00 0x03 || SQN ⊕ AK || 0x00 0x06
   */
964
965
966
  uint8_t  input_s[16]; // less than 16
  uint8_t  sn_id[AUTH_SNID_SIZE]; // less than 16
  uint16_t length;
gauthier's avatar
 
gauthier committed
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
  int      offset         = 0;
  int      size_of_length = sizeof(length);

  // FC
  input_s[offset] = 0x10;
  offset       += 1;

  // P0=SN id
  length        = AUTH_SNID_SIZE;
  sn_id[0] = (plmn->MCCdigit2 << 4) | plmn->MCCdigit1;
  sn_id[1] = (plmn->MNCdigit3 << 4) | plmn->MCCdigit3;
  sn_id[2] = (plmn->MNCdigit2 << 4) | plmn->MNCdigit1;

  memcpy(input_s + offset, sn_id, length);
  LOG_TRACE(INFO,"EMM-PROC  _authentication_kasme P0 MCC,MNC %02X %02X %02X",
            input_s[offset],
            input_s[offset+1],
            input_s[offset+2]);
  offset += length;
  // L0=SN id length
  length = htons(length);
  memcpy(input_s + offset, &length, size_of_length);
  offset += size_of_length;

  // P1=Authentication token
  length = AUTH_SQN_SIZE;
  memcpy(input_s + offset, autn->value, length);
  offset += length;
  // L1
  length = htons(length);
  memcpy(input_s + offset, &length, size_of_length);
  offset += size_of_length;

  LOG_TRACE(INFO,
            "EMM-PROC  _authentication_kasme input S to KFD (length %u)%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X",
            offset,
            input_s[0],input_s[1],input_s[2],input_s[3],
            input_s[4],input_s[5],input_s[6],input_s[7],
            input_s[8],input_s[9],input_s[10],input_s[11],
            input_s[12],input_s[13]);
  /* TODO !!! Compute the Kasme key */
  // todo_hmac_256(key, input_s, kasme->value);
  kdf(key,
      ck->length + ik->length , /*key_length*/
      input_s,
      offset,
      kasme->value,
      kasme->length);

  LOG_TRACE(INFO,"EMM-PROC  KASME (l=%d)%s",
            kasme->length,
            dump_octet_string(kasme));

  LOG_FUNC_RETURN (RETURNok);
}