aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/internal/net/ipsec/ike/utils/RandomnessFactory.java
blob: 9ebb057a460184c41c8a0a63e96b97d539ed910b (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
/*
 * Copyright (C) 2020 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.ipsec.ike.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.net.eap.EapAuthenticator.EapRandomFactory;
import com.android.internal.net.ipsec.ike.testmode.DeterministicSecureRandom;

import java.security.SecureRandom;

/** Factory class that creates a DeterministicSecureRandom when test mode is enabled */
@VisibleForTesting
public class RandomnessFactory implements EapRandomFactory {
    // This constant is mirrored of android.net.NetworkCapabilities.TRANSPORT_TEST due to lack of
    // @TestApi guarantees in mainline modules
    public static final int NETWORK_CAPABILITY_TRANSPORT_TEST = 7;

    private final boolean mIsTestModeEnabled;

    public RandomnessFactory(Context context, Network network) {
        ConnectivityManager connectManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkCapabilities networkCapabilities = connectManager.getNetworkCapabilities(network);

        mIsTestModeEnabled =
                networkCapabilities != null
                        && networkCapabilities.hasCapability(NETWORK_CAPABILITY_TRANSPORT_TEST);
    }

    /**
     * Returns a DeterministicSecureRandom instance when test mode is enabled.
     *
     * <p>Returns a DeterministicSecureRandom instance when test mode is enabled, otherwise returns
     * null
     *
     * <p>TODO(b/154941518): figure out how to let this method always return a random without
     * relying on nullability behavior
     */
    @Override
    public SecureRandom getRandom() {
        if (mIsTestModeEnabled) {
            return new DeterministicSecureRandom();
        }

        return null;
    }
}