1#!/usr/bin/env python3

2# Copyright 2015-2020 Canonical Ltd.

3# All rights reserved.

4#

5# Written by:

6# Zygmunt Krynicki <zygmunt.krynicki@canonical.com>

7# Jonathan Cave <jonathan.cave@canonical.com>

8

9"""

10 Collect information about all sysfs attributes related to TPM.

11

12 This program traverses all the TPM device nodes found in /sys/class/tpm/.

13 Each present device is subsequently inspected by reading all readable files

14 in /sys/class/tpm/*/device/* and presenting the data present there as

15 subsequent RFC822 records. There is one record per TPM chip. In order to

16 differentiate each chip, each record contains the field x-sysfs-device-name

17 that stores the full sysfs directory name of the chip.

18

19@EPILOG@

20

21 Unreadable files (typically due to permissions) are silently skipped.

22"""

23

24 import os

25

26

27 def main():

28 # This is found on 4.2 kernels

29 sysfs_root_tpm = "/sys/class/tpm/"

30 # This is found on 3.19 kernels

31 sysfs_root_misc = "/sys/class/misc/"

32 if os.path.isdir(sysfs_root_tpm):

33 sysfs_root = sysfs_root_tpm

34 elif os.path.isdir(sysfs_root_misc):

35 sysfs_root = sysfs_root_misc

36 else:

37 return

38 for tpm_id in sorted(os.listdir(sysfs_root)):

39 if sysfs_root == sysfs_root_misc and not tpm_id.startswith("tpm"):

40 continue

41 print("x-sysfs-device-name: {}".format(tpm_id))

42 tpm_dirname = os.path.join(sysfs_root, tpm_id, "device")

43 for tpm_attr in sorted(os.listdir(tpm_dirname)):

44 tpm_filename = os.path.join(tpm_dirname, tpm_attr)

45 if not os.path.isfile(tpm_filename):

46 continue

47 if not os.access(tpm_filename, os.R_OK):

48 continue

49 with open(tpm_filename, "rt", encoding="utf-8") as stream:

50 tpm_data = stream.read()

51 tpm_data = tpm_data.rstrip()

52 if "\n" in tpm_data:

53 print("{}:".format(tpm_attr))

54 for tpm_data_chunk in tpm_data.splitlines():

55 print(" {}".format(tpm_data_chunk))

56 else:

57 print("{}: {}".format(tpm_attr, tpm_data))

58 print()

59

60

61 if __name__ == "__main__":

62 main()