summaryrefslogtreecommitdiff
path: root/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
blob: 44e616dfccc14702d2298c959ed676af188def35 (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
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
/*
 * Copyright (C) 2018 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 android.security.cts;

import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;

import com.android.compatibility.common.util.CddTest;
import com.android.compatibility.common.util.CpuFeatures;
import com.android.compatibility.common.util.PropertyUtil;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;

/**
 * Host-side kernel config tests.
 *
 * These tests analyze /proc/config.gz to verify that certain kernel config options are set.
 */
@RunWith(DeviceJUnit4ClassRunner.class)
public class KernelConfigTest extends BaseHostJUnit4Test {

    private static final Map<ITestDevice, HashSet<String>> cachedConfigGzSet = new HashMap<>(1);

    private HashSet<String> configSet;

    private ITestDevice mDevice;
    private IBuildInfo mBuild;

    @Before
    public void setUp() throws Exception {
        mDevice = getDevice();
        mBuild = getBuild();
        configSet = getDeviceConfig(mDevice, cachedConfigGzSet);
        // Assumes every test in this file asserts a requirement of CDD section 9.
        assumeSecurityModelCompat();
    }

    /*
     * IMPLEMENTATION DETAILS: Cache the configurations from /proc/config.gz on per-device basis
     * in case CTS is being run against multiple devices at the same time. This speeds up testing
     * by avoiding pulling/parsing the config file for each individual test
     */
    private static HashSet<String> getDeviceConfig(ITestDevice device,
            Map<ITestDevice, HashSet<String>> cache) throws Exception {
        if (!device.doesFileExist("/proc/config.gz")){
            throw new Exception();
        }
        HashSet<String> set;
        synchronized (cache) {
            set = cache.get(device);
        }
        if (set != null) {
            return set;
        }
        File file = File.createTempFile("config.gz", ".tmp");
        file.deleteOnExit();
        device.pullFile("/proc/config.gz", file);

        BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file))));
        set = new HashSet<String>(reader.lines().collect(Collectors.toList()));

        synchronized (cache) {
            cache.put(device, set);
        }
        return set;
    }

    /**
     * Test that the kernel has Stack Protector Strong enabled.
     *
     * @throws Exception
     */
    @CddTest(requirement="9.7")
    @Test
    public void testConfigStackProtectorStrong() throws Exception {
        assertTrue("Linux kernel must have Stack Protector enabled: " +
                "CONFIG_STACKPROTECTOR_STRONG=y or CONFIG_CC_STACKPROTECTOR_STRONG=y",
                configSet.contains("CONFIG_STACKPROTECTOR_STRONG=y") ||
                configSet.contains("CONFIG_CC_STACKPROTECTOR_STRONG=y"));
    }

    /**
     * Test that the kernel's executable code is read-only, read-only data is non-executable and
     * non-writable, and writable data is non-executable.
     *
     * @throws Exception
     */
    @CddTest(requirement="9.7")
    @Test
    public void testConfigROData() throws Exception {
        if (configSet.contains("CONFIG_UH_RKP=y"))
            return;

        assertTrue("Linux kernel must have RO data enabled: " +
                "CONFIG_DEBUG_RODATA=y or CONFIG_STRICT_KERNEL_RWX=y",
                configSet.contains("CONFIG_DEBUG_RODATA=y") ||
                configSet.contains("CONFIG_STRICT_KERNEL_RWX=y"));

        if (configSet.contains("CONFIG_MODULES=y")) {
            assertTrue("Linux kernel modules must also have RO data enabled: " +
                    "CONFIG_DEBUG_SET_MODULE_RONX=y or CONFIG_STRICT_MODULE_RWX=y",
                    configSet.contains("CONFIG_DEBUG_SET_MODULE_RONX=y") ||
                    configSet.contains("CONFIG_STRICT_MODULE_RWX=y"));
        }
    }

    /**
     * Test that the kernel implements static and dynamic object size bounds checking of copies
     * between user-space and kernel-space.
     *
     * @throws Exception
     */
    @CddTest(requirement="9.7")
    @Test
    public void testConfigHardenedUsercopy() throws Exception {
        if (PropertyUtil.getFirstApiLevel(mDevice) < 28) {
            return;
        }

        assertTrue("Linux kernel must have Hardened Usercopy enabled: CONFIG_HARDENED_USERCOPY=y",
                configSet.contains("CONFIG_HARDENED_USERCOPY=y"));
    }

    /**
     * Test that the kernel has PAN emulation enabled from architectures that support it.
     *
     * @throws Exception
     */
    @CddTest(requirement="9.7")
    @Test
    public void testConfigPAN() throws Exception {
        if (PropertyUtil.getFirstApiLevel(mDevice) < 28) {
            return;
        }

        if (CpuFeatures.isArm64(mDevice)) {
            assertTrue("Linux kernel must have PAN emulation enabled: " +
                    "CONFIG_ARM64_SW_TTBR0_PAN=y or CONFIG_ARM64_PAN=y",
                    (configSet.contains("CONFIG_ARM64_SW_TTBR0_PAN=y") ||
                    configSet.contains("CONFIG_ARM64_PAN=y")));
        } else if (CpuFeatures.isArm32(mDevice)) {
            assertTrue("Linux kernel must have PAN emulation enabled: " +
                    "CONFIG_CPU_SW_DOMAIN_PAN=y or CONFIG_CPU_TTBR0_PAN=y",
                    (configSet.contains("CONFIG_CPU_SW_DOMAIN_PAN=y") ||
                    configSet.contains("CONFIG_CPU_TTBR0_PAN=y")));
        }
    }

    private String getHardware() throws Exception {
        String hardware = "DEFAULT";
        String[] pathList = new String[]{"/proc/cpuinfo", "/sys/devices/soc0/soc_id"};
        String mitigationInfoMeltdown =
                mDevice.pullFileContents("/sys/devices/system/cpu/vulnerabilities/meltdown");
        String mitigationInfoSpectreV2 =
                mDevice.pullFileContents("/sys/devices/system/cpu/vulnerabilities/spectre_v2");

        if (mitigationInfoMeltdown != null && mitigationInfoSpectreV2 != null &&
            !mitigationInfoMeltdown.contains("Vulnerable") &&
            (!mitigationInfoSpectreV2.contains("Vulnerable") ||
              mitigationInfoSpectreV2.equals("Vulnerable: Unprivileged eBPF enabled\n")))
                return "VULN_SAFE";

        for (String nodeInfo : pathList) {
            if (!mDevice.doesFileExist(nodeInfo))
                continue;

            String nodeContent = mDevice.pullFileContents(nodeInfo);
            if (nodeContent == null)
                continue;

            for (String line : nodeContent.split("\n")) {
                /* Qualcomm SoCs */
                if (line.startsWith("Hardware")) {
                    String[] hardwareLine = line.split(" ");
                    hardware = hardwareLine[hardwareLine.length - 1];
                    break;
                }
                /* Samsung Exynos SoCs */
                else if (line.startsWith("EXYNOS")) {
                    hardware = line;
                    break;
                }
            }
        }
        /* TODO lookup other hardware as we get exemption requests. */
        return hardwareMitigations.containsKey(hardware) ? hardware : "DEFAULT";
    }

    private boolean doesFileExist(String filePath) throws Exception {
        String lsGrep = mDevice.executeShellCommand(String.format("ls \"%s\"", filePath));
        return lsGrep.trim().equals(filePath);
    }

    private Map<String, String[]> hardwareMitigations = new HashMap<String, String[]>() {
    {
        put("VULN_SAFE", null);
        put("EXYNOS990", null);
        put("EXYNOS980", null);
        put("EXYNOS850", null);
        put("EXYNOS3830", null);
        put("EXYNOS9630", null);
        put("EXYNOS9830", null);
        put("EXYNOS7870", null);
        put("EXYNOS7880", null);
        put("EXYNOS7570", null);
        put("EXYNOS7872", null);
        put("EXYNOS7885", null);
        put("EXYNOS9610", null);
        put("Kirin980", null);
        put("Kirin970", null);
        put("Kirin810", null);
        put("Kirin710", null);
        put("MT6889Z/CZA", null);
        put("MT6889Z/CIZA", null);
        put("mt6873", null);
        put("MT6853V/TZA", null);
        put("MT6853V/TNZA", null);
        put("MT6833V/ZA", null);
        put("MT6833V/NZA", null);
        put("MT6833V/TZA", null);
        put("MT6833V/TNZA", null);
        put("MT6833V/MZA", null);
        put("MT6833V/MNZA", null);
        put("MT6877V/ZA", null);
        put("MT6877V/NZA", null);
        put("MT6877V/TZA", null);
        put("MT6877V/TNZA", null);
        put("MT6768V/WA", null);
        put("MT6768V/CA", null);
        put("MT6768V/WB", null);
        put("MT6768V/CB", null);
        put("MT6767V/WA", null);
        put("MT6767V/CA", null);
        put("MT6767V/WB", null);
        put("MT6767V/CB", null);
        put("MT6769V/WA", null);
        put("MT6769V/CA", null);
        put("MT6769V/WB", null);
        put("MT6769V/CB", null);
        put("MT6769V/WT", null);
        put("MT6769V/CT", null);
        put("MT6769V/WU", null);
        put("MT6769V/CU", null);
        put("MT6769V/WZ", null);
        put("MT6769V/CZ", null);
        put("MT6769V/WY", null);
        put("MT6769V/CY", null);
        put("SDMMAGPIE", null);
        put("SM6150", null);
        put("SM7150", null);
        put("SM7250", null);
        put("LITO", null);
        put("LAGOON", null);
        put("SM8150", null);
        put("SM8150P", null);
        put("SM8250", null);
        put("KONA", null);
        put("SDM429", null);
        put("SDM439", null);
        put("QM215", null);
        put("ATOLL", null);
        put("ATOLL-AB", null);
        put("SDM660", null);
        put("BENGAL", null);
        put("KHAJE", null);
        put("BENGAL-IOT", null);
        put("BENGALP-IOT", null);
        put("DEFAULT", new String[]{"CONFIG_UNMAP_KERNEL_AT_EL0=y"});
    }};

    private String[] lookupMitigations() throws Exception {
        return hardwareMitigations.get(getHardware());
    }

    /**
     * Test that the kernel has Spectre/Meltdown mitigations for architectures and kernel versions
     * that support it. Exempt platforms which are known to not be vulnerable.
     *
     * @throws Exception
     */
    @CddTest(requirement="9.7")
    @Test
    public void testConfigHardwareMitigations() throws Exception {
        String mitigations[];

        if (PropertyUtil.getFirstApiLevel(mDevice) < 28) {
            return;
        }

        if (CpuFeatures.isArm64(mDevice) && !CpuFeatures.kernelVersionLessThan(mDevice, 4, 4)) {
            mitigations = lookupMitigations();
            if (mitigations != null) {
                for (String mitigation : mitigations) {
                    assertTrue("Linux kernel must have " + mitigation + " enabled.",
                            configSet.contains(mitigation));
                }
            }
        } else if (CpuFeatures.isX86(mDevice)) {
            assertTrue("Linux kernel must have KPTI enabled: CONFIG_PAGE_TABLE_ISOLATION=y",
                    configSet.contains("CONFIG_PAGE_TABLE_ISOLATION=y"));
        }
    }

    /**
     * Test that the kernel enables static usermodehelper and sets
     * the path to a whitelisted path.
     *
     * @throws Exception
     */
    @CddTest(requirement="9.7")
    @Test
    public void testConfigDisableUsermodehelper() throws Exception {
        if (PropertyUtil.getFirstApiLevel(mDevice) < 30) {
            return;
        }

        final String ENABLE_CONFIG = "CONFIG_STATIC_USERMODEHELPER=y";
        final String PATH_CONFIG = "CONFIG_STATIC_USERMODEHELPER_PATH=";

        final Set<String> ALLOWED_PATH_PREFIXES = new HashSet<String>();
        ALLOWED_PATH_PREFIXES.add("/vendor/");
        ALLOWED_PATH_PREFIXES.add("/system/");
        ALLOWED_PATH_PREFIXES.add("/system_ext/");

        assertTrue("Linux kernel must enable static usermodehelper: " + ENABLE_CONFIG,
            configSet.contains(ENABLE_CONFIG));

        String configPath = null;

        for (String option : configSet) {
            if (option.startsWith(PATH_CONFIG)) {
                configPath = option;
            }
        }

        int index = configPath.indexOf('=');
        String path = configPath.substring(index+1).replace("\"", "");

        assertTrue("Linux kernel must specify an absolute path for static usermodehelper path",
            configPath.contains("..") == false);

        boolean pathIsWhitelisted = false;

        for (String allowedPath : ALLOWED_PATH_PREFIXES) {
            if (path.startsWith(allowedPath)) {
                pathIsWhitelisted = true;
                break;
            }
        }

        // Specifying no path, which disables usermodehelper, is also
        // valid.
        pathIsWhitelisted |= path.isEmpty();

        String whitelistedPathPrefixExample = "'" +
            String.join("', '", ALLOWED_PATH_PREFIXES) + "'";

        assertTrue("Linux kernel must specify a whitelisted static usermodehelper path, "
                   + "and it must be empty or start with one of the following "
                   + "prefixes: " + whitelistedPathPrefixExample, pathIsWhitelisted);
    }

    /**
     * Test that the kernel enables fs-verity and its built-in signature support.
     */
    @CddTest(requirement="9.10")
    @Test
    public void testConfigFsVerity() throws Exception {
        if (PropertyUtil.getFirstApiLevel(mDevice) < 30 &&
                PropertyUtil.getPropertyInt(mDevice, "ro.apk_verity.mode") != 2) {
            return;
        }
        assertTrue("Linux kernel must have fs-verity enabled: CONFIG_FS_VERITY=y",
                configSet.contains("CONFIG_FS_VERITY=y"));
        assertTrue("Linux kernel must have fs-verity's builtin signature enabled: "
                + "CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y",
                configSet.contains("CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y"));
    }

    private void assumeSecurityModelCompat() throws Exception {
        // This feature name check only applies to devices that first shipped with
        // SC or later.
        final int firstApiLevel = Math.min(PropertyUtil.getFirstApiLevel(mDevice),
                PropertyUtil.getVendorApiLevel(mDevice));
        if (firstApiLevel >= 31) {
            assumeTrue("Skipping test: FEATURE_SECURITY_MODEL_COMPATIBLE missing.",
                    getDevice().hasFeature("feature:android.hardware.security.model.compatible"));
        }
    }

    /**
     * Test that the kernel is using kASLR.
     *
     * @throws Exception
     */
    @CddTest(requirement="9.7")
    @Test
    public void testConfigRandomizeBase() throws Exception {
        if (PropertyUtil.getFirstApiLevel(mDevice) < 33) {
            return;
        }

        if (CpuFeatures.isArm32(mDevice)) {
            return;
        }

        assertTrue("The kernel's base address must be randomized",
                configSet.contains("CONFIG_RANDOMIZE_BASE=y"));
    }

    /**
     * Test that CONFIG_VMAP_STACK is enabled on architectures that support it.
     *
     * @throws Exception
     */
    @CddTest(requirement="9.7")
    @Test
    public void testConfigVmapStack() throws Exception {
        if (PropertyUtil.getFirstApiLevel(mDevice) < 33) {
            return;
        }

        if (!configSet.contains("CONFIG_HAVE_ARCH_VMAP_STACK=y")) {
            return;
        }

        assertTrue("CONFIG_VMAP_STACK must be enabled on architectures that support it.",
                configSet.contains("CONFIG_VMAP_STACK=y"));
    }
}