aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/internal/net/eap/statemachine/EapAkaPrimeMethodStateMachine.java
blob: d2e8ba25cf66d86919422bdab7907822d9eb1534 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
89
90
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
245
246
247
248
249
250
251
252
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
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.net.eap.statemachine;

import static com.android.internal.net.eap.EapAuthenticator.LOG;
import static com.android.internal.net.eap.message.EapData.EAP_TYPE_AKA_PRIME;
import static com.android.internal.net.eap.message.simaka.EapAkaTypeData.EAP_AKA_CLIENT_ERROR;
import static com.android.internal.net.eap.message.simaka.EapSimAkaAttribute.EAP_AT_AUTN;
import static com.android.internal.net.eap.message.simaka.EapSimAkaAttribute.EAP_AT_KDF;
import static com.android.internal.net.eap.message.simaka.EapSimAkaAttribute.EAP_AT_KDF_INPUT;

import android.annotation.Nullable;
import android.content.Context;
import android.net.eap.EapSessionConfig.EapAkaPrimeConfig;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.net.crypto.KeyGenerationUtils;
import com.android.internal.net.eap.EapResult;
import com.android.internal.net.eap.crypto.HmacSha256ByteSigner;
import com.android.internal.net.eap.message.EapData.EapMethod;
import com.android.internal.net.eap.message.EapMessage;
import com.android.internal.net.eap.message.simaka.EapAkaPrimeTypeData;
import com.android.internal.net.eap.message.simaka.EapAkaPrimeTypeData.EapAkaPrimeTypeDataDecoder;
import com.android.internal.net.eap.message.simaka.EapAkaTypeData;
import com.android.internal.net.eap.message.simaka.EapSimAkaAttribute;
import com.android.internal.net.eap.message.simaka.EapSimAkaAttribute.AtAutn;
import com.android.internal.net.eap.message.simaka.EapSimAkaAttribute.AtClientErrorCode;
import com.android.internal.net.eap.message.simaka.EapSimAkaAttribute.AtKdf;
import com.android.internal.net.eap.message.simaka.EapSimAkaAttribute.AtKdfInput;
import com.android.internal.net.eap.message.simaka.EapSimAkaTypeData.DecodeResult;

import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * EapAkaPrimeMethodStateMachine represents the valid paths possible for the EAP-AKA' protocol.
 *
 * <p>EAP-AKA' sessions will always follow the path:
 *
 * Created --+--> Identity --+--> Challenge  --> Final
 *           |               |
 *           +---------------+
 *
 * <p>Note: If the EAP-Request/AKA'-Challenge message contains an AUTN with an invalid sequence
 * number, the peer will indicate a synchronization failure to the server and a new challenge will
 * be attempted.
 *
 * <p>Note: EAP-Request/Notification messages can be received at any point in the above state
 * machine At most one EAP-AKA'/Notification message is allowed per EAP-AKA' session.
 *
 * @see <a href="https://tools.ietf.org/html/rfc4187">RFC 4187, Extensible Authentication Protocol
 *     for Authentication and Key Agreement (EAP-AKA)</a>
 * @see <a href="https://tools.ietf.org/html/rfc5448">RFC 5448, Improved Extensible Authentication
 *     Protocol Method for 3rd Generation Authentication and Key Agreement (EAP-AKA')</a>
 */
public class EapAkaPrimeMethodStateMachine extends EapAkaMethodStateMachine {
    public static final int K_AUT_LEN = 32;
    public static final int K_RE_LEN = 32;

    // EAP-AKA' identity prefix (RFC 5448#3)
    private static final String AKA_PRIME_IDENTITY_PREFIX = "6";
    private static final int SUPPORTED_KDF = 1;
    private static final int FC = 0x20; // Required by TS 133 402 Annex A.2
    private static final int SQN_XOR_AK_LEN = 6;
    private static final String MAC_ALGORITHM_STRING = "HmacSHA256";
    private static final String MK_DATA_PREFIX = "EAP-AKA'";

    // MK_LEN_BYTES = len(K_encr | K_aut | K_re | MSK | EMSK)
    private static final int MK_LEN_BYTES =
            KEY_LEN + K_AUT_LEN + K_RE_LEN + (2 * SESSION_KEY_LENGTH);

    public final byte[] mKRe = new byte[getKReLen()];

    private final EapAkaPrimeConfig mEapAkaPrimeConfig;
    private final EapAkaPrimeTypeDataDecoder mEapAkaPrimeTypeDataDecoder;

    EapAkaPrimeMethodStateMachine(
            Context context, byte[] eapIdentity, EapAkaPrimeConfig eapAkaPrimeConfig) {
        this(
                context,
                eapIdentity,
                eapAkaPrimeConfig,
                EapAkaPrimeTypeData.getEapAkaPrimeTypeDataDecoder());
    }

    @VisibleForTesting
    protected EapAkaPrimeMethodStateMachine(
            Context context,
            byte[] eapIdentity,
            EapAkaPrimeConfig eapAkaPrimeConfig,
            EapAkaPrimeTypeDataDecoder eapAkaPrimeTypeDataDecoder) {
        super(context, eapIdentity, eapAkaPrimeConfig);
        mEapAkaPrimeConfig = eapAkaPrimeConfig;
        mEapAkaPrimeTypeDataDecoder = eapAkaPrimeTypeDataDecoder;

        transitionTo(new CreatedState());
    }

    @Override
    @EapMethod
    int getEapMethod() {
        return EAP_TYPE_AKA_PRIME;
    }

    @Override
    protected int getKAutLength() {
        return K_AUT_LEN;
    }

    protected int getKReLen() {
        return K_RE_LEN;
    }

    @Override
    protected DecodeResult<EapAkaTypeData> decode(byte[] typeData) {
        return mEapAkaPrimeTypeDataDecoder.decode(typeData);
    }

    @Override
    protected String getIdentityPrefix() {
        return AKA_PRIME_IDENTITY_PREFIX;
    }

    @Override
    protected ChallengeState buildChallengeState() {
        return new ChallengeState();
    }

    @Override
    protected ChallengeState buildChallengeState(byte[] identity) {
        return new ChallengeState(identity);
    }

    @Override
    protected String getMacAlgorithm() {
        return MAC_ALGORITHM_STRING;
    }

    protected class ChallengeState extends EapAkaMethodStateMachine.ChallengeState {
        private final String mTAG = ChallengeState.class.getSimpleName();

        ChallengeState() {
            super();
        }

        ChallengeState(byte[] identity) {
            super(identity);
        }

        @Override
        protected EapResult handleChallengeAuthentication(
                EapMessage message, EapAkaTypeData eapAkaTypeData) {
            EapAkaPrimeTypeData eapAkaPrimeTypeData = (EapAkaPrimeTypeData) eapAkaTypeData;

            if (!isValidChallengeAttributes(eapAkaPrimeTypeData)) {
                return buildAuthenticationRejectMessage(message.eapIdentifier);
            }
            return super.handleChallengeAuthentication(message, eapAkaPrimeTypeData);
        }

        @VisibleForTesting
        boolean isValidChallengeAttributes(EapAkaPrimeTypeData eapAkaPrimeTypeData) {
            Map<Integer, EapSimAkaAttribute> attrs = eapAkaPrimeTypeData.attributeMap;

            if (!attrs.containsKey(EAP_AT_KDF) || !attrs.containsKey(EAP_AT_KDF_INPUT)) {
                return false;
            }

            // TODO(b/143073851): implement KDF resolution specified in RFC 5448#3.2
            // This is safe, as there only exists one defined KDF.
            AtKdf atKdf = (AtKdf) attrs.get(EAP_AT_KDF);
            if (atKdf.kdf != SUPPORTED_KDF) {
                return false;
            }

            AtKdfInput atKdfInput = (AtKdfInput) attrs.get(EAP_AT_KDF_INPUT);
            if (atKdfInput.networkName.length == 0) {
                return false;
            }

            boolean hasMatchingNetworkNames =
                    hasMatchingNetworkNames(
                            mEapAkaPrimeConfig.networkName,
                            new String(atKdfInput.networkName, StandardCharsets.UTF_8));
            return mEapAkaPrimeConfig.allowMismatchedNetworkNames || hasMatchingNetworkNames;
        }

        /**
         * Compares the peer's network name against the server's network name.
         *
         * <p>RFC 5448#3.1 describes how the network names are to be compared: "each name is broken
         * down to the fields separated by colons. If one of the names has more colons and fields
         * than the other one, the additional fields are ignored. The remaining sequences of fields
         * are compared. This algorithm allows a prefix match".
         *
         * @return true iff one network name matches the other, as defined by RC 5448#3.1
         */
        @VisibleForTesting
        boolean hasMatchingNetworkNames(String peerNetworkName, String serverNetworkName) {
            // compare network names according to RFC 5448#3.1
            if (peerNetworkName.isEmpty() || serverNetworkName.isEmpty()) {
                return true;
            }

            String[] peerNetworkNameFields = peerNetworkName.split(":");
            String[] serverNetworkNameFields = serverNetworkName.split(":");
            int numFieldsToCompare =
                    Math.min(peerNetworkNameFields.length, serverNetworkNameFields.length);
            for (int i = 0; i < numFieldsToCompare; i++) {
                if (!peerNetworkNameFields[i].equals(serverNetworkNameFields[i])) {
                    LOG.i(
                            mTAG,
                            "EAP-AKA' network names don't match."
                                    + " Peer: " + LOG.pii(peerNetworkName)
                                    + ", Server: " + LOG.pii(serverNetworkName));
                    return false;
                }
            }

            return true;
        }

        @Nullable
        @Override
        protected EapResult generateAndPersistEapAkaKeys(
                RandChallengeResult result, int eapIdentifier, EapAkaTypeData eapAkaTypeData) {
            try {
                AtKdfInput atKdfInput =
                        (AtKdfInput) eapAkaTypeData.attributeMap.get(EAP_AT_KDF_INPUT);
                AtAutn atAutn = (AtAutn) eapAkaTypeData.attributeMap.get(EAP_AT_AUTN);
                byte[] ckIkPrime = deriveCkIkPrime(result, atKdfInput, atAutn);

                int dataToSignLen = MK_DATA_PREFIX.length() + mIdentity.length;
                ByteBuffer dataToSign = ByteBuffer.allocate(dataToSignLen);
                dataToSign.put(MK_DATA_PREFIX.getBytes(StandardCharsets.US_ASCII));
                dataToSign.put(mIdentity);

                ByteBuffer mk =
                        ByteBuffer.wrap(
                                KeyGenerationUtils.prfPlus(
                                        HmacSha256ByteSigner.getInstance(),
                                        ckIkPrime,
                                        dataToSign.array(),
                                        MK_LEN_BYTES));

                mk.get(mKEncr);
                mk.get(mKAut);
                mk.get(mKRe);
                mk.get(mMsk);
                mk.get(mEmsk);

                // Log as hash unless PII debug mode enabled
                LOG.d(mTAG, "K_encr=" + LOG.pii(mKEncr));
                LOG.d(mTAG, "K_aut=" + LOG.pii(mKAut));
                LOG.d(mTAG, "K_re=" + LOG.pii(mKRe));
                LOG.d(mTAG, "MSK=" + LOG.pii(mMsk));
                LOG.d(mTAG, "EMSK=" + LOG.pii(mEmsk));
                return null;
            } catch (GeneralSecurityException
                    | BufferOverflowException
                    | BufferUnderflowException ex) {
                LOG.e(mTAG, "Error while generating keys", ex);
                return buildClientErrorResponse(
                        eapIdentifier, getEapMethod(), AtClientErrorCode.UNABLE_TO_PROCESS);
            }
        }

        /**
         * Derives CK' and IK' values from CK and IK
         *
         * <p>CK' and IK' generation is specified in TS 133 402 Annex A.2, which relies on the key
         * derivation function KDF specified in TS 133 220 Annex B.2.
         */
        @VisibleForTesting
        byte[] deriveCkIkPrime(
                RandChallengeResult randChallengeResult, AtKdfInput atKdfInput, AtAutn atAutn)
                throws GeneralSecurityException {
            final int fcLen = 1;
            int lengthFieldLen = 2;

            // SQN ^ AK is the first 6B of the AUTN value
            byte[] sqnXorAk = Arrays.copyOf(atAutn.autn, SQN_XOR_AK_LEN);
            int sLength =
                    fcLen
                            + atKdfInput.networkName.length + lengthFieldLen
                            + SQN_XOR_AK_LEN + lengthFieldLen;

            ByteBuffer dataToSign = ByteBuffer.allocate(sLength);
            dataToSign.put((byte) FC);
            dataToSign.put(atKdfInput.networkName);
            dataToSign.putShort((short) atKdfInput.networkName.length);
            dataToSign.put(sqnXorAk);
            dataToSign.putShort((short) SQN_XOR_AK_LEN);

            int keyLen = randChallengeResult.ck.length + randChallengeResult.ik.length;
            ByteBuffer key = ByteBuffer.allocate(keyLen);
            key.put(randChallengeResult.ck);
            key.put(randChallengeResult.ik);

            Mac mac = Mac.getInstance(MAC_ALGORITHM_STRING);
            mac.init(new SecretKeySpec(key.array(), MAC_ALGORITHM_STRING));
            return mac.doFinal(dataToSign.array());
        }
    }

    EapAkaPrimeTypeData getEapSimAkaTypeData(AtClientErrorCode clientErrorCode) {
        return new EapAkaPrimeTypeData(EAP_AKA_CLIENT_ERROR, Arrays.asList(clientErrorCode));
    }

    EapAkaPrimeTypeData getEapSimAkaTypeData(int eapSubtype, List<EapSimAkaAttribute> attributes) {
        return new EapAkaPrimeTypeData(eapSubtype, attributes);
    }
}