1# Copyright (C) 2019 - 2022 Armin Kuster <akuster808@gmail.com>
2#
3from oeqa.runtime.case import OERuntimeTestCase
4from oeqa.core.decorator.depends import OETestDepends
5from oeqa.runtime.decorator.package import OEHasPackage
6from oeqa.core.decorator.data import skipIfNotFeature
7
8class Tpm2Test(OERuntimeTestCase):
9    @classmethod
10    def setUpClass(cls):
11        cls.tc.target.run('mkdir /tmp/myvtpm2')
12
13    @classmethod
14    def tearDownClass(cls):
15        cls.tc.target.run('rm -fr /tmp/myvtpm2')
16
17    def check_endlines(self, results,  expected_endlines):
18        for line in results.splitlines():
19            for el in expected_endlines:
20                if line == el:
21                    expected_endlines.remove(el)
22                    break
23
24        if expected_endlines:
25            self.fail('Missing expected line endings:\n  %s' % '\n  '.join(expected_endlines))
26
27    @OEHasPackage(['tpm2-tools'])
28    @OEHasPackage(['tpm2-abrmd'])
29    @OEHasPackage(['swtpm'])
30    @skipIfNotFeature('tpm2','Test tpm2_startup requires tpm2 to be in DISTRO_FEATURES')
31    @OETestDepends(['ssh.SSHTest.test_ssh'])
32    def test_tpm2_startup(self):
33        cmds = [
34                'swtpm socket -d --tpmstate dir=/tmp/myvtpm2 --tpm2 --ctrl type=tcp,port=2322 --server type=tcp,port=2321 --flags not-need-init',
35                'tpm2_startup -c -T "swtpm:port=2321"',
36               ]
37
38        for cmd in cmds:
39            status, output = self.target.run(cmd)
40            self.assertEqual(status, 0, msg='\n'.join([cmd, output]))
41
42    @OETestDepends(['tpm2.Tpm2Test.test_tpm2_startup'])
43    def test_tpm2_pcrread(self):
44         (status, output) = self.target.run('tpm2_pcrread')
45         expected_endlines = []
46         expected_endlines.append('  sha1:')
47         expected_endlines.append('    0 : 0x0000000000000000000000000000000000000000')
48         expected_endlines.append('    1 : 0x0000000000000000000000000000000000000000')
49         expected_endlines.append('  sha256:')
50         expected_endlines.append('    0 : 0x0000000000000000000000000000000000000000000000000000000000000000')
51         expected_endlines.append('    1 : 0x0000000000000000000000000000000000000000000000000000000000000000')
52
53
54         self.check_endlines(output, expected_endlines)
55
56
57    @OEHasPackage(['p11-kit'])
58    @OEHasPackage(['tpm2-pkcs11'])
59    @OETestDepends(['tpm2.Tpm2Test.test_tpm2_pcrread'])
60    def test_tpm2_pkcs11(self):
61         (status, output) = self.target.run('p11-kit list-modules -v')
62         self.assertEqual(status, 0, msg="Modules missing: %s" % output)
63
64    @OETestDepends(['tpm2.Tpm2Test.test_tpm2_pkcs11'])
65    def test_tpm2_swtpm_reset(self):
66         (status, output) = self.target.run('swtpm_ioctl -i --tcp :2322')
67         self.assertEqual(status, 0, msg="swtpm reset failed: %s" % output)
68