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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <getopt.h>
#include <math.h>
#include <openssl/evp.h>
#include <sys/file.h>
#include "sd-device.h"
#include "ask-password-api.h"
#include "blockdev-util.h"
#include "boot-entry.h"
#include "build.h"
#include "chase.h"
#include "color-util.h"
#include "conf-files.h"
#include "creds-util.h"
#include "efi-api.h"
#include "env-util.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio.h"
#include "find-esp.h"
#include "format-table.h"
#include "format-util.h"
#include "fs-util.h"
#include "gpt.h"
#include "hash-funcs.h"
#include "hexdecoct.h"
#include "initrd-util.h"
#include "main-func.h"
#include "mkdir-label.h"
#include "openssl-util.h"
#include "ordered-set.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-util.h"
#include "pcrextend-util.h"
#include "pcrlock-firmware.h"
#include "pehash.h"
#include "pretty-print.h"
#include "proc-cmdline.h"
#include "random-util.h"
#include "recovery-key.h"
#include "sort-util.h"
#include "string-table.h"
#include "terminal-util.h"
#include "tpm2-util.h"
#include "unaligned.h"
#include "unit-name.h"
#include "utf8.h"
#include "varlink.h"
#include "varlink-io.systemd.PCRLock.h"
#include "verbs.h"
typedef enum RecoveryPinMode {
RECOVERY_PIN_HIDE, /* generate a recovery PIN automatically, but don't show it (alias: "no") */
RECOVERY_PIN_SHOW, /* generate a recovery PIN automatically, and display it to the user */
RECOVERY_PIN_QUERY, /* asks the user for a PIN to use interactively (alias: "yes") */
_RECOVERY_PIN_MODE_MAX,
_RECOVERY_PIN_MODE_INVALID = -EINVAL,
} RecoveryPinMode;
static PagerFlags arg_pager_flags = 0;
static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF|JSON_FORMAT_NEWLINE;
static char **arg_components = NULL;
static uint32_t arg_pcr_mask = 0;
static char *arg_pcrlock_path = NULL;
static bool arg_pcrlock_auto = true;
static bool arg_raw_description = false;
static char *arg_location_start = NULL;
static char *arg_location_end = NULL;
static TPM2_HANDLE arg_nv_index = 0;
static RecoveryPinMode arg_recovery_pin = RECOVERY_PIN_HIDE;
static char *arg_policy_path = NULL;
static bool arg_force = false;
static BootEntryTokenType arg_entry_token_type = BOOT_ENTRY_TOKEN_AUTO;
static char *arg_entry_token = NULL;
static bool arg_varlink = false;
STATIC_DESTRUCTOR_REGISTER(arg_components, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_pcrlock_path, freep);
STATIC_DESTRUCTOR_REGISTER(arg_location_start, freep);
STATIC_DESTRUCTOR_REGISTER(arg_location_end, freep);
STATIC_DESTRUCTOR_REGISTER(arg_policy_path, freep);
STATIC_DESTRUCTOR_REGISTER(arg_entry_token, freep);
#define PCRLOCK_SECUREBOOT_POLICY_PATH "/var/lib/pcrlock.d/240-secureboot-policy.pcrlock.d/generated.pcrlock"
#define PCRLOCK_FIRMWARE_CODE_EARLY_PATH "/var/lib/pcrlock.d/250-firmware-code-early.pcrlock.d/generated.pcrlock"
#define PCRLOCK_FIRMWARE_CONFIG_EARLY_PATH "/var/lib/pcrlock.d/250-firmware-config-early.pcrlock.d/generated.pcrlock"
#define PCRLOCK_FIRMWARE_CODE_LATE_PATH "/var/lib/pcrlock.d/550-firmware-code-late.pcrlock.d/generated.pcrlock"
#define PCRLOCK_FIRMWARE_CONFIG_LATE_PATH "/var/lib/pcrlock.d/550-firmware-config-late.pcrlock.d/generated.pcrlock"
#define PCRLOCK_GPT_PATH "/var/lib/pcrlock.d/600-gpt.pcrlock.d/generated.pcrlock"
#define PCRLOCK_SECUREBOOT_AUTHORITY_PATH "/var/lib/pcrlock.d/620-secureboot-authority.pcrlock.d/generated.pcrlock"
#define PCRLOCK_KERNEL_CMDLINE_PATH "/var/lib/pcrlock.d/710-kernel-cmdline.pcrlock.d/generated.pcrlock"
#define PCRLOCK_KERNEL_INITRD_PATH "/var/lib/pcrlock.d/720-kernel-initrd.pcrlock.d/generated.pcrlock"
#define PCRLOCK_MACHINE_ID_PATH "/var/lib/pcrlock.d/820-machine-id.pcrlock"
#define PCRLOCK_ROOT_FILE_SYSTEM_PATH "/var/lib/pcrlock.d/830-root-file-system.pcrlock"
#define PCRLOCK_FILE_SYSTEM_PATH_PREFIX "/var/lib/pcrlock.d/840-file-system-"
/* The default set of PCRs to lock to */
#define DEFAULT_PCR_MASK \
((UINT32_C(1) << TPM2_PCR_PLATFORM_CODE) | \
(UINT32_C(1) << TPM2_PCR_PLATFORM_CONFIG) | \
(UINT32_C(1) << TPM2_PCR_EXTERNAL_CODE) | \
(UINT32_C(1) << TPM2_PCR_EXTERNAL_CONFIG) | \
(UINT32_C(1) << TPM2_PCR_BOOT_LOADER_CODE) | \
(UINT32_C(1) << TPM2_PCR_BOOT_LOADER_CONFIG) | \
(UINT32_C(1) << TPM2_PCR_SECURE_BOOT_POLICY) | \
(UINT32_C(1) << TPM2_PCR_KERNEL_BOOT) | \
(UINT32_C(1) << TPM2_PCR_KERNEL_CONFIG) | \
(UINT32_C(1) << TPM2_PCR_SYSEXTS) | \
(UINT32_C(1) << TPM2_PCR_SHIM_POLICY) | \
(UINT32_C(1) << TPM2_PCR_SYSTEM_IDENTITY))
static const char* recovery_pin_mode_table[_RECOVERY_PIN_MODE_MAX] = {
[RECOVERY_PIN_HIDE] = "hide",
[RECOVERY_PIN_SHOW] = "show",
[RECOVERY_PIN_QUERY] = "query",
};
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(recovery_pin_mode, RecoveryPinMode, RECOVERY_PIN_QUERY);
typedef struct EventLogRecordBank EventLogRecordBank;
typedef struct EventLogRecord EventLogRecord;
typedef struct EventLogRegisterBank EventLogRegisterBank;
typedef struct EventLogRegister EventLogRegister;
typedef struct EventLogComponentVariant EventLogComponentVariant;
typedef struct EventLogComponent EventLogComponent;
typedef struct EventLog EventLog;
struct EventLogRecordBank {
uint16_t algorithm;
TPM2B_DIGEST hash;
LIST_FIELDS(EventLogRecordBank, banks);
};
typedef enum EventPayloadValid {
EVENT_PAYLOAD_VALID_YES,
EVENT_PAYLOAD_VALID_NO,
EVENT_PAYLOAD_VALID_DONT_KNOW,
_EVENT_PAYLOAD_VALID_MAX,
_EVENT_PAYLOAD_VALID_INVALID = -EINVAL,
} EventPayloadValid;
struct EventLogRecord {
EventLog *event_log;
uint32_t pcr;
const char *source;
char *description;
/* Data for firmware events (i.e. "TCG PC Client Platform Firmware Profile Specification" events) */
uint32_t firmware_event_type;
void *firmware_payload;
size_t firmware_payload_size;
/* Data for userspace events (i.e. those generated by systemd in userspace */
Tpm2UserspaceEventType userspace_event_type;
JsonVariant *userspace_content;
/* Validation result for the event payload itself, if the record contains enough information to validate the hash */
EventPayloadValid event_payload_valid;
/* If this record matches an variant of one of our defined components */
EventLogComponentVariant **mapped;
size_t n_mapped;
/* If this record is part of an EventLogComponentVariant */
EventLogComponentVariant *owning_component_variant;
LIST_HEAD(EventLogRecordBank, banks);
};
#define EVENT_LOG_RECORD_IS_FIRMWARE(record) ((record)->firmware_event_type != UINT32_MAX)
#define EVENT_LOG_RECORD_IS_USERSPACE(record) ((record)->userspace_event_type >= 0)
struct EventLogRegisterBank {
TPM2B_DIGEST observed;
TPM2B_DIGEST calculated;
};
struct EventLogRegister {
char *color;
unsigned n_measurements;
bool fully_recognized; /* true if all measurements in this register have been recognized to match components */
EventLogRegisterBank *banks;
};
struct EventLogComponentVariant {
EventLogComponent *component;
char *id;
char *path;
EventLogRecord **records;
size_t n_records;
};
struct EventLogComponent {
char *id;
EventLogComponentVariant **variants;
size_t n_variants;
};
struct EventLog {
EventLogRecord **records;
size_t n_records;
uint16_t *algorithms;
size_t n_algorithms;
bool algorithms_locked; /* if algorithms where set explicitly by user, and we should not determine them automatically */
const EVP_MD **mds;
/* The hash algorithm which we focus on for matching up components */
uint16_t primary_algorithm;
uint8_t startup_locality;
bool startup_locality_found;
EventLogRegister registers[TPM2_PCRS_MAX];
EventLogComponent **components;
size_t n_components;
/* Number of components which we couldn't find in the event log */
size_t n_missing_components;
/* PCRs mask indicating all PCRs touched by unrecognized components */
uint32_t missing_component_pcrs;
};
static EventLogRecordBank *event_log_record_bank_free(EventLogRecordBank *bank) {
return mfree(bank);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLogRecordBank*, event_log_record_bank_free);
static EventLogRecord *event_log_record_free(EventLogRecord *record) {
EventLogRecordBank *bank;
if (!record)
return NULL;
free(record->description);
free(record->firmware_payload);
json_variant_unref(record->userspace_content);
while ((bank = LIST_POP(banks, record->banks)))
event_log_record_bank_free(bank);
free(record->mapped);
return mfree(record);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLogRecord*, event_log_record_free);
static void event_log_register_done(EventLog *el, EventLogRegister *reg) {
assert(reg);
free(reg->color);
free(reg->banks);
}
static EventLogComponentVariant* event_log_component_variant_free(EventLogComponentVariant *variant) {
if (!variant)
return NULL;
free(variant->id);
free(variant->path);
FOREACH_ARRAY(record, variant->records, variant->n_records)
event_log_record_free(*record);
free(variant->records);
return mfree(variant);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLogComponentVariant*, event_log_component_variant_free);
static EventLogComponent* event_log_component_free(EventLogComponent *component) {
if (!component)
return NULL;
FOREACH_ARRAY(variant, component->variants, component->n_variants)
event_log_component_variant_free(*variant);
free(component->variants);
free(component->id);
return mfree(component);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLogComponent*, event_log_component_free);
static EventLog* event_log_free(EventLog *el) {
if (!el)
return NULL;
FOREACH_ARRAY(p, el->registers, TPM2_PCRS_MAX)
event_log_register_done(el, p);
FOREACH_ARRAY(rr, el->records, el->n_records)
event_log_record_free(*rr);
free(el->records);
FOREACH_ARRAY(c, el->components, el->n_components)
event_log_component_free(*c);
free(el->components);
free(el->algorithms);
free(el->mds);
return mfree(el);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLog*, event_log_free);
static EventLogRecord* event_log_record_new(EventLog *el) {
EventLogRecord *record;
record = new(EventLogRecord, 1);
if (!record)
return NULL;
*record = (EventLogRecord) {
.event_log = el,
.firmware_event_type = UINT32_MAX,
.userspace_event_type = _TPM2_USERSPACE_EVENT_TYPE_INVALID,
.event_payload_valid = _EVENT_PAYLOAD_VALID_INVALID,
};
return record;
}
static int event_log_add_record(
EventLog *el,
EventLogRecord **ret) {
_cleanup_(event_log_record_freep) EventLogRecord *record = NULL;
assert(el);
if (!GREEDY_REALLOC(el->records, el->n_records+1))
return -ENOMEM;
record = event_log_record_new(el);
if (!record)
return -ENOMEM;
el->records[el->n_records++] = record;
if (ret)
*ret = record;
TAKE_PTR(record);
return 0;
}
static int event_log_add_algorithm(EventLog *el, uint16_t alg) {
assert(el);
if (el->algorithms_locked) /* algorithms configured via env var, don't add any further automatically */
return 0;
if (typesafe_bsearch(&alg, el->algorithms, el->n_algorithms, cmp_uint16))
return 0;
if (!GREEDY_REALLOC(el->algorithms, el->n_algorithms+1))
return -ENOMEM;
el->algorithms[el->n_algorithms++] = alg;
typesafe_qsort(el->algorithms, el->n_algorithms, cmp_uint16);
return 1;
}
static int event_log_add_algorithms_from_environment(EventLog *el) {
const char *e;
int r;
assert(el);
e = secure_getenv("SYSTEMD_TPM2_HASH_ALGORITHMS");
if (!e)
return 0;
for (;;) {
_cleanup_free_ char *word = NULL;
r = extract_first_word(&e, &word, ":", 0);
if (r < 0)
return r;
if (r == 0)
break;
r = tpm2_hash_alg_from_string(word);
if (r < 0)
return log_error_errno(r, "Unknown hash algorithm '%s'.", word);
r = event_log_add_algorithm(el, r);
if (r < 0)
return log_error_errno(r, "Failed to add hash algorithm '%s'.", word);
}
if (el->n_algorithms > 0)
el->algorithms_locked = true;
return 0;
}
static EventLogRecordBank *event_log_record_find_bank(
const EventLogRecord *record,
uint16_t alg) {
assert(record);
LIST_FOREACH(banks, i, record->banks)
if (i->algorithm == alg)
return i;
return NULL;
}
static int event_log_record_add_bank(
EventLogRecord *record,
uint16_t algorithm,
const void *hash,
size_t hash_size,
EventLogRecordBank **ret) {
_cleanup_(event_log_record_bank_freep) EventLogRecordBank *bank = NULL;
_cleanup_free_ void *h = NULL;
assert(record);
assert(hash || hash_size == 0);
if (event_log_record_find_bank(record, algorithm))
return -EEXIST;
if (hash_size > sizeof_field(TPM2B_DIGEST, buffer))
return -E2BIG;
h = memdup(hash, hash_size);
if (!h)
return -ENOMEM;
bank = new(EventLogRecordBank, 1);
if (!bank)
return -ENOMEM;
*bank = (EventLogRecordBank) {
.algorithm = algorithm,
.hash = TPM2B_DIGEST_MAKE(hash, hash_size),
};
LIST_PREPEND(banks, record->banks, bank);
if (ret)
*ret = bank;
TAKE_PTR(bank);
return 0;
}
static bool event_log_record_is_stub(EventLogRecord *rec) {
assert(rec);
/* Recognizes the special EV_IPL events systemd-stub generates. Since EV_IPL can be used by almost
* anything, we'll check for the PCR values, to see if it's one of ours. */
if (rec->firmware_event_type != EV_IPL)
return false;
if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
return false;
if (!IN_SET(rec->pcr,
TPM2_PCR_KERNEL_BOOT, /* 11 */
TPM2_PCR_KERNEL_CONFIG, /* 12 */
TPM2_PCR_SYSEXTS)) /* 13 */
return false;
return true;
}
static int event_log_record_parse_variable_data(
EventLogRecord *rec,
sd_id128_t *ret_variable_uuid,
char **ret_variable_name) {
_cleanup_free_ char16_t *p16 = NULL;
_cleanup_free_ char *p = NULL;
assert(rec);
assert(ret_variable_uuid);
assert(ret_variable_name);
if (rec->firmware_payload_size < sizeof(UEFI_VARIABLE_DATA))
return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "EFI variable field too short.");
const UEFI_VARIABLE_DATA *vdata = rec->firmware_payload;
if (vdata->unicodeNameLength > (SIZE_MAX - offsetof(UEFI_VARIABLE_DATA, unicodeNameLength)) / 2)
return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Unicode name length too large.");
size_t m = offsetof(UEFI_VARIABLE_DATA, unicodeName) + vdata->unicodeNameLength * 2;
if (vdata->variableDataLength > SIZE_MAX - m)
return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Oversize EFI variable data size.");
if (rec->firmware_payload_size != m + vdata->variableDataLength)
return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "EFI variable data has wrong size.");
p16 = memdup(vdata->unicodeName, vdata->unicodeNameLength * 2); /* Copy out, to align properly */
if (!p16)
return log_oom_debug();
p = utf16_to_utf8(p16, vdata->unicodeNameLength * 2);
if (!p)
return log_oom_debug();
if (!string_is_safe(p))
return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Unsafe EFI variable string in record.");
*ret_variable_uuid = efi_guid_to_id128(vdata->variableName);
*ret_variable_name = TAKE_PTR(p);
return 0;
}
static int event_log_record_extract_firmware_description(EventLogRecord *rec) {
_cleanup_free_ char *fallback = NULL;
int r;
assert(rec);
if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
return 0;
if (arg_raw_description)
goto catchall;
switch (rec->firmware_event_type) {
case EV_EFI_VARIABLE_DRIVER_CONFIG:
case EV_EFI_VARIABLE_BOOT:
case EV_EFI_VARIABLE_BOOT2:
case EV_EFI_VARIABLE_AUTHORITY: {
_cleanup_free_ char *p = NULL;
sd_id128_t uuid;
r = event_log_record_parse_variable_data(rec, &uuid, &p);
if (r == -ENOMEM)
return log_oom();
if (r < 0) {
log_warning_errno(r, "EFI variable data invalid, ignoring.");
goto invalid;
}
if (asprintf(&rec->description, "%s: %s-" SD_ID128_UUID_FORMAT_STR,
rec->firmware_event_type == EV_EFI_VARIABLE_AUTHORITY ? "Authority" : "Variable",
p,
SD_ID128_FORMAT_VAL(uuid)) < 0)
return log_oom();
return 1;
}
case EV_SEPARATOR: {
if (rec->firmware_payload_size != sizeof(uint32_t)) {
log_warning("EFI separator field has wrong size, ignoring.");
goto invalid;
}
uint32_t val = unaligned_read_ne32(rec->firmware_payload);
switch (val) {
case 0:
case UINT32_C(0xffffffff):
(void) asprintf(&rec->description, "Separator: Success (0x%02" PRIx32 ")", val);
break;
case 1:
rec->description = strdup("Separator: Error (0x01)");
break;
default:
log_warning("Unexpected separator payload %" PRIu32 ", ignoring.", val);
goto invalid;
}
if (!rec->description)
return log_oom();
return 1;
}
case EV_EFI_ACTION: {
_cleanup_free_ char *d = NULL;
r = make_cstring(rec->firmware_payload, rec->firmware_payload_size, MAKE_CSTRING_ALLOW_TRAILING_NUL, &d);
if (r < 0)
return log_error_errno(r, "Failed to make C string from EFI action string: %m");
if (!string_is_safe(d)) {
log_warning("Unsafe EFI action string in record, ignoring.");
goto invalid;
}
rec->description = strjoin("Action: ", d);
if (!rec->description)
return log_oom();
return 1;
}
case EV_EFI_GPT_EVENT: {
if (rec->firmware_payload_size < sizeof(GptHeader)) {
log_warning("GPT measurement too short, ignoring.");
goto invalid;
}
const GptHeader *h = rec->firmware_payload;
if (!gpt_header_has_signature(h)) {
log_warning("GPT measurement does not cover a GPT partition table header, ignoring.");
goto invalid;
}
if (asprintf(&rec->description, "GPT: disk " SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(efi_guid_to_id128(h->disk_guid))) < 0)
return log_oom();
return 1;
}
case EV_IPL: {
_cleanup_free_ char *d = NULL;
/* EV_IPL can be anything, only try to parse the description on PCRs we "own" */
if (!event_log_record_is_stub(rec))
break;
/* sd-stub always sets a description string as text for these */
d = utf16_to_utf8(rec->firmware_payload, rec->firmware_payload_size);
if (!d)
return log_oom();
if (string_has_cc(d, NULL)) {
log_warning("Unsafe EFI action string in record, ignoring.");
goto invalid;
}
rec->description = strjoin("String: ", d);
if (!rec->description)
return log_oom();
return 1;
}
case EV_EVENT_TAG: {
TCG_PCClientTaggedEvent *tag = rec->firmware_payload;
size_t left = rec->firmware_payload_size;
if (left == 0) {
log_warning("Empty tagged PC client event, ignoring.");
goto invalid;
}
for (;;) {
uint64_t m;
if (left < offsetof(TCG_PCClientTaggedEvent, taggedEventData)) {
log_warning("Tagged PC client event too short, ignoring.");
goto invalid;
}
m = offsetof(TCG_PCClientTaggedEvent, taggedEventData) + (uint64_t) tag->taggedEventDataSize;
if (left < m) {
log_warning("Tagged PC client event data too short, ignoring.");
goto invalid;
}
switch (tag->taggedEventID) {
/* Linux kernel's own measurements: */
case INITRD_EVENT_TAG_ID:
/* The tagged event payload is just a constant string, hence don't show it */
if (!strextend_with_separator(&rec->description, ", ", "Linux: initrd"))
return log_oom();
break;
case LOAD_OPTIONS_EVENT_TAG_ID:
/* As above. */
if (!strextend_with_separator(&rec->description, ", ", "Linux: kernel command line"))
return log_oom();
break;
/* systemd's measurements: */
case LOADER_CONF_EVENT_TAG_ID:
/* As above. */
if (!strextend_with_separator(&rec->description, ", ", "systemd-boot: loader.conf"))
return log_oom();
break;
case DEVICETREE_ADDON_EVENT_TAG_ID: {
_cleanup_free_ char *raw = NULL, *s = NULL;
raw = utf16_to_utf8((const char16_t*) tag->taggedEventData, tag->taggedEventDataSize);
if (!raw)
return log_oom();
s = cescape(raw);
if (!s)
return log_oom();
r = strextendf_with_separator(&rec->description, ", ", "systemd-stub: devicetree addon %s", s);
if (r < 0)
return log_error_errno(r, "Failed to format EV_EVENT_TAG description string: %m");
break;
}
default: {
_cleanup_free_ char *s = NULL;
s = cescape_length((char*) tag->taggedEventData, tag->taggedEventDataSize);
if (!s)
return log_oom();
r = strextendf_with_separator(&rec->description, ", ", "Tag 0x%" PRIx32 ": %s", tag->taggedEventID, s);
if (r < 0)
return log_error_errno(r, "Failed to format EV_EVENT_TAG description string: %m");
break;
}}
tag = (TCG_PCClientTaggedEvent*) ((uint8_t*) tag + m);
left -= m;
if (left == 0)
break;
}
return 1;
}
case EV_EFI_PLATFORM_FIRMWARE_BLOB: {
const UEFI_PLATFORM_FIRMWARE_BLOB *blob;
if (rec->firmware_payload_size != sizeof(UEFI_PLATFORM_FIRMWARE_BLOB)) {
log_warning("EV_EFI_PLATFORM_FIRMWARE_BLOB of wrong size, ignoring.");
goto invalid;
}
blob = rec->firmware_payload;
if (asprintf(&rec->description, "Blob: %s @ 0x%" PRIx64, FORMAT_BYTES(blob->blobLength), blob->blobBase) < 0)
return log_oom();
return 1;
}
case EV_EFI_BOOT_SERVICES_APPLICATION:
case EV_EFI_BOOT_SERVICES_DRIVER:
case EV_EFI_RUNTIME_SERVICES_DRIVER: {
const UEFI_IMAGE_LOAD_EVENT *load;
_cleanup_free_ char *fn = NULL;
bool end = false;
if (rec->firmware_payload_size < offsetof(UEFI_IMAGE_LOAD_EVENT, devicePath)) {
log_warning("Device path too short, ignoring.");
goto invalid;
}
load = rec->firmware_payload;
if (load->lengthOfDevicePath !=
rec->firmware_payload_size - offsetof(UEFI_IMAGE_LOAD_EVENT, devicePath)) {
log_warning("Device path size does not match, ignoring.");
goto invalid;
}
const packed_EFI_DEVICE_PATH *dp = (const packed_EFI_DEVICE_PATH*) load->devicePath;
size_t left = load->lengthOfDevicePath;
for (;;) {
if (left == 0) {
if (!end) {
log_warning("Garbage after device path end, ignoring.");
goto invalid;
}
break;
}
if (end) {
log_warning("Garbage after device path end, ignoring.");
goto invalid;
}
if (left < offsetof(packed_EFI_DEVICE_PATH, path) || left < dp->length) {
log_warning("Device path element too short, ignoring.");
goto invalid;
}
if (dp->type == 4 && dp->subType == 4) {
/* Filename, store the last node of this type as description, it should contain the file name */
free(fn);
fn = utf16_to_utf8((void*) dp->path, dp->length - offsetof(packed_EFI_DEVICE_PATH, path));
if (!fn)
return log_oom();
} else if (dp->type == 0x7F && dp->subType == 0xFF)
/* End of Hardware Device Path */
end = true;
else
log_debug("Ignoring device path element type=0x%02x subtype=0x%02x", dp->type, dp->subType);
left -= dp->length;
dp = (packed_EFI_DEVICE_PATH*) ((uint8_t*) dp + dp->length);
}
if (fn) {
rec->description = strjoin("File: ", fn);
if (!rec->description)
return log_oom();
return 1;
}
break;
}}
catchall:
/* Catchall: show binary data */
fallback = cescape_length(rec->firmware_payload, rec->firmware_payload_size);
if (!fallback)
return log_oom();
rec->description = strjoin("Raw: ", fallback);
if (!rec->description)
return log_oom();
return 1;
invalid:
/* Mark the payload as invalid, so that we do not bother parsing/validating it any further */
rec->event_payload_valid = EVENT_PAYLOAD_VALID_NO;
return 0;
}
static int event_log_add_algorithms_from_record(EventLog *el, EventLogRecord *record) {
int r;
assert(el);
assert(record);
if (el->algorithms_locked)
return 0;
LIST_FOREACH(banks, i, record->banks) {
r = event_log_add_algorithm(el, i->algorithm);
if (r < 0)
return r;
}
return 0;
}
static int event_log_load_firmware(EventLog *el) {
const TCG_EfiSpecIdEventAlgorithmSize *algorithms;
size_t bufsize = 0, n_algorithms = 0, left = 0;
_cleanup_free_ void *buf = NULL;
const TCG_PCR_EVENT2 *event;
const char *path;
int r;
assert(el);
path = tpm2_firmware_log_path();
r = read_full_file(path, (char**) &buf, &bufsize);
if (r < 0)
return log_error_errno(r, "Failed to open TPM2 event log '%s': %m", path);
if (bufsize == 0) {
/* Sometimes it's useful to invoke things with SYSTEMD_MEASURE_LOG_FIRMWARE=/dev/null, let's allow that, and proceed */
log_warning("Empty firmware event log file, not loading.");
return 0;
}
r = validate_firmware_header(buf, bufsize, &algorithms, &n_algorithms, &event, &left);
if (r < 0)
return r;
for (const TCG_PCR_EVENT2 *next_event = NULL;; event = next_event) {
EventLogRecord *record = NULL;
const void *payload;
size_t payload_size;
r = validate_firmware_event(
event,
left,
algorithms,
n_algorithms,
&next_event,
&left,
&payload,
&payload_size);
if (r < 0)
return r;
if (r == 0)
break;
if (event->eventType == EV_NO_ACTION &&
event->pcrIndex == 0 &&
payload_size == 17 &&
memcmp(payload, "StartupLocality", sizeof("StartupLocality")) == 0) {
if (el->startup_locality_found)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "StartupLocality event found twice.");
el->startup_locality = ((const uint8_t*) payload)[sizeof("StartupLocality")];
el->startup_locality_found = true;
log_debug("Found StartupLocality event: %u", el->startup_locality);
continue;
}
if (event->eventType == EV_NO_ACTION) { /* Ignore pseudo events, that don't result in a measurement */
log_debug("Skipping NO_ACTION event.");
continue;
}
r = event_log_add_record(el, &record);
if (r < 0)
return log_error_errno(r, "Failed to add record to event log: %m");
record->pcr = event->pcrIndex;
record->source = path;
record->firmware_event_type = event->eventType;
record->firmware_payload = memdup(payload, payload_size);
if (!record->firmware_payload)
return log_oom();
record->firmware_payload_size = payload_size;
const void *ha, *ha_next = NULL;
ha = (const uint8_t*) event + offsetof(TCG_PCR_EVENT2, digests.digests);
assert(event->digests.count == n_algorithms);
for (size_t i = 0; i < n_algorithms; i++, ha = ha_next) {
/* The TPMT_HA is not aligned in the record, hence read the hashAlg field via an unaligned read */
assert_cc(__builtin_types_compatible_p(uint16_t, typeof(TPMI_ALG_HASH)));
uint16_t hash_alg = unaligned_read_ne16((const uint8_t*) ha + offsetof(TPMT_HA, hashAlg));
/* On some systems (some HyperV?) the order of hash algorithms announced in the
* header does not match the order in the records. Let's hence search for the right
* mapping */
size_t j;
for (j = 0; j < n_algorithms; j++)
if (hash_alg == algorithms[j].algorithmId)
break;
if (j >= n_algorithms)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Hash algorithms in event log record not among those advertised by log header.");
ha_next = (const uint8_t*) ha + offsetof(TPMT_HA, digest) + algorithms[j].digestSize;
if (!tpm2_hash_alg_to_string(hash_alg))
continue;
r = event_log_record_add_bank(
record,
hash_alg,
(const uint8_t*) ha + offsetof(TPMT_HA, digest),
algorithms[j].digestSize,
/* ret= */ NULL);
if (r < 0)
return log_error_errno(r, "Failed to add bank to event log record: %m");
}
/* Try to extract a descriptive text */
r = event_log_record_extract_firmware_description(record);
if (r < 0)
return r;
r = event_log_add_algorithms_from_record(el, record);
if (r < 0)
return r;
}
return 0;
}
static int event_log_record_parse_json(EventLogRecord *record, JsonVariant *j) {
const char *rectype = NULL;
JsonVariant *x, *k;
uint64_t u;
int r;
assert(record);
assert(j);
if (!json_variant_is_object(j))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "record object is not an object.");
x = json_variant_by_key(j, "pcr");
if (!x)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'pcr' field missing from TPM measurement log file entry.");
if (!json_variant_is_unsigned(x))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'pcr' field is not an integer.");
u = json_variant_unsigned(x);
if (u >= TPM2_PCRS_MAX)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'pcr' field is out of range.");
record->pcr = json_variant_unsigned(x);
x = json_variant_by_key(j, "digests");
if (!x)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'digests' field missing from TPM measurement log file entry.");
if (!json_variant_is_array(x))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'digests' field is not an array.");
JSON_VARIANT_ARRAY_FOREACH(k, x) {
_cleanup_free_ void *hash = NULL;
size_t hash_size;
JsonVariant *a, *h;
int na;
a = json_variant_by_key(k, "hashAlg");
if (!a)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'digests' field element lacks 'hashAlg' field.");
if (!json_variant_is_string(a))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'hashAlg' field is not a string.");
na = tpm2_hash_alg_from_string(json_variant_string(a));
if (na < 0) {
log_debug_errno(na, "Unsupported hash '%s' in userspace event log, ignoring: %m", json_variant_string(a));
continue;
}
h = json_variant_by_key(k, "digest");
if (!h)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'digests' field lacks 'digest' field.");
r = json_variant_unhex(h, &hash, &hash_size);
if (r < 0)
return log_error_errno(r, "Failed to decode digest: %m");
r = event_log_record_add_bank(
record,
na,
hash,
hash_size,
/* ret= */ NULL);
if (r < 0)
return log_error_errno(r, "Failed to add bank to event log record: %m");
}
x = json_variant_by_key(j, "content_type");
if (!x)
log_debug("'content_type' missing from TPM measurement log file entry, ignoring.");
else {
if (!json_variant_is_string(x))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'content_type' field is not a string.");
rectype = json_variant_string(x);
}
if (streq_ptr(rectype, "systemd")) {
JsonVariant *y;
x = json_variant_by_key(j, "content");
if (!x)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'content' field missing from TPM measurement log file entry.");
if (!json_variant_is_object(x))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'content' sub-object is not an object.");
y = json_variant_by_key(x, "string");
if (y) {
if (!json_variant_is_string(y))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'string' field is not a string.");
r = free_and_strdup_warn(&record->description, json_variant_string(y));
if (r < 0)
return r;
}
y = json_variant_by_key(x, "eventType");
if (y) {
if (!json_variant_is_string(y))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'eventType' field is not a string.");
record->userspace_event_type = tpm2_userspace_event_type_from_string(json_variant_string(y));
if (record->userspace_event_type < 0)
log_debug_errno(record->userspace_event_type, "Unknown userspace event type '%s', ignoring.", json_variant_string(y));
}
json_variant_unref(record->userspace_content);
record->userspace_content = json_variant_ref(x);
}
return 0;
}
static int event_log_load_userspace(EventLog *el) {
_cleanup_fclose_ FILE *f = NULL;
_cleanup_free_ char *b = NULL;
bool beginning = true;
const char *path;
size_t bn = 0;
int r;
assert(el);
path = tpm2_userspace_log_path();
f = fopen(path, "re");
if (!f) {
if (errno != ENOENT)
return log_error_errno(errno, "Failed to open userspace TPM measurement log file: %m");
return 0;
}
if (flock(fileno(f), LOCK_SH) < 0)
return log_error_errno(errno, "Failed to lock userspace TPM measurement log file: %m");
for (;;) {
_cleanup_(json_variant_unrefp) JsonVariant *j = NULL;
EventLogRecord *record;
int ch;
ch = fgetc(f);
if (ch == EOF) {
if (ferror(f))
return log_error_errno(errno, "Failed to read local TPM measurement log file: %m");
if (beginning)
break;
} else if (ch != 0x1EU) {
if (!GREEDY_REALLOC(b, bn + 2))
return log_oom();
b[bn++] = (char) ch;
continue;
}
if (beginning) {
beginning = false;
continue;
}
if (!GREEDY_REALLOC(b, bn + 1))
return log_oom();
b[bn] = 0; /* Turn it into a string */
if (memchr(b, 0, bn)) {
log_warning("Found record with embedded NUL byte, skipping.");
continue;
}
r = json_parse(b, 0, &j, NULL, NULL);
if (r < 0)
return log_error_errno(r, "Failed to parse local TPM measurement log file: %m");
r = event_log_add_record(el, &record);
if (r < 0)
return log_error_errno(r, "Failed to add record to event log: %m");
record->source = path;
r = event_log_record_parse_json(record, j);
if (r < 0)
return r;
r = event_log_add_algorithms_from_record(el, record);
if (r < 0)
return r;
if (ch == EOF)
break;
b = mfree(b);
bn = 0;
}
return 0;
}
static EventLog *event_log_new(void) {
_cleanup_(event_log_freep) EventLog *el = NULL;
el = new(EventLog, 1);
if (!el)
return NULL;
*el = (EventLog) {
.primary_algorithm = UINT16_MAX,
};
return TAKE_PTR(el);
}
static int event_log_load(EventLog *el) {
int r;
assert(el);
r = event_log_load_firmware(el);
if (r < 0)
return r;
r = event_log_load_userspace(el);
if (r < 0)
return r;
return 0;
}
static int event_log_read_pcrs(EventLog *el) {
_cleanup_(tpm2_context_unrefp) Tpm2Context *tc = NULL;
int r;
assert(el);
r = tpm2_context_new_or_warn(/* device= */ NULL, &tc);
if (r < 0)
return r;
FOREACH_ARRAY(rr, el->registers, TPM2_PCRS_MAX) {
if (rr->banks)
continue;
rr->banks = new0(EventLogRegisterBank, el->n_algorithms);
if (!rr->banks)
return log_oom();
}
for (size_t a = 0; a < el->n_algorithms; a++) {
_cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
size_t n_pcr_values;
TPML_PCR_SELECTION selection;
tpm2_tpml_pcr_selection_from_mask(TPM2_PCRS_MASK, el->algorithms[a], &selection);
r = tpm2_pcr_read(tc, &selection, &pcr_values, &n_pcr_values);
if (r < 0)
return r;
FOREACH_ARRAY(v, pcr_values, n_pcr_values) {
assert(v->hash == el->algorithms[a]);
el->registers[v->index].banks[a].observed = v->value;
}
}
return 0;
}
static void event_log_initial_pcr_state(EventLog *el, uint32_t pcr, size_t size, TPM2B_DIGEST *ret) {
assert(el);
assert(pcr < TPM2_PCRS_MAX);
assert(size > 0);
assert(size <= sizeof_field(TPM2B_DIGEST, buffer));
assert(ret);
ret->size = size;
switch (pcr) {
case 0:
memzero(ret->buffer, ret->size-1);
((uint8_t*) ret->buffer)[ret->size-1] = el->startup_locality_found ? el->startup_locality : 0;
break;
case 1 ... 16:
case 23:
memzero(ret->buffer, ret->size);
break;
case 17 ... 22:
memset(ret->buffer, 0xffu, ret->size);
break;
default:
assert_not_reached();
}
}
static int event_log_calculate_pcrs(EventLog *el) {
assert(el);
/* Iterates through the event log an calculates the expected hash values based on all listed records */
assert(!el->mds);
el->mds = new(const EVP_MD*, el->n_algorithms);
if (!el->mds)
return log_oom();
for (size_t i = 0; i < el->n_algorithms; i++) {
const EVP_MD *md;
const char *a;
assert_se(a = tpm2_hash_alg_to_string(el->algorithms[i]));
assert_se(md = EVP_get_digestbyname(a));
el->mds[i] = md;
}
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++)
for (size_t i = 0; i < el->n_algorithms; i++) {
EventLogRegisterBank *b = el->registers[pcr].banks + i;
event_log_initial_pcr_state(el, pcr, EVP_MD_size(el->mds[i]), &b->calculated);
}
FOREACH_ARRAY(rr, el->records, el->n_records) {
EventLogRegister *reg = el->registers + (*rr)->pcr;
for (size_t i = 0; i < el->n_algorithms; i++) {
const char *n = tpm2_hash_alg_to_string(el->algorithms[i]);
_cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *mc = NULL;
EventLogRegisterBank *reg_b;
EventLogRecordBank *rec_b;
unsigned sz;
rec_b = event_log_record_find_bank(*rr, el->algorithms[i]);
if (!rec_b) {
log_warning("Record with missing bank '%s', ignoring.", n);
continue;
}
reg_b = reg->banks + i;
mc = EVP_MD_CTX_new();
if (!mc)
return log_oom();
if (EVP_DigestInit_ex(mc, el->mds[i], NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize %s message digest context.", n);
if (EVP_DigestUpdate(mc, reg_b->calculated.buffer, reg_b->calculated.size) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to run digest.");
if (EVP_DigestUpdate(mc, rec_b->hash.buffer, rec_b->hash.size) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to run digest.");
if (EVP_DigestFinal_ex(mc, reg_b->calculated.buffer, &sz) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize hash context.");
assert(sz == reg_b->calculated.size);
}
reg->n_measurements++;
}
return 0;
}
static int event_log_record_validate_hash_firmware(
EventLogRecord *record,
EventLogRecordBank *bank,
const EVP_MD *md) {
_cleanup_free_ void *hdata_alternative = NULL;
size_t hsz, hsz_alternative = 0;
bool strict = false;
const void *hdata;
assert(record);
assert(bank);
assert(md);
if (!EVENT_LOG_RECORD_IS_FIRMWARE(record))
return 0;
switch (record->firmware_event_type) {
case EV_EFI_ACTION:
case EV_EFI_GPT_EVENT:
case EV_EFI_VARIABLE_BOOT2:
case EV_EFI_VARIABLE_DRIVER_CONFIG:
case EV_EFI_VARIABLE_AUTHORITY:
case EV_SEPARATOR:
case EV_S_CRTM_VERSION:
/* Here the extended hash value is the hash value of the event payload. Note that
* EV_PLATFORM_CONFIG_FLAGS (according to the TCG PC Client Platform Firmware Profile
* Specification) is also supposed to be like this. But ovmf doesn't follow this requirement,
* hence be lenient on that one, and don't include it here. */
hdata = record->firmware_payload;
hsz = record->firmware_payload_size;
strict = true;
break;
case EV_EFI_VARIABLE_BOOT: {
const UEFI_VARIABLE_DATA *vdata = record->firmware_payload;
size_t skip;
/* Here the extended hash value is the hash value of the variable data (i.e. excluding the
* name).
*
* Note: we already checked the general validity of the UEFI_VARIABLE_DATA structure, hence
* no need to do so again. */
assert(record->firmware_payload_size >= offsetof(UEFI_VARIABLE_DATA, unicodeName));
skip = offsetof(UEFI_VARIABLE_DATA, unicodeName) + vdata->unicodeNameLength * 2;
assert(record->firmware_payload_size >= skip);
hdata = (const uint8_t*) record->firmware_payload + skip;
hsz = record->firmware_payload_size - skip;
strict = true;
break;
}
case EV_IPL:
if (event_log_record_is_stub(record)) {
/* The PE section names have a descriptive string in UTF-16 in the payload, but the
* hash is over the UTF-8 version (with suffixing 0), hence let's convert the payload
* into that format here, and see if it checks out. */
hdata_alternative = utf16_to_utf8(record->firmware_payload, record->firmware_payload_size);
if (!hdata_alternative)
return log_oom();
hsz_alternative = strlen(hdata_alternative) + 1; /* with NUL byte */
}
_fallthrough_;
default:
/* For the others check the data too, just in case. But usually this will not match, hence
* only report if the checksum matches, but don't complain if it does not. */
hdata = record->firmware_payload;
hsz = record->firmware_payload_size;
strict = false;
break;
}
int mdsz = EVP_MD_size(md);
assert(mdsz > 0);
assert((size_t) mdsz <= sizeof_field(TPM2B_DIGEST, buffer));
TPM2B_DIGEST payload_hash = {
.size = mdsz,
};
unsigned dsz = mdsz;
if (EVP_Digest(hdata, hsz, payload_hash.buffer, &dsz, md, NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to calculate event payload hash.");
assert(dsz == (unsigned) mdsz);
/* If this didn't match then let's try the alternative format here, if we have one, and check things then. */
if (memcmp_nn(bank->hash.buffer, bank->hash.size, payload_hash.buffer, payload_hash.size) != 0 && hdata_alternative) {
if (EVP_Digest(hdata_alternative, hsz_alternative, payload_hash.buffer, &dsz, md, NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to calculate event payload hash.");
assert(dsz == (unsigned) mdsz);
}
if (memcmp_nn(bank->hash.buffer, bank->hash.size, payload_hash.buffer, payload_hash.size) != 0) {
if (strict)
record->event_payload_valid = EVENT_PAYLOAD_VALID_NO;
else if (record->event_payload_valid != EVENT_PAYLOAD_VALID_NO)
record->event_payload_valid = EVENT_PAYLOAD_VALID_DONT_KNOW;
} else if (record->event_payload_valid < 0)
record->event_payload_valid = EVENT_PAYLOAD_VALID_YES;
return 1;
}
static int event_log_record_validate_hash_userspace(
EventLogRecord *record,
EventLogRecordBank *bank,
const EVP_MD *md) {
_cleanup_free_ unsigned char *payload_hash = NULL;
unsigned payload_hash_size;
JsonVariant *js;
const char *s;
int mdsz;
assert(record);
assert(bank);
assert(md);
if (!EVENT_LOG_RECORD_IS_USERSPACE(record))
return 0;
if (!record->userspace_content)
return 0;
js = json_variant_by_key(record->userspace_content, "string");
if (!js)
return 0;
assert(json_variant_is_string(js));
s = json_variant_string(js);
mdsz = EVP_MD_size(md);
assert(mdsz > 0);
payload_hash_size = mdsz;
payload_hash = malloc(payload_hash_size);
if (!payload_hash)
return log_oom();
if (EVP_Digest(s, strlen(s), payload_hash, &payload_hash_size, md, NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to calculate event payload hash.");
assert((int) payload_hash_size == mdsz);
if (memcmp_nn(bank->hash.buffer, bank->hash.size, payload_hash, payload_hash_size) != 0)
record->event_payload_valid = EVENT_PAYLOAD_VALID_NO;
else if (record->event_payload_valid < 0)
record->event_payload_valid = EVENT_PAYLOAD_VALID_YES;
return 0;
}
static int event_log_validate_record_hashes(EventLog *el) {
int r;
assert(el);
/* For records which contain the full data to validate the hashes, do so. */
FOREACH_ARRAY(rr, el->records, el->n_records) {
LIST_FOREACH(banks, bank, (*rr)->banks) {
const EVP_MD *md;
const char *a;
assert_se(a = tpm2_hash_alg_to_string(bank->algorithm));
assert_se(md = EVP_get_digestbyname(a));
r = event_log_record_validate_hash_firmware(*rr, bank, md);
if (r < 0)
return r;
r = event_log_record_validate_hash_userspace(*rr, bank, md);
if (r < 0)
return r;
}
}
return 0;
}
static int event_log_component_cmp(EventLogComponent *const*a, EventLogComponent *const*b) {
const EventLogComponent *x = ASSERT_PTR(*ASSERT_PTR(a)), *y = ASSERT_PTR(*ASSERT_PTR(b));
return strcmp(x->id, y->id);
}
static EventLogComponent *event_log_find_component(EventLog *el, const char *id) {
EventLogComponent k = {
.id = (char*) id,
};
EventLogComponent *kk = &k, **found;
assert(el);
assert(id);
found = typesafe_bsearch(
&kk,
el->components,
el->n_components,
event_log_component_cmp);
if (!found)
return NULL;
return *found;
}
static int event_log_add_component(EventLog *el, const char *id, EventLogComponent **ret) {
_cleanup_(event_log_component_freep) EventLogComponent *component = NULL;
_cleanup_free_ char *id_copy = NULL;
EventLogComponent *found;
assert(el);
assert(ret);
found = event_log_find_component(el, id);
if (found) {
*ret = found;
return 0;
}
if (!GREEDY_REALLOC(el->components, el->n_components+1))
return log_oom();
id_copy = strdup(id);
if (!id_copy)
return log_oom();
component = new(EventLogComponent, 1);
if (!component)
return log_oom();
*component = (EventLogComponent) {
.id = TAKE_PTR(id_copy),
};
if (ret)
*ret = component;
el->components[el->n_components++] = TAKE_PTR(component);
return 1;
}
static int event_log_record_equal(const EventLogRecord *a, const EventLogRecord *b) {
EventLogRecordBank *x, *y;
assert(a);
assert(a->event_log);
assert(b);
assert(b->event_log);
assert(a->event_log == b->event_log);
if (a->pcr != b->pcr)
return false;
x = event_log_record_find_bank(a, a->event_log->primary_algorithm);
y = event_log_record_find_bank(b, b->event_log->primary_algorithm);
if (!x || !y)
return false;
assert(x->algorithm == a->event_log->primary_algorithm);
assert(y->algorithm == b->event_log->primary_algorithm);
return memcmp_nn(x->hash.buffer, x->hash.size, y->hash.buffer, y->hash.size) == 0;
}
static int event_log_add_component_file(EventLog *el, EventLogComponent *component, const char *path) {
_cleanup_(event_log_component_variant_freep) EventLogComponentVariant *variant = NULL;
_cleanup_free_ char *fname = NULL, *id = NULL, *path_copy = NULL;
_cleanup_(json_variant_unrefp) JsonVariant *j = NULL;
JsonVariant *records;
const char *e;
int r;
assert(el);
r = path_extract_filename(path, &fname);
if (r < 0)
return log_error_errno(r, "Failed to extract basename from path %s: %m", path);
e = endswith(fname, ".pcrlock");
if (!e)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Bad suffix: %s", fname);
id = strndup(fname, e - fname);
if (!id)
return log_oom();
if (!component) {
r = event_log_add_component(el, id, &component);
if (r < 0)
return r;
}
if (!GREEDY_REALLOC(component->variants, component->n_variants+1))
return log_oom();
r = json_parse_file(
/* f= */ NULL,
path,
/* flags= */ 0,
&j,
/* ret_line= */ NULL,
/* ret_column= */ NULL);
if (r < 0) {
log_warning_errno(r, "Failed to parse component file %s, ignoring: %m", path);
return 0;
}
if (!json_variant_is_object(j)) {
log_warning_errno(r, "Component file %s does not contain JSON object, ignoring.", path);
return 0;
}
path_copy = strdup(path);
if (!path_copy)
return log_oom();
variant = new(EventLogComponentVariant, 1);
if (!variant)
return log_oom();
*variant = (EventLogComponentVariant) {
.component = component,
.path = TAKE_PTR(path_copy),
.id = TAKE_PTR(id),
};
records = json_variant_by_key(j, "records");
if (records) {
JsonVariant *rj;
if (!json_variant_is_array(records)) {
log_warning_errno(r, "Component records field of file %s is not an array, ignoring.", path);
return 0;
}
JSON_VARIANT_ARRAY_FOREACH(rj, records) {
_cleanup_(event_log_record_freep) EventLogRecord *record = NULL;
if (!GREEDY_REALLOC(variant->records, variant->n_records+1))
return log_oom();
record = event_log_record_new(el);
if (!record)
return log_oom();
r = event_log_record_parse_json(record, rj);
if (r < 0)
return r;
record->owning_component_variant = variant;
variant->records[variant->n_records++] = TAKE_PTR(record);
}
}
component->variants[component->n_variants++] = TAKE_PTR(variant);
return 1;
}
static int event_log_add_component_dir(EventLog *el, const char *path, char **base_search) {
_cleanup_free_ char *fname = NULL, *id = NULL;
_cleanup_strv_free_ char **files = NULL;
EventLogComponent *component;
const char *e;
int r;
assert(el);
r = path_extract_filename(path, &fname);
if (r < 0)
return log_error_errno(r, "Failed to extract basename from path %s: %m", path);
e = endswith(fname, ".pcrlock.d");
if (!e)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Bad suffix: %s", fname);
id = strndup(fname, e - fname);
if (!id)
return log_oom();
r = event_log_add_component(el, id, &component);
if (r < 0)
return r;
_cleanup_strv_free_ char **search = NULL;
STRV_FOREACH(b, base_search) {
_cleanup_free_ char *q = NULL;
q = path_join(*b, fname);
if (!q)
return log_oom();
r = strv_consume(&search, TAKE_PTR(q));
if (r < 0)
return log_oom();
}
r = conf_files_list_strv(&files, ".pcrlock", /* root= */ NULL, CONF_FILES_REGULAR, (const char*const*) search);
if (r < 0)
return log_error_errno(r, "Failed to enumerate .pcrlock files for component '%s': %m", id);
STRV_FOREACH(f, files) {
r = event_log_add_component_file(el, component, *f);
if (r < 0)
return r;
}
return 0;
}
static int event_log_load_components(EventLog *el) {
_cleanup_strv_free_ char **files = NULL;
char **dirs;
int r;
assert(el);
dirs = arg_components ?:
STRV_MAKE("/etc/pcrlock.d",
"/run/pcrlock.d",
"/var/lib/pcrlock.d",
"/usr/local/lib/pcrlock.d",
"/usr/lib/pcrlock.d");
r = conf_files_list_strv(&files, NULL, NULL, CONF_FILES_REGULAR|CONF_FILES_DIRECTORY|CONF_FILES_FILTER_MASKED, (const char*const*) dirs);
if (r < 0)
return log_error_errno(r, "Failed to enumerate .pcrlock files: %m");
STRV_FOREACH(f, files) {
if (endswith(*f, ".pcrlock.d"))
r = event_log_add_component_dir(el, *f, dirs);
else if (endswith(*f, ".pcrlock"))
r = event_log_add_component_file(el, NULL, *f);
else
continue;
if (r < 0)
return r;
}
return 0;
}
static int event_log_validate_fully_recognized(EventLog *el) {
for (uint32_t pcr = 0; pcr < ELEMENTSOF(el->registers); pcr++) {
bool fully_recognized = true;
FOREACH_ARRAY(rr, el->records, el->n_records) {
EventLogRecord *rec = *rr;
if (rec->pcr != pcr)
continue;
if (rec->n_mapped == 0) {
log_notice("Event log record %zu (PCR %" PRIu32 ", \"%s\") not matching any component.",
(size_t) (rr - el->records), rec->pcr, strna(rec->description));
fully_recognized = false;
break;
}
}
el->registers[pcr].fully_recognized = fully_recognized;
}
return 0;
}
static int event_log_match_component_variant(
EventLog *el,
size_t i,
EventLogComponentVariant *variant,
size_t j,
bool assign) {
int r;
assert(el);
assert(variant);
/* It's OK to point immediately after the last record, but not further */
assert(i <= el->n_records);
assert(j <= variant->n_records);
/* All entries in the variant checked out? Yippieh! */
if (j == variant->n_records)
return true;
/* If the remainder of the variant is longer than the remainder of the event log, it cannot possibly fit. */
if (el->n_records - i < variant->n_records - j)
return false;
/* Does this record match? If not, let's try at the next place in the logs. */
if (!event_log_record_equal(el->records[i], variant->records[j]))
return event_log_match_component_variant(el, i + 1, variant, j, assign); /* Recursion! */
/* This one matches. Good. Let's see if the rest also matches. (Recursion!) */
r = event_log_match_component_variant(el, i + 1, variant, j + 1, assign);
if (r <= 0)
return r;
if (assign) {
/* Take ownership (Note we allow multiple components and variants to take owneship of the same record!) */
if (!GREEDY_REALLOC(el->records[i]->mapped, el->records[i]->n_mapped+1))
return log_oom();
el->records[i]->mapped[el->records[i]->n_mapped++] = variant;
}
return true;
}
static uint32_t event_log_component_variant_pcrs(EventLogComponentVariant *i) {
uint32_t mask = 0;
assert(i);
/* returns mask of PCRs touched by this variant */
FOREACH_ARRAY(rr, i->records, i->n_records)
mask |= UINT32_C(1) << (*rr)->pcr;
return mask;
}
static uint32_t event_log_component_pcrs(EventLogComponent *c) {
uint32_t mask = 0;
assert(c);
/* Returns mask of PCRs touched by this component */
FOREACH_ARRAY(ii, c->variants, c->n_variants)
mask |= event_log_component_variant_pcrs(*ii);
return mask;
}
static int event_log_map_components(EventLog *el) {
_cleanup_free_ char *skipped_ids = NULL;
unsigned n_skipped = 0;
int r;
assert(el);
FOREACH_ARRAY(cc, el->components, el->n_components) {
_cleanup_free_ char *matching_ids = NULL;
unsigned n_matching = 0, n_empty = 0;
EventLogComponent *c = *cc;
if (arg_location_end && strcmp(c->id, arg_location_end) > 0) {
n_skipped++;
if (!strextend_with_separator(&skipped_ids, ", ", c->id))
return log_oom();
continue;
}
FOREACH_ARRAY(ii, c->variants, c->n_variants) {
EventLogComponentVariant *i = *ii;
if (i->n_records == 0) {
/* The empty variant always matches */
n_empty++;
continue;
}
r = event_log_match_component_variant(el, 0, i, 0, n_matching + n_empty == 0);
if (r < 0)
return r;
if (r > 0) {
n_matching++;
if (!strextend_with_separator(&matching_ids, ", ", i->id))
return log_oom();
}
}
if (n_matching + n_empty == 0) {
if (arg_location_start && strcmp(c->id, arg_location_start) >= 0)
log_info("Didn't find component '%s' in event log, assuming system hasn't reached it yet.", c->id);
else {
log_notice("Couldn't find component '%s' in event log.", c->id);
el->n_missing_components++;
el->missing_component_pcrs |= event_log_component_pcrs(c);
}
} else if (n_matching > 1)
log_debug("Found %u possible variants of component '%s' in event log (%s). Proceeding.", n_matching, c->id, matching_ids);
}
if (n_skipped > 0)
log_notice("Skipped %u components after location '%s' (%s).", n_skipped, arg_location_end, skipped_ids);
if (el->n_missing_components > 0)
log_notice("Unable to recognize %zu components in event log.", el->n_missing_components);
return event_log_validate_fully_recognized(el);
}
#define ANSI_TRUE_COLOR_MAX (7U + 3U + 1U + 3U + 1U + 3U + 2U)
static const char *ansi_true_color(uint8_t r, uint8_t g, uint8_t b, char ret[static ANSI_TRUE_COLOR_MAX]) {
snprintf(ret, ANSI_TRUE_COLOR_MAX, "\x1B[38;2;%u;%u;%um", r, g, b);
return ret;
}
static char *color_for_pcr(EventLog *el, uint32_t pcr) {
char color[ANSI_TRUE_COLOR_MAX];
uint8_t r, g, b;
assert(el);
assert(pcr < TPM2_PCRS_MAX);
if (el->registers[pcr].color)
return el->registers[pcr].color;
hsv_to_rgb(360.0 / (TPM2_PCRS_MAX - 1) * pcr, 100, 90, &r, &g, &b);
ansi_true_color(r, g, b, color);
el->registers[pcr].color = strdup(color);
return el->registers[pcr].color;
}
static int add_algorithm_columns(
EventLog *el,
Table *table,
const char *prefix,
const char *json_field_prefix) {
int r;
assert(el);
assert(table);
FOREACH_ARRAY(alg, el->algorithms, el->n_algorithms) {
const char *n = tpm2_hash_alg_to_string(*alg);
_cleanup_free_ char *v = NULL;
if (prefix) {
v = strjoin(prefix, " ", n);
if (!v)
return log_oom();
}
size_t c = table_get_current_column(table);
r = table_add_cell(table, NULL, TABLE_HEADER, v ?: n);
if (r < 0)
return table_log_add_error(r);
if (FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF) &&
el->primary_algorithm != UINT16_MAX &&
*alg != el->primary_algorithm)
(void) table_hide_column_from_display(table, c);
_cleanup_free_ char *j = NULL;
if (json_field_prefix) {
_cleanup_free_ char *m = strdup(n);
if (!m)
return log_oom();
j = strjoin(json_field_prefix, ascii_strupper(m));
if (!j)
return log_oom();
}
(void) table_set_json_field_name(table, c, j ?: n);
}
return 0;
}
static int show_log_table(EventLog *el, JsonVariant **ret_variant) {
_cleanup_(table_unrefp) Table *table = NULL;
int r;
assert(el);
table = table_new_raw(5 + el->n_algorithms + 4);
if (!table)
return log_oom();
(void) table_set_ersatz_string(table, TABLE_ERSATZ_DASH);
r = table_add_many(table,
TABLE_HEADER, "pcr",
TABLE_SET_ALIGN_PERCENT, 100,
TABLE_HEADER, "",
TABLE_HEADER, "pcrname",
TABLE_HEADER, "event",
TABLE_HEADER, "match",
TABLE_SET_ALIGN_PERCENT, 100);
if (r < 0)
return table_log_add_error(r);
r = add_algorithm_columns(el, table, NULL, NULL);
if (r < 0)
return r;
size_t phase_column = table_get_current_column(table);
r = table_add_many(table,
TABLE_HEADER, "F/U",
TABLE_HEADER, "source",
TABLE_HEADER, "component",
TABLE_HEADER, "description");
if (r < 0)
return table_log_add_error(r);
(void) table_hide_column_from_display(table, table_get_columns(table) - 3); /* hide source */
if (!FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF))
(void) table_hide_column_from_display(table, (size_t) 1); /* hide color block column */
(void) table_set_json_field_name(table, phase_column, "phase");
FOREACH_ARRAY(rr, el->records, el->n_records) {
EventLogRecord *record = *rr;
r = table_add_many(table,
TABLE_UINT32, record->pcr,
TABLE_STRING, special_glyph(SPECIAL_GLYPH_FULL_BLOCK),
TABLE_SET_COLOR, color_for_pcr(el, record->pcr),
TABLE_STRING, tpm2_pcr_index_to_string(record->pcr));
if (r < 0)
return table_log_add_error(r);
if (EVENT_LOG_RECORD_IS_FIRMWARE(record)) {
const char *et;
et = tpm2_log_event_type_to_string(record->firmware_event_type);
if (et)
r = table_add_cell(table, NULL, TABLE_STRING, et);
else
r = table_add_cell(table, NULL, TABLE_UINT32_HEX, &record->firmware_event_type);
} else if (EVENT_LOG_RECORD_IS_USERSPACE(record))
r = table_add_cell(table, NULL, TABLE_STRING, tpm2_userspace_event_type_to_string(record->userspace_event_type));
else
r = table_add_cell(table, NULL, TABLE_EMPTY, NULL);
if (r < 0)
return table_log_add_error(r);
if (record->event_payload_valid < 0 || record->event_payload_valid == EVENT_PAYLOAD_VALID_DONT_KNOW)
r = table_add_cell(table, NULL, TABLE_EMPTY, NULL);
else
r = table_add_many(table,
TABLE_BOOLEAN_CHECKMARK, record->event_payload_valid == EVENT_PAYLOAD_VALID_YES,
TABLE_SET_COLOR, ansi_highlight_green_red(record->event_payload_valid == EVENT_PAYLOAD_VALID_YES));
if (r < 0)
return table_log_add_error(r);
FOREACH_ARRAY(alg, el->algorithms, el->n_algorithms) {
EventLogRecordBank *bank;
bank = event_log_record_find_bank(record, *alg);
if (bank) {
_cleanup_free_ char *hex = NULL;
hex = hexmem(bank->hash.buffer, bank->hash.size);
if (!hex)
return log_oom();
r = table_add_cell(table, NULL, TABLE_STRING, hex);
} else
r = table_add_cell(table, NULL, TABLE_EMPTY, NULL);
if (r < 0)
return table_log_add_error(r);
}
r = table_add_many(table,
TABLE_STRING, EVENT_LOG_RECORD_IS_FIRMWARE(record) ? "F" :
EVENT_LOG_RECORD_IS_USERSPACE(record) ? "U" : NULL,
TABLE_PATH_BASENAME, record->source,
TABLE_PATH_BASENAME, record->n_mapped > 0 ? record->mapped[0]->component->id : NULL,
TABLE_STRING, record->description);
if (r < 0)
return table_log_add_error(r);
}
if (ret_variant) {
r = table_to_json(table, ret_variant);
if (r < 0)
return log_error_errno(r, "Failed to format table to JSON: %m");
return 0;
}
r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, /* show_header= */true);
if (r < 0)
return log_error_errno(r, "Failed to output table: %m");
return 0;
}
static bool is_unset_pcr(const void *value, size_t size) {
return memeqzero(value, size) || memeqbyte(0xffu, value, size);
}
static bool event_log_pcr_checks_out(const EventLog *el, const EventLogRegister *reg) {
assert(el);
assert(reg);
for (size_t i = 0; i < el->n_algorithms; i++)
if (memcmp_nn(reg->banks[i].calculated.buffer, reg->banks[i].calculated.size,
reg->banks[i].observed.buffer, reg->banks[i].observed.size) != 0)
return false;
return true;
}
static int show_pcr_table(EventLog *el, JsonVariant **ret_variant) {
_cleanup_(table_unrefp) Table *table = NULL;
int r;
assert(el);
table = table_new_raw(8 + el->n_algorithms*2);
if (!table)
return log_oom();
(void) table_set_ersatz_string(table, TABLE_ERSATZ_DASH);
r = table_add_many(table,
TABLE_HEADER, "pcr",
TABLE_SET_ALIGN_PERCENT, 100,
TABLE_HEADER, "", /* color block column */
TABLE_HEADER, "", /* emoji column */
TABLE_HEADER, "pcrname",
TABLE_HEADER, "count",
TABLE_SET_ALIGN_PERCENT, 100,
TABLE_HEADER, "h",
TABLE_SET_ALIGN_PERCENT, 100,
TABLE_HEADER, "r",
TABLE_SET_ALIGN_PERCENT, 100,
TABLE_HEADER, "c",
TABLE_SET_ALIGN_PERCENT, 100);
if (r < 0)
return table_log_add_error(r);
r = add_algorithm_columns(el, table, "Calculated", "calculated");
if (r < 0)
return r;
r = add_algorithm_columns(el, table, "Observed", "observed");
if (r < 0)
return r;
if (!FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF))
(void) table_hide_column_from_display(table, (size_t) 1, (size_t) 2); /* hide color block and emoji column */
else if (!emoji_enabled())
(void) table_hide_column_from_display(table, (size_t) 2);
(void) table_set_json_field_name(table, 5, "hashMatchesEventLog");
(void) table_set_json_field_name(table, 6, "allEventsMatched");
(void) table_set_json_field_name(table, 7, "noMissingComponents");
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
/* Check if the PCR hash value matches the event log data */
bool hash_match = event_log_pcr_checks_out(el, el->registers + pcr);
/* Whether all records in this PCR have a matching component */
bool fully_recognized = el->registers[pcr].fully_recognized;
/* Whether any unmatched components touch this PCR */
bool missing_components = FLAGS_SET(el->missing_component_pcrs, UINT32_C(1) << pcr);
const char *emoji = special_glyph(
!hash_match ? SPECIAL_GLYPH_DEPRESSED_SMILEY :
!fully_recognized ? SPECIAL_GLYPH_UNHAPPY_SMILEY :
missing_components ? SPECIAL_GLYPH_SLIGHTLY_HAPPY_SMILEY :
SPECIAL_GLYPH_HAPPY_SMILEY);
r = table_add_many(table,
TABLE_UINT32, pcr,
TABLE_STRING, special_glyph(SPECIAL_GLYPH_FULL_BLOCK),
TABLE_SET_COLOR, color_for_pcr(el, pcr),
TABLE_STRING, emoji,
TABLE_STRING, tpm2_pcr_index_to_string(pcr));
if (r < 0)
return table_log_add_error(r);
if (el->registers[pcr].n_measurements > 0)
r = table_add_cell(table, NULL, TABLE_UINT, &el->registers[pcr].n_measurements);
else
r = table_add_cell(table, NULL, TABLE_EMPTY, NULL);
if (r < 0)
return table_log_add_error(r);
r = table_add_many(table,
TABLE_BOOLEAN_CHECKMARK, hash_match,
TABLE_SET_COLOR, ansi_highlight_green_red(hash_match),
TABLE_BOOLEAN_CHECKMARK, fully_recognized,
TABLE_SET_COLOR, ansi_highlight_green_red(fully_recognized),
TABLE_BOOLEAN_CHECKMARK, !missing_components,
TABLE_SET_COLOR, ansi_highlight_green_red(!missing_components));
if (r < 0)
return table_log_add_error(r);
for (size_t i = 0; i < el->n_algorithms; i++) {
const char *color;
color = is_unset_pcr(el->registers[pcr].banks[i].calculated.buffer, el->registers[pcr].banks[i].calculated.size) ? ANSI_GREY : NULL;
if (el->registers[pcr].banks[i].calculated.size > 0) {
_cleanup_free_ char *hex = NULL;
hex = hexmem(el->registers[pcr].banks[i].calculated.buffer, el->registers[pcr].banks[i].calculated.size);
if (!hex)
return log_oom();
r = table_add_many(table,
TABLE_STRING, hex,
TABLE_SET_COLOR, color);
} else
r = table_add_many(table,
TABLE_EMPTY,
TABLE_SET_COLOR, color);
if (r < 0)
return table_log_add_error(r);
}
for (size_t i = 0; i < el->n_algorithms; i++) {
_cleanup_free_ char *hex = NULL;
const char *color;
hex = hexmem(el->registers[pcr].banks[i].observed.buffer, el->registers[pcr].banks[i].observed.size);
if (!hex)
return log_oom();
color = !hash_match ? ANSI_HIGHLIGHT_RED :
is_unset_pcr(el->registers[pcr].banks[i].observed.buffer, el->registers[pcr].banks[i].observed.size) ? ANSI_GREY : NULL;
r = table_add_many(table,
TABLE_STRING, hex,
TABLE_SET_COLOR, color);
if (r < 0)
return table_log_add_error(r);
}
}
if (ret_variant) {
r = table_to_json(table, ret_variant);
if (r < 0)
return log_error_errno(r, "Failed to format table to JSON: %m");
return 0;
}
r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, /* show_header= */ true);
if (r < 0)
return log_error_errno(r, "Failed to output table: %m");
if (FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF))
printf("\n"
"%sLegend: H → PCR hash value matches event log%s\n"
"%s R → All event log records for this PCR have a matching component%s\n"
"%s C → No components that couldn't be matched with log records affect this PCR%s\n",
ansi_grey(), ansi_normal(), /* less on small screens automatically resets the color after long lines, hence we set it anew for each line */
ansi_grey(), ansi_normal(),
ansi_grey(), ansi_normal());
return 0;
}
static int event_determine_primary_algorithm(EventLog *el) {
assert(el);
if (el->n_algorithms == 0) {
/* Nothing loaded to make the decision on? Then pick SHA256 */
el->primary_algorithm = TPM2_ALG_SHA256;
return 0;
}
FOREACH_ARRAY(alg, el->algorithms, el->n_algorithms) {
/* If we have SHA256, focus on that */
if (*alg == TPM2_ALG_SHA256) {
el->primary_algorithm = *alg;
return 0;
}
}
/* Otherwise show the "best" (i.e. the one with the highest id value) */
el->primary_algorithm = el->algorithms[el->n_algorithms-1];
return 0;
}
static int event_log_load_and_process(EventLog **ret) {
_cleanup_(event_log_freep) EventLog *el = NULL;
int r;
el = event_log_new();
if (!el)
return log_oom();
r = event_log_add_algorithms_from_environment(el);
if (r < 0)
return r;
r = event_log_load(el);
if (r < 0)
return r;
r = event_log_read_pcrs(el);
if (r < 0)
return r;
r = event_log_calculate_pcrs(el);
if (r < 0)
return r;
r = event_log_validate_record_hashes(el);
if (r < 0)
return r;
r = event_determine_primary_algorithm(el);
if (r < 0)
return r;
r = event_log_load_components(el);
if (r < 0)
return r;
r = event_log_map_components(el);
if (r < 0)
return r;
*ret = TAKE_PTR(el);
return 0;
}
static int verb_show_log(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *log_table = NULL, *pcr_table = NULL;
_cleanup_(event_log_freep) EventLog *el = NULL;
bool want_json = !FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF);
int r;
r = event_log_load_and_process(&el);
if (r < 0)
return r;
if (!want_json)
putchar('\n');
r = show_log_table(el, want_json ? &log_table : NULL);
if (r < 0)
return r;
if (!want_json)
putchar('\n');
r = show_pcr_table(el, want_json ? &pcr_table : NULL);
if (r < 0)
return r;
if (want_json) {
_cleanup_(json_variant_unrefp) JsonVariant *object = NULL;
r = json_build(&object, JSON_BUILD_OBJECT(
JSON_BUILD_PAIR_VARIANT("log", log_table),
JSON_BUILD_PAIR_VARIANT("pcrs", pcr_table)));
if (r < 0)
return log_error_errno(r, "Failed to generate combined object: %m");
r = json_variant_dump(object, arg_json_format_flags, stdout, /* prefix= */ NULL);
if (r < 0)
return log_error_errno(r, "Failed to dump JSON object: %m");
}
return 0;
}
static int event_log_record_to_cel(EventLogRecord *record, uint64_t *recnum, JsonVariant **ret) {
_cleanup_(json_variant_unrefp) JsonVariant *ja = NULL, *fj = NULL;
JsonVariant *cd = NULL;
const char *ct = NULL;
int r;
assert(record);
assert(recnum);
assert(ret);
LIST_FOREACH(banks, bank, record->banks) {
r = json_variant_append_arrayb(
&ja, JSON_BUILD_OBJECT(
JSON_BUILD_PAIR_STRING("hashAlg", tpm2_hash_alg_to_string(bank->algorithm)),
JSON_BUILD_PAIR_HEX("digest", bank->hash.buffer, bank->hash.size)));
if (r < 0)
return log_error_errno(r, "Failed to append CEL digest entry: %m");
}
if (!ja) {
r = json_variant_new_array(&ja, NULL, 0);
if (r < 0)
return log_error_errno(r, "Failed to allocate JSON array: %m");
}
if (EVENT_LOG_RECORD_IS_FIRMWARE(record)) {
_cleanup_free_ char *et = NULL;
const char *z;
z = tpm2_log_event_type_to_string(record->firmware_event_type);
if (z) {
_cleanup_free_ char *b = NULL;
b = strreplace(z, "-", "_");
if (!b)
return log_oom();
et = strjoin("EV_", ascii_strupper(b));
if (!et)
return log_oom();
} else if (asprintf(&et, "%" PRIu32, record->firmware_event_type) < 0)
return log_oom();
r = json_build(&fj, JSON_BUILD_OBJECT(
JSON_BUILD_PAIR_STRING("event_type", et),
JSON_BUILD_PAIR_HEX("event_data", record->firmware_payload, record->firmware_payload_size)));
if (r < 0)
return log_error_errno(r, "Failed to build firmware event data: %m");
cd = fj;
ct = "pcclient_std";
} else if (EVENT_LOG_RECORD_IS_USERSPACE(record)) {
cd = record->userspace_content;
ct = "systemd";
}
r = json_build(ret,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR_UNSIGNED("pcr", record->pcr),
JSON_BUILD_PAIR_UNSIGNED("recnum", ++(*recnum)),
JSON_BUILD_PAIR_VARIANT("digests", ja),
JSON_BUILD_PAIR_CONDITION(ct, "content_type", JSON_BUILD_STRING(ct)),
JSON_BUILD_PAIR_CONDITION(cd, "content", JSON_BUILD_VARIANT(cd))));
if (r < 0)
return log_error_errno(r, "Failed to make CEL record: %m");
return 0;
}
static int verb_show_cel(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *array = NULL;
_cleanup_(event_log_freep) EventLog *el = NULL;
uint64_t recnum = 0;
int r;
el = event_log_new();
if (!el)
return log_oom();
r = event_log_load(el);
if (r < 0)
return r;
/* Output the event log in TCG CEL-JSON. */
FOREACH_ARRAY(rr, el->records, el->n_records) {
_cleanup_(json_variant_unrefp) JsonVariant *cel = NULL;
r = event_log_record_to_cel(*rr, &recnum, &cel);
if (r < 0)
return r;
r = json_variant_append_array(&array, cel);
if (r < 0)
return log_error_errno(r, "Failed to append CEL record: %m");
}
if (arg_json_format_flags & (JSON_FORMAT_PRETTY|JSON_FORMAT_PRETTY_AUTO))
pager_open(arg_pager_flags);
json_variant_dump(array, arg_json_format_flags|JSON_FORMAT_EMPTY_ARRAY, stdout, NULL);
return 0;
}
static int verb_list_components(int argc, char *argv[], void *userdata) {
_cleanup_(event_log_freep) EventLog *el = NULL;
_cleanup_(table_unrefp) Table *table = NULL;
enum {
BEFORE_LOCATION,
BETWEEN_LOCATION,
AFTER_LOCATION,
} loc = BEFORE_LOCATION;
int r;
el = event_log_new();
if (!el)
return log_oom();
r = event_log_add_algorithms_from_environment(el);
if (r < 0)
return r;
r = event_determine_primary_algorithm(el);
if (r < 0)
return r;
r = event_log_load_components(el);
if (r < 0)
return r;
table = table_new("id", "variants");
if (!table)
return log_oom();
FOREACH_ARRAY(c, el->components, el->n_components) {
if (FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
_cleanup_free_ char *marker = NULL;
switch (loc) {
case BEFORE_LOCATION:
if (arg_location_end && strcmp((*c)->id, arg_location_end) >= 0) {
loc = AFTER_LOCATION;
marker = strjoin(special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), " location '", arg_location_end, "' ", special_glyph(SPECIAL_GLYPH_ARROW_LEFT));
} else if (arg_location_start && strcmp((*c)->id, arg_location_start) >= 0) {
loc = BETWEEN_LOCATION;
marker = strjoin(special_glyph(SPECIAL_GLYPH_TREE_TOP), " start location '", arg_location_start, "' ", special_glyph(SPECIAL_GLYPH_ARROW_DOWN));
}
break;
case BETWEEN_LOCATION:
if (arg_location_end && strcmp((*c)->id, arg_location_end) >= 0) {
loc = AFTER_LOCATION;
marker = strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT), " end location '", arg_location_end, "' ", special_glyph(SPECIAL_GLYPH_ARROW_UP));
}
break;
case AFTER_LOCATION:
break;
}
if (marker) {
r = table_add_many(table,
TABLE_STRING, marker,
TABLE_SET_COLOR, ANSI_GREY,
TABLE_EMPTY);
if (r < 0)
return table_log_add_error(r);
}
}
FOREACH_ARRAY(variant, (*c)->variants, (*c)->n_variants) {
r = table_add_many(table,
TABLE_STRING, (*c)->id,
TABLE_PATH, (*variant)->path);
if (r < 0)
return table_log_add_error(r);
}
}
if (!table_isempty(table) || !FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, /* show_header= */ true);
if (r < 0)
return log_error_errno(r, "Failed to output table: %m");
}
if (FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
if (table_isempty(table))
printf("No components defined.\n");
else
printf("\n%zu components listed.\n", table_get_rows(table) - 1);
}
return 0;
}
static int event_log_pcr_mask_checks_out(EventLog *el, uint32_t mask) {
assert(el);
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
if (!FLAGS_SET(mask, UINT32_C(1) << pcr))
continue;
if (!event_log_pcr_checks_out(el, el->registers + pcr))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Event log for PCR %" PRIu32 " does not match PCR state, refusing.", pcr);
}
return 0;
}
static int make_pcrlock_record(
uint32_t pcr,
const void *data,
size_t data_size,
JsonVariant **ret_record) {
_cleanup_(json_variant_unrefp) JsonVariant *digests = NULL;
int r;
assert(data || data_size == 0);
assert(ret_record);
if (data_size == SIZE_MAX)
data_size = strlen(data);
/* Generates a .pcrlock record for the given PCR and data/data size. This is a subset of TCG CEL. */
FOREACH_ARRAY(pa, tpm2_hash_algorithms, TPM2_N_HASH_ALGORITHMS) {
_cleanup_free_ unsigned char *hash = NULL;
int hash_ssize;
unsigned hash_usize;
const EVP_MD *md;
const char *a;
assert_se(a = tpm2_hash_alg_to_string(*pa));
assert_se(md = EVP_get_digestbyname(a));
hash_ssize = EVP_MD_size(md);
assert(hash_ssize > 0);
hash_usize = hash_ssize;
hash = malloc(hash_usize);
if (!hash)
return log_oom();
if (EVP_Digest(data, data_size, hash, &hash_usize, md, NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash data with algorithm '%s'.", a);
r = json_variant_append_arrayb(
&digests,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("hashAlg", JSON_BUILD_STRING(a)),
JSON_BUILD_PAIR("digest", JSON_BUILD_HEX(hash, hash_usize))));
if (r < 0)
return log_error_errno(r, "Failed to build JSON digest object: %m");
}
r = json_build(ret_record,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("pcr", JSON_BUILD_UNSIGNED(pcr)),
JSON_BUILD_PAIR("digests", JSON_BUILD_VARIANT(digests))));
if (r < 0)
return log_error_errno(r, "Failed to build record object: %m");
return 0;
}
static void evp_md_ctx_free_all(EVP_MD_CTX *(*md)[TPM2_N_HASH_ALGORITHMS]) {
assert(md);
FOREACH_ARRAY(alg, *md, TPM2_N_HASH_ALGORITHMS)
if (*alg)
EVP_MD_CTX_free(*alg);
}
static int make_pcrlock_record_from_stream(
uint32_t pcr_mask,
FILE *f,
JsonVariant **ret_records) {
_cleanup_(json_variant_unrefp) JsonVariant *digests = NULL;
_cleanup_(evp_md_ctx_free_all) EVP_MD_CTX *mdctx[TPM2_N_HASH_ALGORITHMS] = {};
int r;
assert(f);
assert(ret_records);
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
const char *a;
const EVP_MD *md;
assert_se(a = tpm2_hash_alg_to_string(tpm2_hash_algorithms[i]));
assert_se(md = EVP_get_digestbyname(a));
mdctx[i] = EVP_MD_CTX_new();
if (!mdctx[i])
return log_oom();
if (EVP_DigestInit_ex(mdctx[i], md, NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
"Failed to initialize message digest for %s.", a);
}
for (;;) {
uint8_t buffer[64*1024];
size_t n;
n = fread(buffer, 1, sizeof(buffer), f);
if (ferror(f))
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to read file.");
if (n == 0 && feof(f))
break;
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++)
if (EVP_DigestUpdate(mdctx[i], buffer, n) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Unable to hash data.");
}
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
const char *a;
int hash_ssize;
unsigned hash_usize;
assert_se(a = tpm2_hash_alg_to_string(tpm2_hash_algorithms[i]));
hash_ssize = EVP_MD_CTX_size(mdctx[i]);
assert(hash_ssize > 0 && hash_ssize <= EVP_MAX_MD_SIZE);
hash_usize = hash_ssize;
unsigned char hash[hash_usize];
if (EVP_DigestFinal_ex(mdctx[i], hash, &hash_usize) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
"Failed to finalize hash context for algorithn '%s'.", a);
r = json_variant_append_arrayb(
&digests,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("hashAlg", JSON_BUILD_STRING(a)),
JSON_BUILD_PAIR("digest", JSON_BUILD_HEX(hash, hash_usize))));
if (r < 0)
return log_error_errno(r, "Failed to build JSON digest object: %m");
}
for (uint32_t i = 0; i < TPM2_PCRS_MAX; i++) {
_cleanup_(json_variant_unrefp) JsonVariant *record = NULL;
if (!FLAGS_SET(pcr_mask, UINT32_C(1) << i))
continue;
r = json_build(&record,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("pcr", JSON_BUILD_UNSIGNED(i)),
JSON_BUILD_PAIR("digests", JSON_BUILD_VARIANT(digests))));
if (r < 0)
return log_error_errno(r, "Failed to build record object: %m");
r = json_variant_append_array(ret_records, record);
if (r < 0)
return log_error_errno(r, "Failed to append to JSON array: %m");
}
return 0;
}
static const char *pcrlock_path(const char *default_pcrlock_path) {
return arg_pcrlock_path ?: arg_pcrlock_auto ? default_pcrlock_path : NULL;
}
static int write_pcrlock(JsonVariant *array, const char *default_pcrlock_path) {
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL, *a = NULL;
_cleanup_fclose_ FILE *f = NULL;
const char *p;
int r;
if (!array) {
r = json_variant_new_array(&a, NULL, 0);
if (r < 0)
return log_error_errno(r, "Failed to allocate empty array: %m");
array = a;
}
r = json_build(&v, JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("records", JSON_BUILD_VARIANT(array))));
if (r < 0)
return log_error_errno(r, "Failed to build JSON object: %m");
p = pcrlock_path(default_pcrlock_path);
if (p) {
(void) mkdir_parents_label(p, 0755);
f = fopen(p, "we");
if (!f)
return log_error_errno(errno, "Failed to open %s for writing: %m", p);
}
r = json_variant_dump(v, arg_json_format_flags, f ?: stdout, /* prefix= */ NULL);
if (r < 0)
return log_error_errno(r, "Failed to output JSON object: %m");
if (p)
log_info("%s written.", p);
return 0;
}
static int unlink_pcrlock(const char *default_pcrlock_path) {
const char *p;
p = pcrlock_path(default_pcrlock_path);
if (!p)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No .pcrlock path specified, refusing.");
if (unlink(p) < 0) {
if (errno != ENOENT)
return log_error_errno(errno, "Failed to delete %s: %m", p);
log_info("%s already deleted.", p);
} else
log_info("%s deleted.", p);
(void) rmdir_parents(p, "/var/lib");
return 0;
}
static int verb_lock_raw(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *records = NULL;
_cleanup_fclose_ FILE *f = NULL;
int r;
if (arg_pcr_mask == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No PCR specified, refusing.");
if (argc >= 2) {
f = fopen(argv[1], "re");
if (!f)
return log_error_errno(errno, "Failed to open '%s': %m", argv[1]);
}
r = make_pcrlock_record_from_stream(arg_pcr_mask, f ?: stdin, &records);
if (r < 0)
return r;
return write_pcrlock(records, NULL);
}
static int verb_unlock_simple(int argc, char *argv[], void *userdata) {
return unlink_pcrlock(NULL);
}
static int verb_lock_secureboot_policy(int argc, char *argv[], void *userdata) {
static const struct {
sd_id128_t id;
const char *name;
int synthesize_empty; /* 0 → fail, > 0 → synthesize empty db, < 0 → skip */
} variables[] = {
{ EFI_VENDOR_GLOBAL, "SecureBoot", 0 },
{ EFI_VENDOR_GLOBAL, "PK", 1 },
{ EFI_VENDOR_GLOBAL, "KEK", 1 },
{ EFI_VENDOR_DATABASE, "db", 1 },
{ EFI_VENDOR_DATABASE, "dbx", 1 },
{ EFI_VENDOR_DATABASE, "dbt", -1 },
{ EFI_VENDOR_DATABASE, "dbr", -1 },
};
_cleanup_(json_variant_unrefp) JsonVariant *array = NULL;
int r;
/* Generates expected records from the current SecureBoot state, as readable in the EFI variables
* right now. */
FOREACH_ELEMENT(vv, variables) {
_cleanup_(json_variant_unrefp) JsonVariant *record = NULL;
_cleanup_free_ char *name = NULL;
if (asprintf(&name, "%s-" SD_ID128_UUID_FORMAT_STR, vv->name, SD_ID128_FORMAT_VAL(vv->id)) < 0)
return log_oom();
_cleanup_free_ void *data = NULL;
size_t data_size;
r = efi_get_variable(name, NULL, &data, &data_size);
if (r < 0) {
if (r != -ENOENT || vv->synthesize_empty == 0)
return log_error_errno(r, "Failed to read EFI variable '%s': %m", name);
if (vv->synthesize_empty < 0)
continue;
/* If the main database variables are not set we don't consider this an error, but
* measure an empty database instead. */
log_debug("EFI variable %s is not set, synthesizing empty variable for measurement.", name);
data_size = 0;
}
_cleanup_free_ char16_t* name16 = utf8_to_utf16(vv->name, SIZE_MAX);
if (!name16)
return log_oom();
size_t name16_bytes = char16_strlen(name16) * 2;
size_t vdata_size = offsetof(UEFI_VARIABLE_DATA, unicodeName) + name16_bytes + data_size;
_cleanup_free_ UEFI_VARIABLE_DATA *vdata = malloc(vdata_size);
if (!vdata)
return log_oom();
*vdata = (UEFI_VARIABLE_DATA) {
.unicodeNameLength = name16_bytes / 2,
.variableDataLength = data_size,
};
efi_id128_to_guid(vv->id, vdata->variableName);
memcpy(mempcpy(vdata->unicodeName, name16, name16_bytes), data, data_size);
r = make_pcrlock_record(TPM2_PCR_SECURE_BOOT_POLICY /* =7 */, vdata, vdata_size, &record);
if (r < 0)
return r;
r = json_variant_append_array(&array, record);
if (r < 0)
return log_error_errno(r, "Failed to append to JSON array: %m");
}
return write_pcrlock(array, PCRLOCK_SECUREBOOT_POLICY_PATH);
}
static int verb_unlock_secureboot_policy(int argc, char *argv[], void *userdata) {
return unlink_pcrlock(PCRLOCK_SECUREBOOT_POLICY_PATH);
}
static int event_log_record_is_secureboot_variable(EventLogRecord *rec, sd_id128_t uuid, const char *name) {
_cleanup_free_ char *found_name = NULL;
sd_id128_t found_uuid;
int r;
assert(rec);
assert(name);
if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
return false;
if (rec->pcr != TPM2_PCR_SECURE_BOOT_POLICY)
return false;
if (rec->event_payload_valid != EVENT_PAYLOAD_VALID_YES)
return false;
if (rec->firmware_event_type != EV_EFI_VARIABLE_DRIVER_CONFIG)
return false;
r = event_log_record_parse_variable_data(rec, &found_uuid, &found_name);
if (r == -EBADMSG)
return false;
if (r < 0)
return r;
if (!sd_id128_equal(found_uuid, uuid))
return false;
return streq(found_name, name);
}
static bool event_log_record_is_secureboot_authority(EventLogRecord *rec) {
assert(rec);
if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
return false;
if (rec->pcr != TPM2_PCR_SECURE_BOOT_POLICY)
return false;
if (rec->event_payload_valid != EVENT_PAYLOAD_VALID_YES)
return false;
return rec->firmware_event_type == EV_EFI_VARIABLE_AUTHORITY;
}
static int event_log_ensure_secureboot_consistency(EventLog *el) {
static const struct {
sd_id128_t id;
const char *name;
bool required;
} table[] = {
{ EFI_VENDOR_GLOBAL, "SecureBoot", true },
{ EFI_VENDOR_GLOBAL, "PK", true },
{ EFI_VENDOR_GLOBAL, "KEK", true },
{ EFI_VENDOR_DATABASE, "db", true },
{ EFI_VENDOR_DATABASE, "dbx", true },
{ EFI_VENDOR_DATABASE, "dbt", false },
{ EFI_VENDOR_DATABASE, "dbr", false },
// FIXME: ensure we also find the separator here
};
EventLogRecord *records[ELEMENTSOF(table)] = {};
EventLogRecord *first_authority = NULL;
assert(el);
/* Ensures that the PCR 7 records are complete and in order. Before we lock down PCR 7 we want to
* ensure its state is actually consistent. */
FOREACH_ARRAY(rr, el->records, el->n_records) {
EventLogRecord *rec = *rr;
size_t found = SIZE_MAX;
if (event_log_record_is_secureboot_authority(rec)) {
if (first_authority)
continue;
first_authority = rec;
// FIXME: also check that each authority record's data is also listed in 'db'
continue;
}
for (size_t i = 0; i < ELEMENTSOF(table); i++)
if (event_log_record_is_secureboot_variable(rec, table[i].id, table[i].name)) {
found = i;
break;
}
if (found == SIZE_MAX)
continue;
/* Require the authority records always come *after* database measurements */
if (first_authority)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "SecureBoot authority before variable, refusing.");
/* Check for duplicates */
if (records[found])
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Duplicate '%s' record, refusing.", rec->description);
/* Check for order */
for (size_t j = found + 1; j < ELEMENTSOF(table); j++)
if (records[j])
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'%s' record before '%s' record, refusing.", records[j]->description, rec->description);
records[found] = rec;
}
/* Check for existence */
for (size_t i = 0; i < ELEMENTSOF(table); i++)
if (table[i].required && !records[i])
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Required record '%s' not found, refusing.", table[i].name);
/* At this point we know that all required variables have been measured, in the right order. */
return 0;
}
static int verb_lock_secureboot_authority(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *array = NULL;
_cleanup_(event_log_freep) EventLog *el = NULL;
int r;
/* Lock down the EV_EFI_VARIABLE_AUTHORITY records from the existing log. Note that there's not too
* much value in locking this down too much, since it stores only the result of the primary database
* checks, and that's what we should bind policy to. Moreover it's hard to predict, since extension
* card firmware validation will result in additional records here. */
if (!is_efi_secure_boot()) {
log_info("SecureBoot disabled, not generating authority .pcrlock file.");
return unlink_pcrlock(PCRLOCK_SECUREBOOT_AUTHORITY_PATH);
}
el = event_log_new();
if (!el)
return log_oom();
r = event_log_add_algorithms_from_environment(el);
if (r < 0)
return r;
r = event_log_load(el);
if (r < 0)
return r;
r = event_log_read_pcrs(el);
if (r < 0)
return r;
r = event_log_calculate_pcrs(el);
if (r < 0)
return r;
/* Before we base anything on the event log records, let's check that the event log state checks
* out. */
r = event_log_pcr_mask_checks_out(el, UINT32_C(1) << TPM2_PCR_SECURE_BOOT_POLICY);
if (r < 0)
return r;
r = event_log_validate_record_hashes(el);
if (r < 0)
return r;
r = event_log_ensure_secureboot_consistency(el);
if (r < 0)
return r;
FOREACH_ARRAY(rr, el->records, el->n_records) {
_cleanup_(json_variant_unrefp) JsonVariant *digests = NULL;
EventLogRecord *rec = *rr;
if (!event_log_record_is_secureboot_authority(rec))
continue;
log_debug("Locking down authority '%s'.", strna(rec->description));
LIST_FOREACH(banks, bank, rec->banks) {
r = json_variant_append_arrayb(
&digests,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("hashAlg", JSON_BUILD_STRING(tpm2_hash_alg_to_string(bank->algorithm))),
JSON_BUILD_PAIR("digest", JSON_BUILD_HEX(bank->hash.buffer, bank->hash.size))));
if (r < 0)
return log_error_errno(r, "Failed to build digests array: %m");
}
r = json_variant_append_arrayb(
&array,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("pcr", JSON_BUILD_UNSIGNED(rec->pcr)),
JSON_BUILD_PAIR("digests", JSON_BUILD_VARIANT(digests))));
if (r < 0)
return log_error_errno(r, "Failed to build record array: %m");
}
return write_pcrlock(array, PCRLOCK_SECUREBOOT_AUTHORITY_PATH);
}
static int verb_unlock_secureboot_authority(int argc, char *argv[], void *userdata) {
return unlink_pcrlock(PCRLOCK_SECUREBOOT_AUTHORITY_PATH);
}
static int verb_lock_gpt(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *array = NULL, *record = NULL;
_cleanup_(sd_device_unrefp) sd_device *d = NULL;
uint8_t h[2 * 4096]; /* space for at least two 4K sectors. GPT header should definitely be in here */
uint64_t start, n_members, member_size;
_cleanup_close_ int fd = -EBADF;
const GptHeader *p;
size_t found = 0;
ssize_t n;
int r;
r = block_device_new_from_path(
argc >= 2 ? argv[1] : "/",
BLOCK_DEVICE_LOOKUP_WHOLE_DISK|BLOCK_DEVICE_LOOKUP_BACKING|BLOCK_DEVICE_LOOKUP_ORIGINATING,
&d);
if (r < 0)
return log_error_errno(r, "Failed to determine root block device: %m");
fd = sd_device_open(d, O_CLOEXEC|O_RDONLY|O_NOCTTY);
if (fd < 0)
return log_error_errno(fd, "Failed to open root block device: %m");
n = pread(fd, &h, sizeof(h), 0);
if (n < 0)
return log_error_errno(errno, "Failed to read GPT header of block device: %m");
if ((size_t) n != sizeof(h))
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short read trying to read GPT header.");
/* Try a couple of sector sizes */
for (size_t sz = 512; sz <= 4096; sz <<= 1) {
assert(sizeof(h) >= sz * 2);
p = (const GptHeader*) (h + sz); /* 2nd sector */
if (!gpt_header_has_signature(p))
continue;
if (found != 0)
return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
"Disk has partition table for multiple sector sizes, refusing.");
found = sz;
}
if (found == 0)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
"Disk does not have GPT partition table, refusing.");
p = (const GptHeader*) (h + found);
if (le32toh(p->header_size) > found)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
"GPT header size over long (%" PRIu32 "), refusing.", le32toh(p->header_size));
start = le64toh(p->partition_entry_lba);
if (start > UINT64_MAX / found)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
"Partition table start offset overflow, refusing.");
member_size = le32toh(p->size_of_partition_entry);
if (member_size < sizeof(GptPartitionEntry))
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
"Partition entry size too short, refusing.");
n_members = le32toh(p->number_of_partition_entries);
uint64_t member_bufsz = n_members * member_size;
if (member_bufsz > 1U*1024U*1024U)
return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
"Partition table size too large, refusing.");
member_bufsz = ROUND_UP(member_bufsz, found);
_cleanup_free_ void *members = malloc(member_bufsz);
if (!members)
return log_oom();
n = pread(fd, members, member_bufsz, start * found);
if (n < 0)
return log_error_errno(errno, "Failed to read GPT partition table entries: %m");
if ((size_t) n != member_bufsz)
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short read while reading GPT partition table entries.");
size_t vdata_size = le32toh(p->header_size) + sizeof(le64_t) + member_size * n_members;
_cleanup_free_ void *vdata = malloc0(vdata_size);
if (!vdata)
return log_oom();
void *n_measured_entries = mempcpy(vdata, p, sizeof(GptHeader)); /* n_measured_entries is a 64bit value */
void *qq = (uint8_t*) n_measured_entries + sizeof(le64_t);
for (uint64_t i = 0; i < n_members; i++) {
const GptPartitionEntry *entry = (const GptPartitionEntry*) ((const uint8_t*) members + (member_size * i));
if (memeqzero(entry->partition_type_guid, sizeof(entry->partition_type_guid)))
continue;
qq = mempcpy(qq, entry, member_size);
unaligned_write_le64(n_measured_entries, unaligned_read_le64(n_measured_entries) + 1);
}
vdata_size = (uint8_t*) qq - (uint8_t*) vdata;
r = make_pcrlock_record(TPM2_PCR_BOOT_LOADER_CONFIG /* =5 */, vdata, vdata_size, &record);
if (r < 0)
return r;
r = json_variant_new_array(&array, &record, 1);
if (r < 0)
return log_error_errno(r, "Failed to append to JSON array: %m");
return write_pcrlock(array, PCRLOCK_GPT_PATH);
}
static int verb_unlock_gpt(int argc, char *argv[], void *userdata) {
return unlink_pcrlock(PCRLOCK_GPT_PATH);
}
static bool event_log_record_is_separator(const EventLogRecord *rec) {
assert(rec);
/* Recognizes EV_SEPARATOR events */
if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
return false;
if (rec->firmware_event_type != EV_SEPARATOR)
return false;
return rec->event_payload_valid == EVENT_PAYLOAD_VALID_YES; /* Insist the record is consistent */
}
static int event_log_record_is_action_calling_efi_app(const EventLogRecord *rec) {
_cleanup_free_ char *d = NULL;
int r;
assert(rec);
/* Recognizes the special EV_EFI_ACTION that is issues when the firmware passes control to the boot loader. */
if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
return false;
if (rec->pcr != TPM2_PCR_BOOT_LOADER_CODE)
return false;
if (rec->firmware_event_type != EV_EFI_ACTION)
return false;
if (rec->event_payload_valid != EVENT_PAYLOAD_VALID_YES) /* Insist the record is consistent */
return false;
r = make_cstring(rec->firmware_payload, rec->firmware_payload_size, MAKE_CSTRING_ALLOW_TRAILING_NUL, &d);
if (r < 0)
return r;
return streq(d, "Calling EFI Application from Boot Option");
}
static void enable_json_sse(void) {
/* We shall write this to a single output stream? We have to output two files, hence try to be smart
* and enable JSON SSE */
if (!arg_pcrlock_path && arg_pcrlock_auto)
return;
if (FLAGS_SET(arg_json_format_flags, JSON_FORMAT_SSE))
return;
log_notice("Enabling JSON_SEQ mode, since writing two .pcrlock files to single output.");
arg_json_format_flags |= JSON_FORMAT_SSE;
}
static int verb_lock_firmware(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *array_early = NULL, *array_late = NULL;
_cleanup_(event_log_freep) EventLog *el = NULL;
uint32_t always_mask, separator_mask, separator_seen_mask = 0, action_seen_mask = 0;
const char *default_pcrlock_early_path, *default_pcrlock_late_path;
int r;
enable_json_sse();
/* The PCRs we intend to cover. Note that we measure firmware, external *and* boot loader code/config
* here – but the latter only until the "separator" events are seen, which tell us where transition
* into OS boot loader happens. This reflects the fact that on some systems the firmware already
* measures some firmware-supplied apps into PCR 4. (e.g. Thinkpad X1 Gen9) */
if (endswith(argv[0], "firmware-code")) {
always_mask = (UINT32_C(1) << TPM2_PCR_PLATFORM_CODE) | /* → 0 */
(UINT32_C(1) << TPM2_PCR_EXTERNAL_CODE); /* → 2 */
separator_mask = UINT32_C(1) << TPM2_PCR_BOOT_LOADER_CODE; /* → 4 */
default_pcrlock_early_path = PCRLOCK_FIRMWARE_CODE_EARLY_PATH;
default_pcrlock_late_path = PCRLOCK_FIRMWARE_CODE_LATE_PATH;
} else {
assert(endswith(argv[0], "firmware-config"));
always_mask = (UINT32_C(1) << TPM2_PCR_PLATFORM_CONFIG) | /* → 1 */
(UINT32_C(1) << TPM2_PCR_EXTERNAL_CONFIG); /* → 3 */
separator_mask = UINT32_C(1) << TPM2_PCR_BOOT_LOADER_CONFIG; /* → 5 */
default_pcrlock_early_path = PCRLOCK_FIRMWARE_CONFIG_EARLY_PATH;
default_pcrlock_late_path = PCRLOCK_FIRMWARE_CONFIG_LATE_PATH;
}
el = event_log_new();
if (!el)
return log_oom();
r = event_log_add_algorithms_from_environment(el);
if (r < 0)
return r;
r = event_log_load(el);
if (r < 0)
return r;
r = event_log_read_pcrs(el);
if (r < 0)
return r;
r = event_log_calculate_pcrs(el);
if (r < 0)
return r;
r = event_log_validate_record_hashes(el);
if (r < 0)
return r;
/* Before we base anything on the event log records for any of the selected PCRs, let's check that
* the event log state checks out for them. */
r = event_log_pcr_mask_checks_out(el, always_mask|separator_mask);
if (r < 0)
return r;
// FIXME: before doing this, validate ahead-of-time that EV_SEPARATOR records exist for all entries,
// and exactly once
FOREACH_ARRAY(rr, el->records, el->n_records) {
_cleanup_(json_variant_unrefp) JsonVariant *digests = NULL;
EventLogRecord *rec = *rr;
uint32_t bit = UINT32_C(1) << rec->pcr;
if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
continue;
if (!FLAGS_SET(always_mask, bit) &&
!(FLAGS_SET(separator_mask, bit) && !FLAGS_SET(separator_seen_mask|action_seen_mask, bit)))
continue;
/* If we hit the separator record, we stop processing the PCRs listed in `separator_mask` */
if (event_log_record_is_separator(rec)) {
separator_seen_mask |= bit;
continue;
}
/* If we hit the special "Calling EFI Application from Boot Option" action we treat this the
* same as a separator here, as that's where firmware passes control to boot loader. Note
* that some EFI implementations forget to generate one of them. */
r = event_log_record_is_action_calling_efi_app(rec);
if (r < 0)
return log_error_errno(r, "Failed to check if event is 'Calling EFI Application from Boot Option' action: %m");
if (r > 0) {
action_seen_mask |= bit;
continue;
}
LIST_FOREACH(banks, bank, rec->banks) {
r = json_variant_append_arrayb(
&digests,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("hashAlg", JSON_BUILD_STRING(tpm2_hash_alg_to_string(bank->algorithm))),
JSON_BUILD_PAIR("digest", JSON_BUILD_HEX(bank->hash.buffer, bank->hash.size))));
if (r < 0)
return log_error_errno(r, "Failed to build digests array: %m");
}
r = json_variant_append_arrayb(
FLAGS_SET(separator_seen_mask, bit) ? &array_late : &array_early,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("pcr", JSON_BUILD_UNSIGNED(rec->pcr)),
JSON_BUILD_PAIR("digests", JSON_BUILD_VARIANT(digests))));
if (r < 0)
return log_error_errno(r, "Failed to build record array: %m");
}
r = write_pcrlock(array_early, default_pcrlock_early_path);
if (r < 0)
return r;
return write_pcrlock(array_late, default_pcrlock_late_path);
}
static int verb_unlock_firmware(int argc, char *argv[], void *userdata) {
const char *default_pcrlock_early_path, *default_pcrlock_late_path;
int r;
if (endswith(argv[0], "firmware-code")) {
default_pcrlock_early_path = PCRLOCK_FIRMWARE_CODE_EARLY_PATH;
default_pcrlock_late_path = PCRLOCK_FIRMWARE_CODE_LATE_PATH;
} else {
default_pcrlock_early_path = PCRLOCK_FIRMWARE_CONFIG_EARLY_PATH;
default_pcrlock_late_path = PCRLOCK_FIRMWARE_CONFIG_LATE_PATH;
}
r = unlink_pcrlock(default_pcrlock_early_path);
if (r < 0)
return r;
if (arg_pcrlock_path) /* if the path is specified don't delete the same thing twice */
return 0;
r = unlink_pcrlock(default_pcrlock_late_path);
if (r < 0)
return r;
return 0;
}
static int verb_lock_machine_id(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *record = NULL, *array = NULL;
_cleanup_free_ char *word = NULL;
int r;
r = pcrextend_machine_id_word(&word);
if (r < 0)
return r;
r = make_pcrlock_record(TPM2_PCR_SYSTEM_IDENTITY /* = 15 */, word, SIZE_MAX, &record);
if (r < 0)
return r;
r = json_variant_new_array(&array, &record, 1);
if (r < 0)
return log_error_errno(r, "Failed to create record array: %m");
return write_pcrlock(array, PCRLOCK_MACHINE_ID_PATH);
}
static int verb_unlock_machine_id(int argc, char *argv[], void *userdata) {
return unlink_pcrlock(PCRLOCK_MACHINE_ID_PATH);
}
static int pcrlock_file_system_path(const char *normalized_path, char **ret) {
_cleanup_free_ char *s = NULL;
assert(normalized_path);
if (path_equal(normalized_path, "/"))
s = strdup(PCRLOCK_ROOT_FILE_SYSTEM_PATH);
else {
/* We reuse the escaping we use for turning paths into unit names */
_cleanup_free_ char *escaped = NULL;
assert(normalized_path[0] == '/');
assert(normalized_path[1] != '/');
escaped = unit_name_escape(normalized_path + 1);
if (!escaped)
return log_oom();
s = strjoin(PCRLOCK_FILE_SYSTEM_PATH_PREFIX, escaped, ".pcrlock");
}
if (!s)
return log_oom();
*ret = TAKE_PTR(s);
return 0;
}
static int verb_lock_file_system(int argc, char *argv[], void *userdata) {
const char* paths[3] = {};
int r;
if (argc > 1)
paths[0] = argv[1];
else {
dev_t a, b;
paths[0] = "/";
r = get_block_device("/", &a);
if (r < 0)
return log_error_errno(r, "Failed to get device of root file system: %m");
r = get_block_device("/var", &b);
if (r < 0)
return log_error_errno(r, "Failed to get device of /var/ file system: %m");
/* if backing device is distinct, then measure /var/ too */
if (a != b)
paths[1] = "/var";
enable_json_sse();
}
STRV_FOREACH(p, paths) {
_cleanup_free_ char *word = NULL, *normalized_path = NULL, *pcrlock_file = NULL;
_cleanup_(json_variant_unrefp) JsonVariant *record = NULL, *array = NULL;
r = pcrextend_file_system_word(*p, &word, &normalized_path);
if (r < 0)
return r;
r = pcrlock_file_system_path(normalized_path, &pcrlock_file);
if (r < 0)
return r;
r = make_pcrlock_record(TPM2_PCR_SYSTEM_IDENTITY /* = 15 */, word, SIZE_MAX, &record);
if (r < 0)
return r;
r = json_variant_new_array(&array, &record, 1);
if (r < 0)
return log_error_errno(r, "Failed to create record array: %m");
r = write_pcrlock(array, pcrlock_file);
if (r < 0)
return r;
}
return 0;
}
static int verb_unlock_file_system(int argc, char *argv[], void *userdata) {
const char* paths[3] = {};
int r;
if (argc > 1)
paths[0] = argv[1];
else {
paths[0] = "/";
paths[1] = "/var";
}
STRV_FOREACH(p, paths) {
_cleanup_free_ char *normalized_path = NULL, *pcrlock_file = NULL;
r = chase(*p, NULL, 0, &normalized_path, NULL);
if (r < 0)
return log_error_errno(r, "Failed to normal path '%s': %m", argv[1]);
r = pcrlock_file_system_path(normalized_path, &pcrlock_file);
if (r < 0)
return r;
r = unlink_pcrlock(pcrlock_file);
if (r < 0)
return r;
}
return 0;
}
static int verb_lock_pe(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *array = NULL;
_cleanup_close_ int fd = -EBADF;
int r;
// FIXME: Maybe also generate a matching EV_EFI_VARIABLE_AUTHORITY records here for each signature that
// covers this PE plus its hash, as alternatives under the same component name
if (argc >= 2) {
fd = open(argv[1], O_RDONLY|O_CLOEXEC);
if (fd < 0)
return log_error_errno(errno, "Failed to open '%s': %m", argv[1]);
}
if (arg_pcr_mask == 0)
arg_pcr_mask = UINT32_C(1) << TPM2_PCR_BOOT_LOADER_CODE;
for (uint32_t i = 0; i < TPM2_PCRS_MAX; i++) {
_cleanup_(json_variant_unrefp) JsonVariant *digests = NULL;
if (!FLAGS_SET(arg_pcr_mask, UINT32_C(1) << i))
continue;
FOREACH_ARRAY(pa, tpm2_hash_algorithms, TPM2_N_HASH_ALGORITHMS) {
_cleanup_free_ void *hash = NULL;
size_t hash_size;
const EVP_MD *md;
const char *a;
assert_se(a = tpm2_hash_alg_to_string(*pa));
assert_se(md = EVP_get_digestbyname(a));
r = pe_hash(fd < 0 ? STDIN_FILENO : fd, md, &hash, &hash_size);
if (r < 0)
return log_error_errno(r, "Failed to hash PE binary: %m");
r = json_variant_append_arrayb(&digests,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("hashAlg", JSON_BUILD_STRING(a)),
JSON_BUILD_PAIR("digest", JSON_BUILD_HEX(hash, hash_size))));
if (r < 0)
return log_error_errno(r, "Failed to build JSON digest object: %m");
}
r = json_variant_append_arrayb(
&array,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("pcr", JSON_BUILD_UNSIGNED(i)),
JSON_BUILD_PAIR("digests", JSON_BUILD_VARIANT(digests))));
if (r < 0)
return log_error_errno(r, "Failed to append record object: %m");
}
return write_pcrlock(array, NULL);
}
typedef void* SectionHashArray[_UNIFIED_SECTION_MAX * TPM2_N_HASH_ALGORITHMS];
static void section_hashes_array_done(SectionHashArray *array) {
assert(array);
for (size_t i = 0; i < _UNIFIED_SECTION_MAX * TPM2_N_HASH_ALGORITHMS; i++)
free((*array)[i]);
}
static int verb_lock_uki(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *array = NULL, *pe_digests = NULL;
_cleanup_(section_hashes_array_done) SectionHashArray section_hashes = {};
size_t hash_sizes[TPM2_N_HASH_ALGORITHMS];
_cleanup_close_ int fd = -EBADF;
int r;
if (arg_pcr_mask != 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PCR not configurable for UKI lock down.");
if (argc >= 2) {
fd = open(argv[1], O_RDONLY|O_CLOEXEC);
if (fd < 0)
return log_error_errno(errno, "Failed to open '%s': %m", argv[1]);
}
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
_cleanup_free_ void *peh = NULL;
const EVP_MD *md;
const char *a;
assert_se(a = tpm2_hash_alg_to_string(tpm2_hash_algorithms[i]));
assert_se(md = EVP_get_digestbyname(a));
r = pe_hash(fd < 0 ? STDIN_FILENO : fd, md, &peh, hash_sizes + i);
if (r < 0)
return log_error_errno(r, "Failed to hash PE binary: %m");
r = json_variant_append_arrayb(
&pe_digests,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("hashAlg", JSON_BUILD_STRING(a)),
JSON_BUILD_PAIR("digest", JSON_BUILD_HEX(peh, hash_sizes[i]))));
if (r < 0)
return log_error_errno(r, "Failed to build JSON digest object: %m");
r = uki_hash(fd < 0 ? STDIN_FILENO : fd, md, section_hashes + (i * _UNIFIED_SECTION_MAX), hash_sizes + i);
if (r < 0)
return log_error_errno(r, "Failed to UKI hash PE binary: %m");
}
r = json_variant_append_arrayb(
&array,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("pcr", JSON_BUILD_UNSIGNED(TPM2_PCR_BOOT_LOADER_CODE)),
JSON_BUILD_PAIR("digests", JSON_BUILD_VARIANT(pe_digests))));
if (r < 0)
return log_error_errno(r, "Failed to append record object: %m");
for (UnifiedSection section = 0; section < _UNIFIED_SECTION_MAX; section++) {
_cleanup_(json_variant_unrefp) JsonVariant *section_digests = NULL, *record = NULL;
if (!unified_section_measure(section))
continue;
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
const char *a;
void *hash;
hash = section_hashes[i * _UNIFIED_SECTION_MAX + section];
if (!hash)
continue;
assert_se(a = tpm2_hash_alg_to_string(tpm2_hash_algorithms[i]));
r = json_variant_append_arrayb(
§ion_digests,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("hashAlg", JSON_BUILD_STRING(a)),
JSON_BUILD_PAIR("digest", JSON_BUILD_HEX(hash, hash_sizes[i]))));
if (r < 0)
return log_error_errno(r, "Failed to build JSON digest object: %m");
}
if (!section_digests)
continue;
/* So we have digests for this section, hence generate a record for the section name first. */
r = make_pcrlock_record(TPM2_PCR_KERNEL_BOOT /* =11 */, unified_sections[section], strlen(unified_sections[section]) + 1, &record);
if (r < 0)
return r;
r = json_variant_append_array(&array, record);
if (r < 0)
return log_error_errno(r, "Failed to append JSON record array: %m");
/* And then append a record for the section contents digests as well */
r = json_variant_append_arrayb(
&array,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("pcr", JSON_BUILD_UNSIGNED(TPM2_PCR_KERNEL_BOOT /* =11 */)),
JSON_BUILD_PAIR("digests", JSON_BUILD_VARIANT(section_digests))));
if (r < 0)
return log_error_errno(r, "Failed to append record object: %m");
}
return write_pcrlock(array, NULL);
}
static int event_log_reduce_to_safe_pcrs(EventLog *el, uint32_t *pcrs) {
_cleanup_free_ char *dropped = NULL, *kept = NULL;
assert(el);
assert(pcrs);
/* When we compile a new PCR policy we don't want to bind to PCRs which are fishy for one of three
* reasons:
*
* 1. The PCR value doesn't match the event log
* 2. The event log for the PCR contains measurements we don't know responsible components for
* 3. The event log for the PCR does not contain measurements for components we know
*
* This function checks for the three conditions and drops the PCR from the mask.
*/
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
if (!FLAGS_SET(*pcrs, UINT32_C(1) << pcr))
continue;
if (!event_log_pcr_checks_out(el, el->registers + pcr)) {
log_notice("PCR %" PRIu32 " (%s) value does not match event log. Removing from set of PCRs.", pcr, strna(tpm2_pcr_index_to_string(pcr)));
goto drop;
}
if (!el->registers[pcr].fully_recognized) {
log_notice("PCR %" PRIu32 " (%s) event log contains unrecognized measurements. Removing from set of PCRs.", pcr, strna(tpm2_pcr_index_to_string(pcr)));
goto drop;
}
if (FLAGS_SET(el->missing_component_pcrs, UINT32_C(1) << pcr)) {
log_notice("PCR %" PRIu32 " (%s) is touched by component we can't find in event log. Removing from set of PCRs.", pcr, strna(tpm2_pcr_index_to_string(pcr)));
goto drop;
}
log_info("PCR %" PRIu32 " (%s) matches event log and fully consists of recognized measurements. Including in set of PCRs.", pcr, strna(tpm2_pcr_index_to_string(pcr)));
if (strextendf_with_separator(&kept, ", ", "%" PRIu32 " (%s)", pcr, tpm2_pcr_index_to_string(pcr)) < 0)
return log_oom();
continue;
drop:
*pcrs &= ~(UINT32_C(1) << pcr);
if (strextendf_with_separator(&dropped, ", ", "%" PRIu32 " (%s)", pcr, tpm2_pcr_index_to_string(pcr)) < 0)
return log_oom();
}
if (dropped)
log_notice("PCRs dropped from protection mask: %s", dropped);
else
log_debug("No PCRs dropped from protection mask.");
if (kept)
log_notice("PCRs in protection mask: %s", kept);
else
log_notice("No PCRs kept in protection mask.");
return 0;
}
static int verb_lock_kernel_cmdline(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *record = NULL, *array = NULL;
_cleanup_free_ char *cmdline = NULL;
int r;
if (argc > 1) {
if (empty_or_dash(argv[1]))
r = read_full_stream(stdin, &cmdline, NULL);
else
r = read_full_file(argv[1], &cmdline, NULL);
} else
r = proc_cmdline(&cmdline);
if (r < 0)
return log_error_errno(r, "Failed to read cmdline: %m");
delete_trailing_chars(cmdline, "\n");
_cleanup_free_ char16_t *u = NULL;
u = utf8_to_utf16(cmdline, SIZE_MAX);
if (!u)
return log_oom();
r = make_pcrlock_record(TPM2_PCR_KERNEL_INITRD /* = 9 */, u, char16_strlen(u)*2+2, &record);
if (r < 0)
return r;
r = json_variant_new_array(&array, &record, 1);
if (r < 0)
return log_error_errno(r, "Failed to create record array: %m");
r = write_pcrlock(array, PCRLOCK_KERNEL_CMDLINE_PATH);
if (r < 0)
return r;
return 0;
}
static int verb_unlock_kernel_cmdline(int argc, char *argv[], void *userdata) {
return unlink_pcrlock(PCRLOCK_KERNEL_CMDLINE_PATH);
}
static int verb_lock_kernel_initrd(int argc, char *argv[], void *userdata) {
_cleanup_(json_variant_unrefp) JsonVariant *records = NULL;
_cleanup_fclose_ FILE *f = NULL;
uint32_t pcr_mask = UINT32_C(1) << TPM2_PCR_KERNEL_INITRD;
int r;
if (argc >= 2) {
f = fopen(argv[1], "re");
if (!f)
return log_error_errno(errno, "Failed to open '%s': %m", argv[1]);
}
r = make_pcrlock_record_from_stream(pcr_mask, f ?: stdin, &records);
if (r < 0)
return r;
r = write_pcrlock(records, PCRLOCK_KERNEL_INITRD_PATH);
if (r < 0)
return r;
return 0;
}
static int verb_unlock_kernel_initrd(int argc, char *argv[], void *userdata) {
return unlink_pcrlock(PCRLOCK_KERNEL_INITRD_PATH);
}
static int pcr_prediction_add_result(
Tpm2PCRPrediction *context,
Tpm2PCRPredictionResult *result,
uint32_t pcr,
const char *path,
size_t offset) {
_cleanup_free_ Tpm2PCRPredictionResult *copy = NULL;
int r;
assert(context);
assert(result);
copy = newdup(Tpm2PCRPredictionResult, result, 1);
if (!copy)
return log_oom();
r = ordered_set_ensure_put(context->results + pcr, &tpm2_pcr_prediction_result_hash_ops, copy);
if (r == -EEXIST) /* Multiple identical results for the same PCR are totally expected */
return 0;
if (r < 0)
return log_error_errno(r, "Failed to insert result into set: %m");
log_debug("Added prediction result %u for PCR %" PRIu32 " (path: %s)", ordered_set_size(context->results[pcr]), pcr, strempty(path));
TAKE_PTR(copy);
return 0;
}
static const EVP_MD* evp_from_tpm2_alg(uint16_t alg) {
const char *name;
name = tpm2_hash_alg_to_string(alg);
if (!name)
return NULL;
return EVP_get_digestbyname(name);
}
static int event_log_component_variant_calculate(
Tpm2PCRPrediction *context,
Tpm2PCRPredictionResult *result,
EventLogComponent *component,
EventLogComponentVariant *variant,
uint32_t pcr,
const char *path) {
int r;
assert(context);
assert(result);
assert(component);
assert(variant);
FOREACH_ARRAY(rr, variant->records, variant->n_records) {
EventLogRecord *rec = *rr;
if (rec->pcr != pcr)
continue;
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
_cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *md_ctx = NULL;
EventLogRecordBank *b;
if (result->hash[i].size <= 0) /* already invalidated */
continue;
b = event_log_record_find_bank(rec, tpm2_hash_algorithms[i]);
if (!b) {
/* Can't calculate, hence invalidate */
result->hash[i] = (TPM2B_DIGEST) {};
continue;
}
md_ctx = EVP_MD_CTX_new();
if (!md_ctx)
return log_oom();
const EVP_MD *md = ASSERT_PTR(evp_from_tpm2_alg(tpm2_hash_algorithms[i]));
int sz = EVP_MD_size(md);
assert(sz > 0);
assert((size_t) sz <= sizeof_field(TPM2B_DIGEST, buffer));
assert(sz == tpm2_hash_alg_to_size(tpm2_hash_algorithms[i]));
assert(result->hash[i].size == (size_t) sz);
assert(b->hash.size == (size_t) sz);
if (EVP_DigestInit_ex(md_ctx, md, NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to initialize message digest.");
if (EVP_DigestUpdate(md_ctx, result->hash[i].buffer, sz) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash bank value.");
if (EVP_DigestUpdate(md_ctx, b->hash.buffer, sz) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash data value.");
unsigned l = (unsigned) sz;
if (EVP_DigestFinal_ex(md_ctx, result->hash[i].buffer, &l) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to finalize message digest.");
assert(l == (unsigned) sz);
}
/* This is a valid result once we hit the start location */
if (arg_location_start && strcmp(component->id, arg_location_start) >= 0) {
r = pcr_prediction_add_result(context, result, pcr, path, rr - variant->records);
if (r < 0)
return r;
}
}
return 0;
}
static int event_log_predict_pcrs(
EventLog *el,
Tpm2PCRPrediction *context,
Tpm2PCRPredictionResult *parent_result,
size_t component_index,
uint32_t pcr,
const char *path) {
EventLogComponent *component;
int count = 0, r;
assert(el);
assert(context);
assert(parent_result);
/* Check if we reached the end of the components, generate a result, and backtrack */
if (component_index >= el->n_components ||
(arg_location_end && strcmp(el->components[component_index]->id, arg_location_end) > 0)) {
r = pcr_prediction_add_result(context, parent_result, pcr, path, /* offset= */ 0);
if (r < 0)
return r;
return 1;
}
component = ASSERT_PTR(el->components[component_index]);
FOREACH_ARRAY(ii, component->variants, component->n_variants) {
_cleanup_free_ Tpm2PCRPredictionResult *result = NULL;
EventLogComponentVariant *variant = *ii;
_cleanup_free_ char *subpath = NULL;
/* Operate on a copy of the result */
if (path)
subpath = strjoin(path, ":", component->id);
else
subpath = strdup(component->id);
if (!subpath)
return log_oom();
if (!streq(component->id, variant->id))
if (!strextend(&subpath, "@", variant->id))
return log_oom();
result = newdup(Tpm2PCRPredictionResult, parent_result, 1);
if (!result)
return log_oom();
r = event_log_component_variant_calculate(
context,
result,
component,
variant,
pcr,
subpath);
if (r < 0)
return r;
r = event_log_predict_pcrs(
el,
context,
result,
component_index + 1, /* Next component */
pcr,
subpath);
if (r < 0)
return r;
count += r;
}
return count;
}
static ssize_t event_log_calculate_component_combinations(EventLog *el) {
ssize_t count = 1;
assert(el);
FOREACH_ARRAY(cc, el->components, el->n_components) {
EventLogComponent *c = *cc;
/* Overflow check */
if (c->n_variants > (size_t) (SSIZE_MAX/count))
return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Too many component combinations.");
count *= c->n_variants;
}
return count;
}
static int event_log_show_predictions(Tpm2PCRPrediction *context, uint16_t alg) {
int r;
assert(context);
pager_open(arg_pager_flags);
if (!FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
_cleanup_(json_variant_unrefp) JsonVariant *j = NULL;
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
_cleanup_(json_variant_unrefp) JsonVariant *aj = NULL;
r = tpm2_pcr_prediction_to_json(
context,
tpm2_hash_algorithms[i],
&aj);
if (r < 0)
return r;
if (json_variant_elements(aj) == 0)
continue;
r = json_variant_set_field(
&j,
tpm2_hash_alg_to_string(tpm2_hash_algorithms[i]),
aj);
if (r < 0)
return log_error_errno(r, "Failed to add prediction bank to object: %m");
}
if (!j) {
r = json_variant_new_object(&j, NULL, 0);
if (r < 0)
return log_error_errno(r, "Failed to allocated empty object: %m");
}
json_variant_dump(j, arg_json_format_flags, /* f= */ NULL, /* prefix= */ NULL);
return 0;
}
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
Tpm2PCRPredictionResult *result;
if (!FLAGS_SET(context->pcrs, UINT32_C(1) << pcr))
continue;
if (ordered_set_isempty(context->results[pcr])) {
printf("No results for PCR %u (%s).\n", pcr, tpm2_pcr_index_to_string(pcr));
continue;
}
printf("%sResults for PCR %u (%s):%s\n", ansi_underline(), pcr, tpm2_pcr_index_to_string(pcr), ansi_normal());
ORDERED_SET_FOREACH(result, context->results[pcr]) {
_cleanup_free_ char *aa = NULL, *h = NULL;
const char *a;
TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(result, alg);
if (!hash)
continue;
a = ASSERT_PTR(tpm2_hash_alg_to_string(alg));
aa = strdup(a);
if (!aa)
return log_oom();
ascii_strlower(aa);
h = hexmem(hash->buffer, hash->size);
if (!h)
return log_oom();
printf(" %s%-6s:%s %s\n", ansi_grey(), aa, ansi_normal(), h);
}
}
return 0;
}
static int tpm2_pcr_prediction_run(
EventLog *el,
Tpm2PCRPrediction *context) {
int r;
assert(el);
assert(context);
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
_cleanup_free_ Tpm2PCRPredictionResult *result = NULL;
if (!FLAGS_SET(context->pcrs, UINT32_C(1) << pcr))
continue;
result = new0(Tpm2PCRPredictionResult, 1);
if (!result)
return log_oom();
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++)
event_log_initial_pcr_state(el, pcr, tpm2_hash_alg_to_size(tpm2_hash_algorithms[i]), result->hash + i);
r = event_log_predict_pcrs(
el,
context,
result,
/* component_index= */ 0,
pcr,
/* path= */ NULL);
if (r < 0)
return r;
}
return 0;
}
static int verb_predict(int argc, char *argv[], void *userdata) {
_cleanup_(tpm2_pcr_prediction_done) Tpm2PCRPrediction context = {
arg_pcr_mask != 0 ? arg_pcr_mask : DEFAULT_PCR_MASK,
};
_cleanup_(event_log_freep) EventLog *el = NULL;
ssize_t count;
int r;
r = event_log_load_and_process(&el);
if (r < 0)
return r;
count = event_log_calculate_component_combinations(el);
if (count < 0)
return count;
log_info("%zi combinations of components.", count);
r = event_log_reduce_to_safe_pcrs(el, &context.pcrs);
if (r < 0)
return r;
r = tpm2_pcr_prediction_run(el, &context);
if (r < 0)
return r;
return event_log_show_predictions(&context, el->primary_algorithm);
}
static int remove_policy_file(const char *path) {
assert(path);
if (unlink(path) < 0) {
if (errno == ENOENT)
return 0;
return log_error_errno(errno, "Failed to remove policy file '%s': %m", path);
}
log_info("Removed policy file '%s'.", path);
return 1;
}
static int determine_boot_policy_file(char **ret) {
_cleanup_free_ char *path = NULL, *fn = NULL, *joined = NULL;
sd_id128_t machine_id;
int r;
assert(ret);
r = find_xbootldr_and_warn(
/* root= */ NULL,
/* path= */ NULL,
/* unprivileged_mode= */ false,
&path,
/* ret_uuid= */ NULL,
/* ret_devid= */ NULL);
if (r < 0) {
if (r != -ENOKEY)
return log_error_errno(r, "Failed to find XBOOTLDR partition: %m");
r = find_esp_and_warn(
/* root= */ NULL,
/* path= */ NULL,
/* unprivileged_mode= */ false,
&path,
/* ret_part= */ NULL,
/* ret_pstart= */ NULL,
/* ret_psize= */ NULL,
/* ret_uuid= */ NULL,
/* ret_devid= */ NULL);
if (r < 0) {
if (r != -ENOKEY)
return log_error_errno(r, "Failed to find ESP partition: %m");
*ret = NULL;
return 0; /* not found! */
}
}
r = sd_id128_get_machine(&machine_id);
if (r < 0)
return log_error_errno(r, "Failed to read machine ID: %m");
r = boot_entry_token_ensure(
/* root= */ NULL,
"/etc/kernel",
machine_id,
/* machine_id_is_random = */ false,
&arg_entry_token_type,
&arg_entry_token);
if (r < 0)
return r;
fn = strjoin("pcrlock.", arg_entry_token, ".cred");
if (!fn)
return log_oom();
if (!filename_is_valid(fn))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential name '%s' would not be a valid file name, refusing.", fn);
joined = path_join(path, "loader/credentials", fn);
if (!joined)
return log_oom();
*ret = TAKE_PTR(joined);
return 1; /* found! */
}
static int write_boot_policy_file(const char *json_text) {
_cleanup_free_ char *boot_policy_file = NULL;
int r;
assert(json_text);
r = determine_boot_policy_file(&boot_policy_file);
if (r < 0)
return r;
if (r == 0) {
log_info("Did not find XBOOTLDR/ESP partition, not writing boot policy file.");
return 0;
}
_cleanup_free_ char *c = NULL;
r = path_extract_filename(boot_policy_file, &c);
if (r < 0)
return log_error_errno(r, "Failed to extract file name from %s: %m", boot_policy_file);
ascii_strlower(c); /* lowercase this file, no matter what, since stored on VFAT, and we don't want to
* run into case change incompatibilities */
_cleanup_(iovec_done) struct iovec encoded = {};
r = encrypt_credential_and_warn(
CRED_AES256_GCM_BY_NULL,
c,
now(CLOCK_REALTIME),
/* not_after= */ USEC_INFINITY,
/* tpm2_device= */ NULL,
/* tpm2_hash_pcr_mask= */ 0,
/* tpm2_pubkey_path= */ NULL,
/* tpm2_pubkey_path_mask= */ 0,
UID_INVALID,
&IOVEC_MAKE_STRING(json_text),
CREDENTIAL_ALLOW_NULL,
&encoded);
if (r < 0)
return log_error_errno(r, "Failed to encode policy as credential: %m");
_cleanup_free_ char *base64_buf = NULL;
ssize_t base64_size;
base64_size = base64mem_full(encoded.iov_base, encoded.iov_len, 79, &base64_buf);
if (base64_size < 0)
return base64_size;
r = write_string_file(
boot_policy_file,
base64_buf,
WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_SYNC|WRITE_STRING_FILE_MKDIR_0755);
if (r < 0)
return log_error_errno(r, "Failed to write boot policy file to '%s': %m", boot_policy_file);
log_info("Written new boot policy to '%s'.", boot_policy_file);
return 1;
}
static int make_policy(bool force, RecoveryPinMode recovery_pin_mode) {
int r;
/* Here's how this all works: after predicting all possible PCR values for next boot (with
* alternatives) we'll calculate a policy from it as a combination of PolicyPCR + PolicyOR
* expressions. This is then stored in an NV index. When a component of the boot process is changed a
* new prediction is made and the NV index updated (which automatically invalidates any older
* policies).
*
* Whenever we want to lock an encrypted object (for example FDE) against this policy, we'll use a
* PolicyAuthorizeNV expression that pins the NV index in the policy, and permits access to any
* policies matching the current NV index contents.
*
* We grant world-readable read access to the NV index. Write access is controlled by a PIN (which we
* either generate locally or which the user can provide us with) which can also be used for
* recovery. This PIN is sealed to the TPM and is locked via PolicyAuthorizeNV to the NV index it
* protects (i.e. we dogfood 🌭 🐶 hard here). This means in order to update such a policy we need
* the policy to pass.
*
* Information about the used NV Index, the SRK of the TPM, the sealed PIN and the current PCR
* prediction data are stored in a JSON file in /var/lib/. In order to be able to unlock root disks
* this data must be also copied to the ESP so that it is available to the initrd. The data is not
* sensitive, as SRK and NV index are pinned by it, and the prediction data must match the NV index
* to be useful. */
usec_t start_usec = now(CLOCK_MONOTONIC);
_cleanup_(event_log_freep) EventLog *el = NULL;
r = event_log_load_and_process(&el);
if (r < 0)
return r;
_cleanup_(tpm2_pcr_prediction_done) Tpm2PCRPrediction new_prediction = {
arg_pcr_mask != 0 ? arg_pcr_mask : DEFAULT_PCR_MASK,
};
r = event_log_reduce_to_safe_pcrs(el, &new_prediction.pcrs);
if (r < 0)
return r;
usec_t predict_start_usec = now(CLOCK_MONOTONIC);
r = tpm2_pcr_prediction_run(el, &new_prediction);
if (r < 0)
return r;
log_info("Predicted future PCRs in %s.", FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), predict_start_usec), 1));
_cleanup_(json_variant_unrefp) JsonVariant *new_prediction_json = NULL;
r = tpm2_pcr_prediction_to_json(&new_prediction, el->primary_algorithm, &new_prediction_json);
if (r < 0)
return r;
if (DEBUG_LOGGING)
(void) json_variant_dump(new_prediction_json, JSON_FORMAT_PRETTY_AUTO|JSON_FORMAT_COLOR_AUTO, stderr, NULL);
_cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy old_policy = {};
r = tpm2_pcrlock_policy_load(arg_pcrlock_path, &old_policy);
if (r < 0)
return r;
bool have_old_policy = r > 0;
/* When we update the policy the old serializations for NV, SRK, PIN remain the same */
_cleanup_(iovec_done) struct iovec
nv_blob = TAKE_STRUCT(old_policy.nv_handle),
nv_public_blob = TAKE_STRUCT(old_policy.nv_public),
srk_blob = TAKE_STRUCT(old_policy.srk_handle),
pin_public = TAKE_STRUCT(old_policy.pin_public),
pin_private = TAKE_STRUCT(old_policy.pin_private);
if (have_old_policy) {
if (arg_nv_index != 0 && old_policy.nv_index != arg_nv_index)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Stored policy references different NV index (0x%x) than specified (0x%x), refusing.", old_policy.nv_index, arg_nv_index);
if (!force &&
old_policy.algorithm == el->primary_algorithm &&
tpm2_pcr_prediction_equal(&old_policy.prediction, &new_prediction, el->primary_algorithm)) {
log_info("Prediction is identical to current policy, skipping update.");
return 0; /* NOP */
}
}
_cleanup_(tpm2_context_unrefp) Tpm2Context *tc = NULL;
r = tpm2_context_new_or_warn(/* device= */ NULL, &tc);
if (r < 0)
return r;
if (!tpm2_supports_command(tc, TPM2_CC_PolicyAuthorizeNV))
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 does not support PolicyAuthorizeNV command, refusing.");
_cleanup_(tpm2_handle_freep) Tpm2Handle *srk_handle = NULL;
if (iovec_is_set(&srk_blob)) {
r = tpm2_deserialize(
tc,
srk_blob.iov_base,
srk_blob.iov_len,
&srk_handle);
if (r < 0)
return log_error_errno(r, "Failed to deserialize SRK TR: %m");
} else {
r = tpm2_get_or_create_srk(
tc,
/* session= */ NULL,
/* ret_public= */ NULL,
/* ret_name= */ NULL,
/* ret_qname= */ NULL,
&srk_handle);
if (r < 0)
return log_error_errno(r, "Failed to install SRK: %m");
}
_cleanup_(tpm2_handle_freep) Tpm2Handle *encryption_session = NULL;
r = tpm2_make_encryption_session(
tc,
srk_handle,
/* bind_key= */ &TPM2_HANDLE_NONE,
&encryption_session);
if (r < 0)
return log_error_errno(r, "Failed to allocate encryption session: %m");
/* Acquire a recovery PIN, either from the user, or create a randomized one */
_cleanup_(erase_and_freep) char *pin = NULL;
if (recovery_pin_mode == RECOVERY_PIN_QUERY) {
r = getenv_steal_erase("PIN", &pin);
if (r < 0)
return log_error_errno(r, "Failed to acquire PIN from environment: %m");
if (r == 0) {
_cleanup_(strv_free_erasep) char **l = NULL;
AskPasswordRequest req = {
.message = "Recovery PIN",
.id = "pcrlock-recovery-pin",
.credential = "pcrlock.recovery-pin",
};
r = ask_password_auto(
&req,
/* until= */ 0,
/* flags= */ 0,
&l);
if (r < 0)
return log_error_errno(r, "Failed to query for recovery PIN: %m");
if (strv_length(l) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Expected a single PIN only.");
pin = TAKE_PTR(l[0]);
l = mfree(l);
}
} else if (!have_old_policy) {
r = make_recovery_key(&pin);
if (r < 0)
return log_error_errno(r, "Failed to generate a randomized recovery PIN: %m");
if (recovery_pin_mode == RECOVERY_PIN_SHOW)
printf("%s Selected recovery PIN is: %s%s%s\n",
special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY),
ansi_highlight_cyan(),
pin,
ansi_normal());
}
_cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
TPM2_HANDLE nv_index = 0;
if (iovec_is_set(&nv_blob)) {
r = tpm2_deserialize(tc, nv_blob.iov_base, nv_blob.iov_len, &nv_handle);
if (r < 0)
return log_error_errno(r, "Failed to deserialize NV index TR: %m");
nv_index = old_policy.nv_index;
}
TPM2B_AUTH auth = {};
CLEANUP_ERASE(auth);
if (pin) {
r = tpm2_auth_value_from_pin(TPM2_ALG_SHA256, pin, &auth);
if (r < 0)
return log_error_errno(r, "Failed to hash PIN: %m");
} else {
assert(iovec_is_set(&pin_public));
assert(iovec_is_set(&pin_private));
log_debug("Retrieving PIN from sealed data.");
usec_t pin_start_usec = now(CLOCK_MONOTONIC);
_cleanup_(iovec_done_erase) struct iovec secret = {};
for (unsigned attempt = 0;; attempt++) {
_cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
r = tpm2_make_policy_session(
tc,
srk_handle,
encryption_session,
&policy_session);
if (r < 0)
return log_error_errno(r, "Failed to allocate policy session: %m");
r = tpm2_policy_super_pcr(
tc,
policy_session,
&old_policy.prediction,
old_policy.algorithm);
if (r < 0)
return log_error_errno(r, "Failed to submit super PCR policy: %m");
r = tpm2_policy_authorize_nv(
tc,
policy_session,
nv_handle,
NULL);
if (r < 0)
return log_error_errno(r, "Failed to submit AuthorizeNV policy: %m");
r = tpm2_unseal_data(
tc,
&pin_public,
&pin_private,
srk_handle,
policy_session,
encryption_session,
&secret);
if (r < 0 && (r != -ESTALE || attempt >= 16))
return log_error_errno(r, "Failed to unseal PIN: %m");
if (r == 0)
break;
log_debug("Trying again (attempt %u), as PCR values changed during unlock attempt.", attempt+1);
}
if (secret.iov_len > sizeof_field(TPM2B_AUTH, buffer))
return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Decrypted PIN too large.");
auth = (TPM2B_AUTH) {
.size = secret.iov_len,
};
memcpy_safe(auth.buffer, secret.iov_base, secret.iov_len);
log_info("Retrieved PIN from TPM2 in %s.", FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), pin_start_usec), 1));
}
/* Now convert the PIN into an HMAC-SHA256 key that we can use in PolicySigned to protect access to the nvindex with */
_cleanup_(tpm2_handle_freep) Tpm2Handle *pin_handle = NULL;
r = tpm2_hmac_key_from_pin(tc, encryption_session, &auth, &pin_handle);
if (r < 0)
return r;
TPM2B_NV_PUBLIC nv_public = {};
usec_t nv_index_start_usec = now(CLOCK_MONOTONIC);
if (!iovec_is_set(&nv_blob)) {
_cleanup_(Esys_Freep) TPM2B_NAME *pin_name = NULL;
r = tpm2_get_name(
tc,
pin_handle,
&pin_name);
if (r < 0)
return log_error_errno(r, "Failed to get name of PIN from TPM2: %m");
TPM2B_DIGEST recovery_policy_digest = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
r = tpm2_calculate_policy_signed(&recovery_policy_digest, pin_name);
if (r < 0)
return log_error_errno(r, "Failed to calculate PolicySigned policy: %m");
log_debug("Allocating NV index to write PCR policy to...");
r = tpm2_define_policy_nv_index(
tc,
encryption_session,
arg_nv_index,
&recovery_policy_digest,
&nv_index,
&nv_handle,
&nv_public);
if (r == -EEXIST)
return log_error_errno(r, "NV index 0x%" PRIx32 " already allocated.", arg_nv_index);
if (r < 0)
return log_error_errno(r, "Failed to allocate NV index: %m");
}
_cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
r = tpm2_make_policy_session(
tc,
srk_handle,
encryption_session,
&policy_session);
if (r < 0)
return log_error_errno(r, "Failed to allocate policy session: %m");
r = tpm2_policy_signed_hmac_sha256(
tc,
policy_session,
pin_handle,
&IOVEC_MAKE(auth.buffer, auth.size),
/* ret_policy_digest= */ NULL);
if (r < 0)
return log_error_errno(r, "Failed to submit authentication value policy: %m");
log_debug("Calculating new PCR policy to write...");
TPM2B_DIGEST new_super_pcr_policy_digest = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
usec_t pcr_policy_start_usec = now(CLOCK_MONOTONIC);
r = tpm2_calculate_policy_super_pcr(
&new_prediction,
el->primary_algorithm,
&new_super_pcr_policy_digest);
if (r < 0)
return log_error_errno(r, "Failed to calculate super PCR policy: %m");
log_info("Calculated new PCR policy in %s.", FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), pcr_policy_start_usec), 1));
log_debug("Writing new PCR policy to NV index...");
r = tpm2_write_policy_nv_index(
tc,
policy_session,
nv_index,
nv_handle,
&new_super_pcr_policy_digest);
if (r < 0)
return log_error_errno(r, "Failed to write to NV index: %m");
log_info("Updated NV index in %s.", FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), nv_index_start_usec), 1));
assert(iovec_is_set(&pin_public) == iovec_is_set(&pin_private));
if (!iovec_is_set(&pin_public)) {
TPM2B_DIGEST authnv_policy_digest = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
r = tpm2_calculate_policy_authorize_nv(&nv_public, &authnv_policy_digest);
if (r < 0)
return log_error_errno(r, "Failed to calculate AuthorizeNV policy: %m");
struct iovec data = {
.iov_base = auth.buffer,
.iov_len = auth.size,
};
usec_t pin_seal_start_usec = now(CLOCK_MONOTONIC);
log_debug("Sealing PIN to NV index policy...");
r = tpm2_seal_data(
tc,
&data,
srk_handle,
encryption_session,
&authnv_policy_digest,
&pin_public,
&pin_private);
if (r < 0)
return log_error_errno(r, "Failed to seal PIN to NV auth policy: %m");
log_info("Sealed PIN in %s.", FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), pin_seal_start_usec), 1));
}
if (!iovec_is_set(&nv_blob)) {
r = tpm2_serialize(tc, nv_handle, &nv_blob.iov_base, &nv_blob.iov_len);
if (r < 0)
return log_error_errno(r, "Failed to serialize NV index TR: %m");
}
if (!iovec_is_set(&srk_blob)) {
r = tpm2_serialize(tc, srk_handle, &srk_blob.iov_base, &srk_blob.iov_len);
if (r < 0)
return log_error_errno(r, "Failed to serialize SRK index TR: %m");
}
if (!iovec_is_set(&nv_public_blob)) {
r = tpm2_marshal_nv_public(&nv_public, &nv_public_blob.iov_base, &nv_public_blob.iov_len);
if (r < 0)
return log_error_errno(r, "Failed to marshal NV public area: %m");
}
_cleanup_(json_variant_unrefp) JsonVariant *new_configuration_json = NULL;
r = json_build(&new_configuration_json,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR_STRING("pcrBank", tpm2_hash_alg_to_string(el->primary_algorithm)),
JSON_BUILD_PAIR_VARIANT("pcrValues", new_prediction_json),
JSON_BUILD_PAIR_INTEGER("nvIndex", nv_index),
JSON_BUILD_PAIR_IOVEC_BASE64("nvHandle", &nv_blob),
JSON_BUILD_PAIR_IOVEC_BASE64("nvPublic", &nv_public_blob),
JSON_BUILD_PAIR_IOVEC_BASE64("srkHandle", &srk_blob),
JSON_BUILD_PAIR_IOVEC_BASE64("pinPublic", &pin_public),
JSON_BUILD_PAIR_IOVEC_BASE64("pinPrivate", &pin_private)));
if (r < 0)
return log_error_errno(r, "Failed to generate JSON: %m");
_cleanup_free_ char *text = NULL;
r = json_variant_format(new_configuration_json, 0, &text);
if (r < 0)
return log_error_errno(r, "Failed to format new configuration to JSON: %m");
const char *path = arg_pcrlock_path ?: (in_initrd() ? "/run/systemd/pcrlock.json" : "/var/lib/systemd/pcrlock.json");
r = write_string_file(path, text, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_SYNC|WRITE_STRING_FILE_MKDIR_0755);
if (r < 0)
return log_error_errno(r, "Failed to write new configuration to '%s': %m", path);
if (!arg_pcrlock_path && !in_initrd()) {
r = remove_policy_file("/run/systemd/pcrlock.json");
if (r < 0)
return r;
}
log_info("Written new policy to '%s' and digest to TPM2 NV index 0x%x.", path, nv_index);
(void) write_boot_policy_file(text);
log_info("Overall time spent: %s", FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start_usec), 1));
return 1; /* installed new policy */
}
static int verb_make_policy(int argc, char *argv[], void *userdata) {
return make_policy(arg_force, arg_recovery_pin);
}
static int undefine_policy_nv_index(
uint32_t nv_index,
const struct iovec *nv_blob,
const struct iovec *srk_blob) {
int r;
assert(nv_blob);
assert(srk_blob);
_cleanup_(tpm2_context_unrefp) Tpm2Context *tc = NULL;
r = tpm2_context_new_or_warn(/* device= */ NULL, &tc);
if (r < 0)
return r;
_cleanup_(tpm2_handle_freep) Tpm2Handle *srk_handle = NULL;
r = tpm2_deserialize(
tc,
srk_blob->iov_base,
srk_blob->iov_len,
&srk_handle);
if (r < 0)
return log_error_errno(r, "Failed to deserialize SRK TR: %m");
_cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
r = tpm2_deserialize(
tc,
nv_blob->iov_base,
nv_blob->iov_len,
&nv_handle);
if (r < 0)
return log_error_errno(r, "Failed to deserialize NV TR: %m");
_cleanup_(tpm2_handle_freep) Tpm2Handle *encryption_session = NULL;
r = tpm2_make_encryption_session(
tc,
srk_handle,
/* bind_key= */ &TPM2_HANDLE_NONE,
&encryption_session);
if (r < 0)
return r;
r = tpm2_undefine_policy_nv_index(
tc,
encryption_session,
nv_index,
nv_handle);
if (r < 0)
return r;
log_info("Removed NV index 0x%x", nv_index);
return 0;
}
static int remove_policy(void) {
int ret = 0, r;
_cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy policy = {};
r = tpm2_pcrlock_policy_load(arg_policy_path, &policy);
if (r == 0) {
log_info("No policy found.");
return 0;
}
if (r < 0)
log_notice("Failed to load old policy file, assuming it is corrupted, removing.");
else {
r = undefine_policy_nv_index(policy.nv_index, &policy.nv_handle, &policy.srk_handle);
if (r < 0)
log_notice("Failed to remove NV index, assuming data out of date, removing policy file.");
RET_GATHER(ret, r);
}
if (arg_policy_path)
RET_GATHER(ret, remove_policy_file(arg_policy_path));
else {
RET_GATHER(ret, remove_policy_file("/var/lib/systemd/pcrlock.json"));
RET_GATHER(ret, remove_policy_file("/run/systemd/pcrlock.json"));
}
_cleanup_free_ char *boot_policy_file = NULL;
r = determine_boot_policy_file(&boot_policy_file);
if (r == 0)
log_info("Did not find XBOOTLDR/ESP partition, not removing boot policy file.");
else if (r > 0) {
RET_GATHER(ret, remove_policy_file(boot_policy_file));
} else
RET_GATHER(ret, r);
return ret;
}
static int verb_remove_policy(int argc, char *argv[], void *userdata) {
return remove_policy();
}
static int help(int argc, char *argv[], void *userdata) {
_cleanup_free_ char *link = NULL;
int r;
r = terminal_urlify_man("systemd-pcrlock", "8", &link);
if (r < 0)
return log_oom();
printf("%1$s [OPTIONS...] COMMAND ...\n"
"\n%5$sManage a TPM2 PCR lock.%6$s\n"
"\n%3$sCommands:%4$s\n"
" log Show measurement log\n"
" cel Show measurement log in TCG CEL-JSON format\n"
" list-components List defined .pcrlock components\n"
" predict Predict PCR values\n"
" make-policy Predict PCR values and generate TPM2 policy from it\n"
" remove-policy Remove TPM2 policy\n"
"\n%3$sProtections:%4$s\n"
" lock-firmware-code Generate a .pcrlock file from current firmware code\n"
" unlock-firmware-code Remove .pcrlock file for firmware code\n"
" lock-firmware-config Generate a .pcrlock file from current firmware configuration\n"
" unlock-firmware-config Remove .pcrlock file for firmware configuration\n"
" lock-secureboot-policy Generate a .pcrlock file from current SecureBoot policy\n"
" unlock-secureboot-policy Remove .pcrlock file for SecureBoot policy\n"
" lock-secureboot-authority Generate a .pcrlock file from current SecureBoot authority\n"
" unlock-secureboot-authority Remove .pcrlock file for SecureBoot authority\n"
" lock-gpt [DISK] Generate a .pcrlock file from GPT header\n"
" unlock-gpt Remove .pcrlock file for GPT header\n"
" lock-pe [BINARY] Generate a .pcrlock file from PE binary\n"
" unlock-pe Remove .pcrlock file for PE binary\n"
" lock-uki [UKI] Generate a .pcrlock file from UKI PE binary\n"
" unlock-uki Remove .pcrlock file for UKI PE binary\n"
" lock-machine-id Generate a .pcrlock file from current machine ID\n"
" unlock-machine-id Remove .pcrlock file for machine ID\n"
" lock-file-system [PATH] Generate a .pcrlock file from current root fs + /var/\n"
" unlock-file-system [PATH] Remove .pcrlock file for root fs + /var/\n"
" lock-kernel-cmdline [FILE] Generate a .pcrlock file from kernel command line\n"
" unlock-kernel-cmdline Remove .pcrlock file for kernel command line\n"
" lock-kernel-initrd FILE Generate a .pcrlock file from an initrd file\n"
" unlock-kernel-initrd Remove .pcrlock file for an initrd file\n"
" lock-raw [FILE] Generate a .pcrlock file from raw data\n"
" unlock-raw Remove .pcrlock file for raw data\n"
"\n%3$sOptions:%4$s\n"
" -h --help Show this help\n"
" --version Print version\n"
" --no-pager Do not pipe output into a pager\n"
" --json=pretty|short|off Generate JSON output\n"
" --raw-description Show raw firmware record data as description in table\n"
" --pcr=NR Generate .pcrlock for specified PCR\n"
" --nv-index=NUMBER Use the specified NV index, instead of a random one\n"
" --components=PATH Directory to read .pcrlock files from\n"
" --location=STRING[:STRING]\n"
" Do not process components beyond this component name\n"
" --recovery-pin=yes Ask for a recovery PIN\n"
" --pcrlock=PATH .pcrlock file to write expected PCR measurement to\n"
" --policy=PATH JSON file to write policy output to\n"
" --force Write policy even if it matches existing policy\n"
" --entry-token=machine-id|os-id|os-image-id|auto|literal:…\n"
" Boot entry token to use for this installation\n"
"\nSee the %2$s for details.\n",
program_invocation_short_name,
link,
ansi_underline(),
ansi_normal(),
ansi_highlight(),
ansi_normal());
return 0;
}
static int parse_argv(int argc, char *argv[]) {
enum {
ARG_VERSION = 0x100,
ARG_NO_PAGER,
ARG_JSON,
ARG_RAW_DESCRIPTION,
ARG_PCR,
ARG_NV_INDEX,
ARG_COMPONENTS,
ARG_LOCATION,
ARG_RECOVERY_PIN,
ARG_PCRLOCK,
ARG_POLICY,
ARG_FORCE,
ARG_ENTRY_TOKEN,
};
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, ARG_VERSION },
{ "no-pager", no_argument, NULL, ARG_NO_PAGER },
{ "json", required_argument, NULL, ARG_JSON },
{ "raw-description", no_argument, NULL, ARG_RAW_DESCRIPTION },
{ "pcr", required_argument, NULL, ARG_PCR },
{ "nv-index", required_argument, NULL, ARG_NV_INDEX },
{ "components", required_argument, NULL, ARG_COMPONENTS },
{ "location", required_argument, NULL, ARG_LOCATION },
{ "recovery-pin", required_argument, NULL, ARG_RECOVERY_PIN },
{ "pcrlock", required_argument, NULL, ARG_PCRLOCK },
{ "policy", required_argument, NULL, ARG_POLICY },
{ "force", no_argument, NULL, ARG_FORCE },
{ "entry-token", required_argument, NULL, ARG_ENTRY_TOKEN },
{}
};
bool auto_location = true;
int c, r;
assert(argc >= 0);
assert(argv);
while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
switch (c) {
case 'h':
help(0, NULL, NULL);
return 0;
case ARG_VERSION:
return version();
case ARG_NO_PAGER:
arg_pager_flags |= PAGER_DISABLE;
break;
case ARG_JSON:
r = parse_json_argument(optarg, &arg_json_format_flags);
if (r <= 0)
return r;
break;
case ARG_RAW_DESCRIPTION:
arg_raw_description = true;
break;
case ARG_PCR: {
r = tpm2_parse_pcr_argument_to_mask(optarg, &arg_pcr_mask);
if (r < 0)
return log_error_errno(r, "Failed to parse PCR specification: %s", optarg);
break;
}
case ARG_NV_INDEX:
if (isempty(optarg))
arg_nv_index = 0;
else {
uint32_t u;
r = safe_atou32_full(optarg, 16, &u);
if (r < 0)
return log_error_errno(r, "Failed to parse --nv-index= argument: %s", optarg);
if (u < TPM2_NV_INDEX_FIRST || u > TPM2_NV_INDEX_LAST)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Argument for --nv-index= outside of valid range 0x%" PRIx32 "…0x%" PRIx32 ": 0x%" PRIx32,
TPM2_NV_INDEX_FIRST, TPM2_NV_INDEX_LAST, u);
arg_nv_index = u;
}
break;
case ARG_COMPONENTS: {
_cleanup_free_ char *p = NULL;
r = parse_path_argument(optarg, /* suppress_root= */ false, &p);
if (r < 0)
return r;
r = strv_consume(&arg_components, TAKE_PTR(p));
if (r < 0)
return log_oom();
break;
}
case ARG_LOCATION: {
_cleanup_free_ char *start = NULL, *end = NULL;
const char *e;
auto_location = false;
if (isempty(optarg)) {
arg_location_start = mfree(arg_location_start);
arg_location_end = mfree(arg_location_end);
break;
}
e = strchr(optarg, ':');
if (e) {
start = strndup(optarg, e - optarg);
if (!start)
return log_oom();
end = strdup(e + 1);
if (!end)
return log_oom();
} else {
start = strdup(optarg);
if (!start)
return log_oom();
end = strdup(optarg);
if (!end)
return log_oom();
}
if (!filename_is_valid(start))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Location string invalid, refusing: %s", start);
if (!filename_is_valid(end))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Location string invalid, refusing: %s", end);
free_and_replace(arg_location_start, start);
free_and_replace(arg_location_end, end);
break;
}
case ARG_RECOVERY_PIN:
arg_recovery_pin = recovery_pin_mode_from_string(optarg);
if (arg_recovery_pin < 0)
return log_error_errno(arg_recovery_pin, "Failed to parse --recovery-pin= mode: %s", optarg);
break;
case ARG_PCRLOCK:
if (empty_or_dash(optarg))
arg_pcrlock_path = mfree(arg_pcrlock_path);
else {
r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_pcrlock_path);
if (r < 0)
return r;
}
arg_pcrlock_auto = false;
break;
case ARG_POLICY:
if (empty_or_dash(optarg))
arg_policy_path = mfree(arg_policy_path);
else {
r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_policy_path);
if (r < 0)
return r;
}
break;
case ARG_FORCE:
arg_force = true;
break;
case ARG_ENTRY_TOKEN:
r = parse_boot_entry_token_type(optarg, &arg_entry_token_type, &arg_entry_token);
if (r < 0)
return r;
break;
case '?':
return -EINVAL;
default:
assert_not_reached();
}
if (auto_location) {
assert(!arg_location_start);
assert(!arg_location_end);
arg_location_start = strdup("760-");
if (!arg_location_start)
return log_oom();
arg_location_end = strdup("940-");
if (!arg_location_end)
return log_oom();
}
r = varlink_invocation(VARLINK_ALLOW_ACCEPT);
if (r < 0)
return log_error_errno(r, "Failed to check if invoked in Varlink mode: %m");
if (r > 0) {
arg_varlink = true;
arg_pager_flags |= PAGER_DISABLE;
}
return 1;
}
static int pcrlock_main(int argc, char *argv[]) {
static const Verb verbs[] = {
{ "help", VERB_ANY, VERB_ANY, 0, help },
{ "log", VERB_ANY, 1, VERB_DEFAULT, verb_show_log },
{ "cel", VERB_ANY, 1, 0, verb_show_cel },
{ "list-components", VERB_ANY, 1, 0, verb_list_components },
{ "predict", VERB_ANY, 1, 0, verb_predict },
{ "lock-firmware-code", VERB_ANY, 2, 0, verb_lock_firmware },
{ "unlock-firmware-code", VERB_ANY, 1, 0, verb_unlock_firmware },
{ "lock-firmware-config", VERB_ANY, 2, 0, verb_lock_firmware },
{ "unlock-firmware-config", VERB_ANY, 1, 0, verb_unlock_firmware },
{ "lock-secureboot-policy", VERB_ANY, 1, 0, verb_lock_secureboot_policy },
{ "unlock-secureboot-policy", VERB_ANY, 1, 0, verb_unlock_secureboot_policy },
{ "lock-secureboot-authority", VERB_ANY, 1, 0, verb_lock_secureboot_authority },
{ "unlock-secureboot-authority", VERB_ANY, 1, 0, verb_unlock_secureboot_authority },
{ "lock-gpt", VERB_ANY, 2, 0, verb_lock_gpt },
{ "unlock-gpt", VERB_ANY, 1, 0, verb_unlock_gpt },
{ "lock-pe", VERB_ANY, 2, 0, verb_lock_pe },
{ "unlock-pe", VERB_ANY, 1, 0, verb_unlock_simple },
{ "lock-uki", VERB_ANY, 2, 0, verb_lock_uki },
{ "unlock-uki", VERB_ANY, 1, 0, verb_unlock_simple },
{ "lock-machine-id", VERB_ANY, 1, 0, verb_lock_machine_id },
{ "unlock-machine-id", VERB_ANY, 1, 0, verb_unlock_machine_id },
{ "lock-file-system", VERB_ANY, 2, 0, verb_lock_file_system },
{ "unlock-file-system", VERB_ANY, 2, 0, verb_unlock_file_system },
{ "lock-kernel-cmdline", VERB_ANY, 2, 0, verb_lock_kernel_cmdline },
{ "unlock-kernel-cmdline", VERB_ANY, 1, 0, verb_unlock_kernel_cmdline },
{ "lock-kernel-initrd", VERB_ANY, 2, 0, verb_lock_kernel_initrd },
{ "unlock-kernel-initrd", VERB_ANY, 1, 0, verb_unlock_kernel_initrd },
{ "lock-raw", VERB_ANY, 2, 0, verb_lock_raw },
{ "unlock-raw", VERB_ANY, 1, 0, verb_unlock_simple },
{ "make-policy", VERB_ANY, 1, 0, verb_make_policy },
{ "remove-policy", VERB_ANY, 1, 0, verb_remove_policy },
{}
};
return dispatch_verb(argc, argv, verbs, NULL);
}
static int vl_method_read_event_log(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
_cleanup_(event_log_freep) EventLog *el = NULL;
uint64_t recnum = 0;
int r;
assert(link);
if (json_variant_elements(parameters) > 0)
return varlink_error_invalid_parameter(link, parameters);
el = event_log_new();
if (!el)
return log_oom();
r = event_log_load(el);
if (r < 0)
return r;
_cleanup_(json_variant_unrefp) JsonVariant *rec_cel = NULL;
FOREACH_ARRAY(rr, el->records, el->n_records) {
if (rec_cel) {
r = varlink_notifyb(link,
JSON_BUILD_OBJECT(JSON_BUILD_PAIR_VARIANT("record", rec_cel)));
if (r < 0)
return r;
rec_cel = json_variant_unref(rec_cel);
}
r = event_log_record_to_cel(*rr, &recnum, &rec_cel);
if (r < 0)
return r;
}
return varlink_replyb(link,
JSON_BUILD_OBJECT(JSON_BUILD_PAIR_CONDITION(rec_cel, "record", JSON_BUILD_VARIANT(rec_cel))));
}
typedef struct MethodMakePolicyParameters {
bool force;
} MethodMakePolicyParameters;
static int vl_method_make_policy(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
static const JsonDispatch dispatch_table[] = {
{ "force", JSON_VARIANT_BOOLEAN, json_dispatch_boolean, offsetof(MethodMakePolicyParameters, force), 0 },
{}
};
MethodMakePolicyParameters p = {};
int r;
assert(link);
r = varlink_dispatch(link, parameters, dispatch_table, &p);
if (r != 0)
return r;
r = make_policy(p.force, /* recovery_key= */ RECOVERY_PIN_HIDE);
if (r < 0)
return r;
if (r == 0)
return varlink_error(link, "io.systemd.PCRLock.NoChange", NULL);
return varlink_reply(link, NULL);
}
static int vl_method_remove_policy(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
int r;
assert(link);
if (json_variant_elements(parameters) > 0)
return varlink_error_invalid_parameter(link, parameters);
r = remove_policy();
if (r < 0)
return r;
return varlink_reply(link, NULL);
}
static int run(int argc, char *argv[]) {
int r;
log_setup();
r = parse_argv(argc, argv);
if (r <= 0)
return r;
if (arg_varlink) {
_cleanup_(varlink_server_unrefp) VarlinkServer *varlink_server = NULL;
/* Invocation as Varlink service */
r = varlink_server_new(&varlink_server, VARLINK_SERVER_ROOT_ONLY);
if (r < 0)
return log_error_errno(r, "Failed to allocate Varlink server: %m");
r = varlink_server_add_interface(varlink_server, &vl_interface_io_systemd_PCRLock);
if (r < 0)
return log_error_errno(r, "Failed to add Varlink interface: %m");
r = varlink_server_bind_method_many(
varlink_server,
"io.systemd.PCRLock.ReadEventLog", vl_method_read_event_log,
"io.systemd.PCRLock.MakePolicy", vl_method_make_policy,
"io.systemd.PCRLock.RemovePolicy", vl_method_remove_policy);
if (r < 0)
return log_error_errno(r, "Failed to bind Varlink methods: %m");
r = varlink_server_loop_auto(varlink_server);
if (r < 0)
return log_error_errno(r, "Failed to run Varlink event loop: %m");
return EXIT_SUCCESS;
}
return pcrlock_main(argc, argv);
}
DEFINE_MAIN_FUNCTION(run);
|