aboutsummaryrefslogtreecommitdiffstats
path: root/spectre-meltdown-checker.sh
blob: 906646ada21e37d78b89534e8e53d892f3cf3863 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
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
#! /bin/sh
# Spectre & Meltdown checker
#
# Check for the latest version at:
# https://github.com/speed47/spectre-meltdown-checker
# git clone https://github.com/speed47/spectre-meltdown-checker.git
# or wget https://raw.githubusercontent.com/speed47/spectre-meltdown-checker/master/spectre-meltdown-checker.sh
#
# Stephane Lesimple
#
VERSION=0.32

show_usage()
{
	cat <<EOF
	Usage:
		Live mode:    `basename $0` [options] [--live]
		Offline mode: `basename $0` [options] [--kernel <vmlinux_file>] [--config <kernel_config>] [--map <kernel_map_file>]

	Modes:
		Two modes are available.

		First mode is the "live" mode (default), it does its best to find information about the currently running kernel.
		To run under this mode, just start the script without any option (you can also use --live explicitly)

		Second mode is the "offline" mode, where you can inspect a non-running kernel.
		You'll need to specify the location of the vmlinux file, config and System.map files:

		--kernel vmlinux_file		Specify a (possibly compressed) vmlinux file
		--config kernel_config		Specify a kernel config file
		--map	 kernel_map_file	Specify a kernel System.map file

	Options:
		--no-color			Don't use color codes
		--verbose, -v			Increase verbosity level
		--no-sysfs			Don't use the /sys interface even if present
		--sysfs-only			Only use the /sys interface, don't run our own checks
		--coreos			Special mode for CoreOS (use an ephemeral toolbox to inspect kernel)
		--batch text			Produce machine readable output, this is the default if --batch is specified alone
		--batch json			Produce JSON output formatted for Puppet, Ansible, Chef...
		--batch nrpe			Produce machine readable output formatted for NRPE
		--variant [1,2,3]		Specify which variant you'd like to check, by default all variants are checked
						Can be specified multiple times (e.g. --variant 2 --variant 3)

	Return codes:
		0 (not vulnerable), 2 (vulnerable), 3 (unknown), 255 (error)

	IMPORTANT:
	A false sense of security is worse than no security at all.
	Please use the --disclaimer option to understand exactly what this script does.

EOF
}

show_disclaimer()
{
	cat <<EOF
Disclaimer:

This tool does its best to determine whether your system is immune (or has proper mitigations in place) for the
collectively named "speculative execution" vulnerabilities. It doesn't attempt to run any kind of exploit, and can't guarantee
that your system is secure, but rather helps you verifying whether your system has the known correct mitigations in place.
However, some mitigations could also exist in your kernel that this script doesn't know (yet) how to detect, or it might
falsely detect mitigations that in the end don't work as expected (for example, on backported or modified kernels).

Your system exposure also depends on your CPU. As of now, AMD and ARM processors are marked as immune to some or all of these
vulnerabilities (except some specific ARM models). All Intel processors manufactured since circa 1995 are thought to be vulnerable.
Whatever processor one uses, one might seek more information from the manufacturer of that processor and/or of the device
in which it runs.

The nature of the discovered vulnerabilities being quite new, the landscape of vulnerable processors can be expected
to change over time, which is why this script makes the assumption that all CPUs are vulnerable, except if the manufacturer
explicitly stated otherwise in a verifiable public announcement.

This tool has been released in the hope that it'll be useful, but don't use it to jump to conclusions about your security.

EOF
}

# parse options
opt_kernel=''
opt_config=''
opt_map=''
opt_live_explicit=0
opt_live=1
opt_no_color=0
opt_batch=0
opt_batch_format="text"
opt_verbose=1
opt_variant1=0
opt_variant2=0
opt_variant3=0
opt_allvariants=1
opt_no_sysfs=0
opt_sysfs_only=0
opt_coreos=0

global_critical=0
global_unknown=0
nrpe_vuln=""

echo_cmd=''
__echo()
{
	opt="$1"
	shift
	_msg="$@"

	if [ -z "$echo_cmd" ]; then
		# find a sane `echo` command
		# we'll try to avoid using shell builtins that might not take options
		if which echo >/dev/null 2>&1; then
			echo_cmd=`which echo`
		else
			[ -x /bin/echo        ] && echo_cmd=/bin/echo
			[ -x /system/bin/echo ] && echo_cmd=/system/bin/echo
		fi
		# still empty ? fallback to builtin
		[ -z "$echo_cmd" ] && echo_cmd=echo
	fi

	if [ "$opt_no_color" = 1 ] ; then
		# strip ANSI color codes
		_msg=$($echo_cmd -e  "$_msg" | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g")
	fi
	$echo_cmd $opt -e "$_msg"
}

_echo()
{
	if [ $opt_verbose -ge $1 ]; then
		shift
		__echo '' "$@"
	fi
}

_echo_nol()
{
	if [ $opt_verbose -ge $1 ]; then
		shift
		__echo -n "$@"
	fi
}

_warn()
{
	_echo 0 "\033[31m${@}\033[0m" >&2
}

_info()
{
	_echo 1 "$@"
}

_info_nol()
{
	_echo_nol 1 "$@"
}

_verbose()
{
	_echo 2 "$@"
}

_verbose_nol()
{
	_echo_nol 2 "$@"
}

_debug()
{
	_echo 3 "\033[34m(debug) $@\033[0m"
}

is_cpu_vulnerable_cached=0
_is_cpu_vulnerable_cached()
{
	[ "$1" = 1 ] && return $variant1
	[ "$1" = 2 ] && return $variant2
	[ "$1" = 3 ] && return $variant3
	echo "$0: error: invalid variant '$1' passed to is_cpu_vulnerable()" >&2
	exit 255
}

is_cpu_vulnerable()
{
	# param: 1, 2 or 3 (variant)
	# returns 0 if vulnerable, 1 if not vulnerable
	# (note that in shell, a return of 0 is success)
	# by default, everything is vulnerable, we work in a "whitelist" logic here.
	# usage: is_cpu_vulnerable 2 && do something if vulnerable
	if [ "$is_cpu_vulnerable_cached" = 1 ]; then
		_is_cpu_vulnerable_cached "$1"
		return $?
	fi

	variant1=''
	variant2=''
	variant3=''
	# we also set a friendly name for the CPU to be used in the script if needed
	cpu_friendly_name=$(grep '^model name' /proc/cpuinfo | cut -d: -f2- | head -1 | sed -e 's/^ *//')

	if grep -q GenuineIntel /proc/cpuinfo; then
		# Intel
		# Old Atoms are not vulnerable to spectre 2 nor meltdown
		# https://security-center.intel.com/advisory.aspx?intelid=INTEL-SA-00088&languageid=en-fr
		# model name : Genuine Intel(R) CPU N270 @ 1.60GHz
		# model name : Intel(R) Atom(TM) CPU N270 @ 1.60GHz
		# model name : Intel(R) Atom(TM) CPU 330 @ 1.60GHz
		#
		# https://github.com/crozone/SpectrePoC/issues/1 ^F E5200:
		# model name : Pentium(R) Dual-Core  CPU      E5200  @ 2.50GHz
		if grep -qE -e '^model name.+ Intel\(R\) (Atom\(TM\) CPU +(S|D|N|230|330)|CPU N[0-9]{3} )'   \
			    -e '^model name.+ Pentium\(R\) Dual-Core[[:space:]]+CPU[[:space:]]+E[0-9]{4}K? ' \
				/proc/cpuinfo; then
			variant1=vuln
			[ -z "$variant2" ] && variant2=immune
			[ -z "$variant3" ] && variant3=immune
		fi
	elif grep -q AuthenticAMD /proc/cpuinfo; then
		# AMD revised their statement about variant2 => vulnerable
		# https://www.amd.com/en/corporate/speculative-execution
		variant1=vuln
		variant2=vuln
		[ -z "$variant3" ] && variant3=immune
	elif grep -qi 'CPU implementer[[:space:]]*:[[:space:]]*0x41' /proc/cpuinfo; then
		# ARM
		# reference: https://developer.arm.com/support/security-update
		# some devices (phones or other) have several ARMs and as such different part numbers,
		# an example is "bigLITTLE". we shouldn't rely on the first CPU only, so we check the whole list
		cpupart_list=$(awk '/CPU part/         {print $4}' /proc/cpuinfo)
		cpuarch_list=$(awk '/CPU architecture/ {print $3}' /proc/cpuinfo)
		i=0
		for cpupart in $cpupart_list
		do
			i=$(( i + 1 ))
			cpuarch=$(echo $cpuarch_list | awk '{ print $'$i' }')
			_debug "checking cpu$i: <$cpupart> <$cpuarch>"
			# some kernels report AArch64 instead of 8
			[ "$cpuarch" = "AArch64" ] && cpuarch=8
			if [ -n "$cpupart" -a -n "$cpuarch" ]; then
				cpu_friendly_name="ARM v$cpuarch model $cpupart"
				# Cortex-R7 and Cortex-R8 are real-time and only used in medical devices or such
				# I can't find their CPU part number, but it's probably not that useful anyway
				# model R7 R8 A9    A15   A17   A57   A72    A73    A75
				# part   ?  ? 0xc09 0xc0f 0xc0e 0xd07 0xd08  0xd09  0xd0a
				# arch  7? 7? 7     7     7     8     8      8      8
				#
				# variant 1 & variant 2
				if [ "$cpuarch" = 7 ] && echo "$cpupart" | grep -Eq '^0x(c09|c0f|c0e)$'; then
					# armv7 vulnerable chips
					_debug "checking cpu$i: this armv7 vulnerable to spectre 1 & 2"
					variant1=vuln
					variant2=vuln
				elif [ "$cpuarch" = 8 ] && echo "$cpupart" | grep -Eq '^0x(d07|d08|d09|d0a)$'; then
					# armv8 vulnerable chips
					_debug "checking cpu$i: this armv8 vulnerable to spectre 1 & 2"
					variant1=vuln
					variant2=vuln
				else
					_debug "checking cpu$i: this arm non vulnerable to 1 & 2"
					# others are not vulnerable
					[ -z "$variant1" ] && variant1=immune
					[ -z "$variant2" ] && variant2=immune
				fi

				# for variant3, only A75 is vulnerable
				if [ "$cpuarch" = 8 -a "$cpupart" = 0xd0a ]; then
					_debug "checking cpu$i: arm A75 vulnerable to meltdown"
					variant3=vuln
				else
					_debug "checking cpu$i: this arm non vulnerable to meltdown"
					[ -z "$variant3" ] && variant3=immune
				fi
			fi
			_debug "is_cpu_vulnerable: for cpu$i and so far, we have <$variant1> <$variant2> <$variant3>"
		done
	fi
	_debug "is_cpu_vulnerable: temp results are <$variant1> <$variant2> <$variant3>"
	# if at least one of the cpu is vulnerable, then the system is vulnerable
	[ "$variant1" = "immune" ] && variant1=1 || variant1=0
	[ "$variant2" = "immune" ] && variant2=1 || variant2=0
	[ "$variant3" = "immune" ] && variant3=1 || variant3=0
	_debug "is_cpu_vulnerable: final results are <$variant1> <$variant2> <$variant3>"
	is_cpu_vulnerable_cached=1
	_is_cpu_vulnerable_cached "$1"
	return $?
}

show_header()
{
	_info "\033[1;34mSpectre and Meltdown mitigation detection tool v$VERSION\033[0m"
	_info
}

parse_opt_file()
{
	# parse_opt_file option_name option_value
	option_name="$1"
	option_value="$2"
	if [ -z "$option_value" ]; then
		show_header
		show_usage
		echo "$0: error: --$option_name expects one parameter (a file)" >&2
		exit 1
	elif [ ! -e "$option_value" ]; then
		show_header
		echo "$0: error: couldn't find file $option_value" >&2
		exit 1
	elif [ ! -f "$option_value" ]; then
		show_header
		echo "$0: error: $option_value is not a file" >&2
		exit 1
	elif [ ! -r "$option_value" ]; then
		show_header
		echo "$0: error: couldn't read $option_value (are you root?)" >&2
		exit 1
	fi
	echo "$option_value"
	exit 0
}

while [ -n "$1" ]; do
	if [ "$1" = "--kernel" ]; then
		opt_kernel=$(parse_opt_file kernel "$2")
		[ $? -ne 0 ] && exit 255
		shift 2
		opt_live=0
	elif [ "$1" = "--config" ]; then
		opt_config=$(parse_opt_file config "$2")
		[ $? -ne 0 ] && exit 255
		shift 2
		opt_live=0
	elif [ "$1" = "--map" ]; then
		opt_map=$(parse_opt_file map "$2")
		[ $? -ne 0 ] && exit 255
		shift 2
		opt_live=0
	elif [ "$1" = "--live" ]; then
		opt_live_explicit=1
		shift
	elif [ "$1" = "--no-color" ]; then
		opt_no_color=1
		shift
	elif [ "$1" = "--no-sysfs" ]; then
		opt_no_sysfs=1
		shift
	elif [ "$1" = "--sysfs-only" ]; then
		opt_sysfs_only=1
		shift
	elif [ "$1" = "--coreos" ]; then
		opt_coreos=1
		shift
	elif [ "$1" = "--coreos-within-toolbox" ]; then
		# don't use directly: used internally by --coreos
		opt_coreos=0
		shift
	elif [ "$1" = "--batch" ]; then
		opt_batch=1
		opt_verbose=0
		shift
		case "$1" in
			text|nrpe|json) opt_batch_format="$1"; shift;;
			--*) ;;    # allow subsequent flags
			'') ;;     # allow nothing at all
			*)
				echo "$0: error: unknown batch format '$1'" >&2
				echo "$0: error: --batch expects a format from: text, nrpe, json" >&2
				exit 255
				;;
		esac
	elif [ "$1" = "-v" -o "$1" = "--verbose" ]; then
		opt_verbose=$(expr $opt_verbose + 1)
		shift
	elif [ "$1" = "--variant" ]; then
		if [ -z "$2" ]; then
			echo "$0: error: option --variant expects a parameter (1, 2 or 3)" >&2
			exit 255
		fi
		case "$2" in
			1) opt_variant1=1; opt_allvariants=0;;
			2) opt_variant2=1; opt_allvariants=0;;
			3) opt_variant3=1; opt_allvariants=0;;
			*)
				echo "$0: error: invalid parameter '$2' for --variant, expected either 1, 2 or 3" >&2;
				exit 255
				;;
		esac
		shift 2
	elif [ "$1" = "-h" -o "$1" = "--help" ]; then
		show_header
		show_usage
		exit 0
	elif [ "$1" = "--version" ]; then
		opt_no_color=1
		show_header
		exit 0
	elif [ "$1" = "--disclaimer" ]; then
		show_header
		show_disclaimer
		exit 0
	else
		show_header
		show_usage
		echo "$0: error: unknown option '$1'"
		exit 255
	fi
done

show_header

if [ "$opt_no_sysfs" = 1 -a "$opt_sysfs_only" = 1 ]; then
	_warn "Incompatible options specified (--no-sysfs and --sysfs-only), aborting"
	exit 255
fi

# print status function
pstatus()
{
	if [ "$opt_no_color" = 1 ]; then
		_info_nol "$2"
	else
		case "$1" in
			red)    col="\033[41m\033[30m";;
			green)  col="\033[42m\033[30m";;
			yellow) col="\033[43m\033[30m";;
			blue)   col="\033[44m\033[30m";;
			*)      col="";;
		esac
		_info_nol "$col $2 \033[0m"
	fi
	[ -n "$3" ] && _info_nol " ($3)"
	_info
}

# Print the final status of a vulnerability (incl. batch mode)
# Arguments are: CVE UNK/OK/VULN description
pvulnstatus()
{
	if [ "$opt_batch" = 1 ]; then
		case "$opt_batch_format" in
			text) _echo 0 "$1: $2 ($3)";;
			json)
				case "$1" in
					CVE-2017-5753) aka="SPECTRE VARIANT 1";;
					CVE-2017-5715) aka="SPECTRE VARIANT 2";;
					CVE-2017-5754) aka="MELTDOWN";;
				esac
				case "$2" in
					UNK)  is_vuln="null";;
					VULN) is_vuln="true";;
					OK)   is_vuln="false";;
				esac
				json_output="${json_output:-[}{\"NAME\":\""$aka"\",\"CVE\":\""$1"\",\"VULNERABLE\":$is_vuln,\"INFOS\":\""$3"\"},"
				;;

			nrpe)	[ "$2" = VULN ] && nrpe_vuln="$nrpe_vuln $1";;
		esac
	fi

	# always fill global_* vars because we use that do decide the program exit code
	case "$2" in
		UNK)  global_unknown="1";;
		VULN) global_critical="1";;
	esac

	# display info if we're not in quiet/batch mode
	vulnstatus="$2"
	shift 2
	_info_nol "> \033[46m\033[30mSTATUS:\033[0m "
	case "$vulnstatus" in
		UNK)  pstatus yellow 'UNKNOWN'        "$@";;
		VULN) pstatus red    'VULNERABLE'     "$@";;
		OK)   pstatus green  'NOT VULNERABLE' "$@";;
	esac
}


# The 3 below functions are taken from the extract-linux script, available here:
# https://github.com/torvalds/linux/blob/master/scripts/extract-vmlinux
# The functions have been modified for better integration to this script
# The original header of the file has been retained below

# ----------------------------------------------------------------------
# extract-vmlinux - Extract uncompressed vmlinux from a kernel image
#
# Inspired from extract-ikconfig
# (c) 2009,2010 Dick Streefland <dick@streefland.net>
#
# (c) 2011      Corentin Chary <corentin.chary@gmail.com>
#
# Licensed under the GNU General Public License, version 2 (GPLv2).
# ----------------------------------------------------------------------

vmlinux=''
vmlinux_err=''
check_vmlinux()
{
	readelf -h "$1" >/dev/null 2>&1 && return 0
	return 1
}

try_decompress()
{
	# The obscure use of the "tr" filter is to work around older versions of
	# "grep" that report the byte offset of the line instead of the pattern.

	# Try to find the header ($1) and decompress from here
	for     pos in `tr "$1\n$2" "\n$2=" < "$6" | grep -abo "^$2"`
	do
		_debug "try_decompress: magic for $3 found at offset $pos"
		if ! which "$3" >/dev/null 2>&1; then
			vmlinux_err="missing '$3' tool, please install it, usually it's in the '$5' package"
			return 0
		fi
		pos=${pos%%:*}
		tail -c+$pos "$6" 2>/dev/null | $3 $4 > $vmlinuxtmp 2>/dev/null
		if check_vmlinux "$vmlinuxtmp"; then
			vmlinux="$vmlinuxtmp"
			_debug "try_decompress: decompressed with $3 successfully!"
			return 0
		else
			_debug "try_decompress: decompression with $3 did not work"
		fi
	done
	return 1
}

extract_vmlinux()
{
	[ -n "$1" ] || return 1
	# Prepare temp files:
	vmlinuxtmp="$(mktemp /tmp/vmlinux-XXXXXX)"
	trap "rm -f $vmlinuxtmp" EXIT

	# Initial attempt for uncompressed images or objects:
	if check_vmlinux "$1"; then
		cat "$1" > "$vmlinuxtmp"
		vmlinux=$vmlinuxtmp
		return 0
	fi

	# That didn't work, so retry after decompression.
	try_decompress '\037\213\010'     xy    gunzip  ''      gunzip      "$1" && return 0
	try_decompress '\3757zXZ\000'     abcde unxz    ''      xz-utils    "$1" && return 0
	try_decompress 'BZh'              xy    bunzip2 ''      bzip2       "$1" && return 0
	try_decompress '\135\0\0\0'       xxx   unlzma  ''      xz-utils    "$1" && return 0
	try_decompress '\211\114\132'     xy    'lzop'  '-d'    lzop        "$1" && return 0
	try_decompress '\002\041\114\030' xyy   'lz4'   '-d -l' liblz4-tool "$1" && return 0
	return 1
}

# end of extract-vmlinux functions

mount_debugfs()
{
	if [ ! -e /sys/kernel/debug/sched_features ]; then
		# try to mount the debugfs hierarchy ourselves and remember it to umount afterwards
		mount -t debugfs debugfs /sys/kernel/debug 2>/dev/null && mounted_debugfs=1
	fi
}

umount_debugfs()
{
	if [ "$mounted_debugfs" = 1 ]; then
		# umount debugfs if we did mount it ourselves
		umount /sys/kernel/debug
	fi
}

load_msr()
{
	modprobe msr 2>/dev/null && insmod_msr=1
	_debug "attempted to load module msr, insmod_msr=$insmod_msr"
}

unload_msr()
{
	if [ "$insmod_msr" = 1 ]; then
		# if we used modprobe ourselves, rmmod the module
		rmmod msr 2>/dev/null
		_debug "attempted to unload module msr, ret=$?"
	fi
}

load_cpuid()
{
	modprobe cpuid 2>/dev/null && insmod_cpuid=1
	_debug "attempted to load module cpuid, insmod_cpuid=$insmod_cpuid"
}

unload_cpuid()
{
	if [ "$insmod_cpuid" = 1 ]; then
		# if we used modprobe ourselves, rmmod the module
		rmmod cpuid 2>/dev/null
		_debug "attempted to unload module cpuid, ret=$?"
	fi
}

dmesg_grep()
{
	# grep for something in dmesg, ensuring that the dmesg buffer
	# has not been truncated
	dmesg_grepped=''
	if ! dmesg | grep -qE '(^|\] )Linux version [0-9]'; then
		# dmesg truncated
		return 2
	fi
	dmesg_grepped=$(dmesg | grep -E "$1" | head -1)
	# not found:
	[ -z "$dmesg_grepped" ] && return 1
	# found, output is in $dmesg_grepped
	return 0
}

is_coreos()
{
	which coreos-install >/dev/null 2>&1 && which toolbox >/dev/null 2>&1 && return 0
	return 1
}

# check for mode selection inconsistency
if [ "$opt_live_explicit" = 1 ]; then
	if [ -n "$opt_kernel" -o -n "$opt_config" -o -n "$opt_map" ]; then
		show_usage
		echo "$0: error: incompatible modes specified, use either --live or --kernel/--config/--map" >&2
		exit 255
	fi
fi

# coreos mode
if [ "$opt_coreos" = 1 ]; then
	if ! is_coreos; then
		_warn "CoreOS mode asked, but we're not under CoreOS!"
		exit 255
	fi
	_warn "CoreOS mode, starting an ephemeral toolbox to launch the script"
	load_msr
	load_cpuid
	mount_debugfs
	toolbox --ephemeral --bind-ro /dev/cpu:/dev/cpu -- sh -c "dnf install -y binutils which && /media/root$PWD/$0 $@ --coreos-within-toolbox"
	exitcode=$?
	mount_debugfs
	unload_cpuid
	unload_msr
	exit $exitcode
else
	if is_coreos; then
		_warn "You seem to be running CoreOS, you might want to use the --coreos option for better results"
		_warn
	fi
fi

# root check (only for live mode, for offline mode, we already checked if we could read the files)

if [ "$opt_live" = 1 ]; then
	if [ "$(id -u)" -ne 0 ]; then
		_warn "Note that you should launch this script with root privileges to get accurate information."
		_warn "We'll proceed but you might see permission denied errors."
		_warn "To run it as root, you can try the following command: sudo $0"
		_warn
	fi
	_info "Checking for vulnerabilities on current system"
	_info "Kernel is \033[35m"$(uname -s) $(uname -r) $(uname -v) $(uname -m)"\033[0m"
	# call is_cpu_vulnerable to fill the cpu_friendly_name var
	is_cpu_vulnerable 1
	_info "CPU is \033[35m$cpu_friendly_name\033[0m"

	# try to find the image of the current running kernel
	# first, look for the BOOT_IMAGE hint in the kernel cmdline
	if [ -r /proc/cmdline ] && grep -q 'BOOT_IMAGE=' /proc/cmdline; then
		opt_kernel=$(grep -Eo 'BOOT_IMAGE=[^ ]+' /proc/cmdline | cut -d= -f2)
		_debug "found opt_kernel=$opt_kernel in /proc/cmdline"
		# if we have a dedicated /boot partition, our bootloader might have just called it /
		# so try to prepend /boot and see if we find anything
		[ -e "/boot/$opt_kernel" ] && opt_kernel="/boot/$opt_kernel"
		# special case for CoreOS if we're inside the toolbox
		[ -e "/media/root/boot/$opt_kernel" ] && opt_kernel="/media/root/boot/$opt_kernel"
		_debug "opt_kernel is now $opt_kernel"
		# else, the full path is already there (most probably /boot/something)
	fi
	# if we didn't find a kernel, default to guessing
	if [ ! -e "$opt_kernel" ]; then
		# Fedora:
		[ -e /lib/modules/$(uname -r)/vmlinuz ] && opt_kernel=/lib/modules/$(uname -r)/vmlinuz
		# Slackare:
		[ -e /boot/vmlinuz             ] && opt_kernel=/boot/vmlinuz
		# Arch:
		[ -e /boot/vmlinuz-linux       ] && opt_kernel=/boot/vmlinuz-linux
		# Linux-Libre:
		[ -e /boot/vmlinuz-linux-libre ] && opt_kernel=/boot/vmlinuz-linux-libre
		# generic:
		[ -e /boot/vmlinuz-$(uname -r) ] && opt_kernel=/boot/vmlinuz-$(uname -r)
		[ -e /boot/kernel-$( uname -r) ] && opt_kernel=/boot/kernel-$( uname -r)
		[ -e /boot/bzImage-$(uname -r) ] && opt_kernel=/boot/bzImage-$(uname -r)
		# Gentoo:
		[ -e /boot/kernel-genkernel-$(uname -m)-$(uname -r) ] && opt_kernel=/boot/kernel-genkernel-$(uname -m)-$(uname -r)
		# NixOS:
		[ -e /run/booted-system/kernel ] && opt_kernel=/run/booted-system/kernel
	fi

	# system.map
	if [ -e /proc/kallsyms ] ; then
		opt_map="/proc/kallsyms"
	elif [ -e /lib/modules/$(uname -r)/System.map ] ; then
		opt_map=/lib/modules/$(uname -r)/System.map
	elif [ -e /boot/System.map-$(uname -r) ] ; then
		opt_map=/boot/System.map-$(uname -r)
	fi

	# config
	if [ -e /proc/config.gz ] ; then
		dumped_config="$(mktemp /tmp/config-XXXXXX)"
		gunzip -c /proc/config.gz > $dumped_config
		# dumped_config will be deleted at the end of the script
		opt_config=$dumped_config
	elif [ -e /lib/modules/$(uname -r)/config ]; then
		opt_config=/lib/modules/$(uname -r)/config
	elif [ -e /boot/config-$(uname -r) ]; then
		opt_config=/boot/config-$(uname -r)
	fi
else
	_info "Checking for vulnerabilities against specified kernel"
fi

if [ -n "$opt_kernel" ]; then
	_verbose "Will use vmlinux image \033[35m$opt_kernel\033[0m"
else
	_verbose "Will use no vmlinux image (accuracy might be reduced)"
	bad_accuracy=1
fi

if [ -n "$opt_config" ] && ! grep -q '^CONFIG_' "$opt_config"; then
	# given file is invalid!
	_warn "The kernel config file seems invalid, was expecting a plain-text file, ignoring it!"
	opt_config=''
fi

if [ -n "$dumped_config" ] && [ -n "$opt_config" ]; then
	_verbose "Will use kconfig \033[35m/proc/config.gz (decompressed)\033[0m"
elif [ -n "$opt_config" ]; then
	_verbose "Will use kconfig \033[35m$opt_config\033[0m"
else
	_verbose "Will use no kconfig (accuracy might be reduced)"
	bad_accuracy=1
fi

if [ -n "$opt_map" ]; then
	_verbose "Will use System.map file \033[35m$opt_map\033[0m"
else
	_verbose "Will use no System.map file (accuracy might be reduced)"
	bad_accuracy=1
fi

if [ "$bad_accuracy" = 1 ]; then
	_info "We're missing some kernel info (see -v), accuracy might be reduced"
fi

if [ -e "$opt_kernel" ]; then
	if ! which readelf >/dev/null 2>&1; then
		_debug "readelf not found"
		vmlinux_err="missing 'readelf' tool, please install it, usually it's in the 'binutils' package"
	else
		extract_vmlinux "$opt_kernel"
	fi
else
	_debug "no opt_kernel defined"
	vmlinux_err="couldn't find your kernel image in /boot, if you used netboot, this is normal"
fi
if [ -z "$vmlinux" -o ! -r "$vmlinux" ]; then
	[ -z "$vmlinux_err" ] && vmlinux_err="couldn't extract your kernel from $opt_kernel"
fi

_info

# end of header stuff

# now we define some util functions and the check_*() funcs, as
# the user can choose to execute only some of those

sys_interface_check()
{
	[ "$opt_live" = 1 -a "$opt_no_sysfs" = 0 -a -r "$1" ] || return 1
	_info_nol "* Mitigated according to the /sys interface: "
	if grep -qi '^not affected' "$1"; then
		# Not affected
		status=OK
		pstatus green YES "kernel confirms that your CPU is unaffected"
	elif grep -qi '^mitigation' "$1"; then
		# Mitigation: PTI
		status=OK
		pstatus green YES "kernel confirms that the mitigation is active"
	elif grep -qi '^vulnerable' "$1"; then
		# Vulnerable
		status=VULN
		pstatus red NO "kernel confirms your system is vulnerable"
	else
		status=UNK
		pstatus yellow UNKNOWN "unknown value reported by kernel"
	fi
	msg=$(cat "$1")
	_debug "sys_interface_check: $1=$msg"
	return 0
}

###################
# SPECTRE VARIANT 1
check_variant1()
{
	_info "\033[1;34mCVE-2017-5753 [bounds check bypass] aka 'Spectre Variant 1'\033[0m"

	status=UNK
	sys_interface_available=0
	msg=''
	if sys_interface_check "/sys/devices/system/cpu/vulnerabilities/spectre_v1"; then
		# this kernel has the /sys interface, trust it over everything
		sys_interface_available=1
	elif [ "$opt_sysfs_only" != 1 ]; then
		# no /sys interface (or offline mode), fallback to our own ways
		_info_nol "* Checking count of LFENCE opcodes in kernel: "
		if [ -n "$vmlinux_err" ]; then
			msg="couldn't check ($vmlinux_err)"
			status=UNK
			pstatus yellow UNKNOWN
		else
			if ! which objdump >/dev/null 2>&1; then
				msg="missing 'objdump' tool, please install it, usually it's in the binutils package"
				status=UNK
				pstatus yellow UNKNOWN
			else
				# here we disassemble the kernel and count the number of occurrences of the LFENCE opcode
				# in non-patched kernels, this has been empirically determined as being around 40-50
				# in patched kernels, this is more around 70-80, sometimes way higher (100+)
				# v0.13: 68 found in a 3.10.23-xxxx-std-ipv6-64 (with lots of modules compiled-in directly), which doesn't have the LFENCE patches,
				# so let's push the threshold to 70.
				nb_lfence=$(objdump -d "$vmlinux" | grep -wc lfence)
				if [ "$nb_lfence" -lt 70 ]; then
					msg="only $nb_lfence opcodes found, should be >= 70, heuristic to be improved when official patches become available"
					status=VULN
					pstatus red NO
				else
					msg="$nb_lfence opcodes found, which is >= 70, heuristic to be improved when official patches become available"
					status=OK
					pstatus green YES
				fi
			fi
		fi
	else
		# we have no sysfs but were asked to use it only!
		msg="/sys vulnerability interface use forced, but it's not available!"
		status=UNK
	fi

	if ! is_cpu_vulnerable 1; then
		# override status & msg in case CPU is not vulnerable after all
		msg="your CPU vendor reported your CPU model as not vulnerable"
		status=OK
	fi

	# report status
	pvulnstatus CVE-2017-5753 "$status" "$msg"
}

###################
# SPECTRE VARIANT 2
check_variant2()
{
	_info "\033[1;34mCVE-2017-5715 [branch target injection] aka 'Spectre Variant 2'\033[0m"

	status=UNK
	sys_interface_available=0
	msg=''
	if sys_interface_check "/sys/devices/system/cpu/vulnerabilities/spectre_v2"; then
		# this kernel has the /sys interface, trust it over everything
		sys_interface_available=1
	fi
	if [ "$opt_sysfs_only" != 1 ]; then
		_info     "* Mitigation 1"
		_info     "  * Hardware support (CPU microcode)"
		_info     "    * Indirect Branch Restricted Speculation (IBRS)"
		_info_nol "      * SPEC_CTRL MSR is available: "
		if [ ! -e /dev/cpu/0/msr ]; then
			# try to load the module ourselves (and remember it so we can rmmod it afterwards)
			load_msr
		fi
		if [ ! -e /dev/cpu/0/msr ]; then
			pstatus yellow UNKNOWN "couldn't read /dev/cpu/0/msr, is msr support enabled in your kernel?"
		else
			# the new MSR 'SPEC_CTRL' is at offset 0x48
			# here we use dd, it's the same as using 'rdmsr 0x48' but without needing the rdmsr tool
			# if we get a read error, the MSR is not there. bs has to be 8 for msr
			# skip=9 because 8*9=72=0x48
			dd if=/dev/cpu/0/msr of=/dev/null bs=8 count=1 skip=9 2>/dev/null
			if [ $? -eq 0 ]; then
				pstatus green YES
			else
				pstatus red NO
			fi
		fi

		_info_nol "      * CPU indicates IBRS capability: "
		if [ ! -e /dev/cpu/0/cpuid ]; then
			# try to load the module ourselves (and remember it so we can rmmod it afterwards)
			load_cpuid
		fi
		if [ ! -e /dev/cpu/0/cpuid ]; then
			pstatus yellow UNKNOWN "couldn't read /dev/cpu/0/cpuid, is cpuid support enabled in your kernel?"
		else
			# from kernel src: { X86_FEATURE_SPEC_CTRL,        CPUID_EDX,26, 0x00000007, 0 },
			if [ "$opt_verbose" -ge 3 ]; then
				dd if=/dev/cpu/0/cpuid bs=16 skip=7 iflag=skip_bytes count=1 >/dev/null 2>/dev/null
				_debug "cpuid: reading leaf7 of cpuid on cpu0, ret=$?"
				_debug "cpuid: leaf7 eax-ebx-ecx-edx: "$(dd if=/dev/cpu/0/cpuid bs=16 skip=7 iflag=skip_bytes count=1 2>/dev/null | od -x -A n)
				_debug "cpuid: leaf7 edx higher byte is: "$(dd if=/dev/cpu/0/cpuid bs=16 skip=7 iflag=skip_bytes count=1 2>/dev/null | dd bs=1 skip=15 count=1 2>/dev/null | od -x -A n)
			fi
			# getting high byte of edx on leaf7 of cpuinfo in decimal
			edx_hb=$(dd if=/dev/cpu/0/cpuid bs=16 skip=7 iflag=skip_bytes count=1 2>/dev/null | dd bs=1 skip=15 count=1 2>/dev/null | od -t u -A n | awk '{print $1}')
			_debug "cpuid: leaf7 edx higher byte: $edx_hb (decimal)"
			edx_bit26=$(( edx_hb & 4 ))
			_debug "cpuid: edx_bit26=$edx_bit26"
			if [ "$edx_bit26" -eq 4 ]; then
				pstatus green YES "SPEC_CTRL feature bit"
				cpuid_spec_ctrl=1
			else
				pstatus red NO
			fi
		fi

		# hardware support according to kernel
		if [ "$opt_verbose" -ge 2 ]; then
			# the spec_ctrl flag in cpuinfo is set if and only if the kernel sees
			# that the spec_ctrl cpuinfo bit set. we already check that ourselves above
			# but let's check it anyway (in verbose mode only)
			_verbose_nol "      * Kernel has set the spec_ctrl flag in cpuinfo: "
			if [ "$opt_live" = 1 ]; then
				if grep ^flags /proc/cpuinfo | grep -qw spec_ctrl; then
					pstatus green YES
				else
					pstatus blue NO
				fi
			else
				pstatus blue N/A "not testable in offline mode"
			fi
		fi

		# IBPB
		_info     "    * Indirect Branch Prediction Barrier (IBPB)"
		_info_nol "      * PRED_CMD MSR is available: "
		if [ ! -e /dev/cpu/0/msr ]; then
			pstatus yellow UNKNOWN "couldn't read /dev/cpu/0/msr, is msr support enabled in your kernel?"
		else
			# the new MSR 'PRED_CTRL' is at offset 0x49, write-only
			# here we use dd, it's the same as using 'wrmsr 0x49 0' but without needing the wrmsr tool
			# if we get a write error, the MSR is not there
			$echo_cmd -ne "\0\0\0\0\0\0\0\0" | dd of=/dev/cpu/0/msr bs=8 count=1 seek=73 oflag=seek_bytes 2>/dev/null
			if [ $? -eq 0 ]; then
				pstatus green YES
			else
				pstatus red NO
			fi
		fi

		_info_nol "      * CPU indicates IBPB capability: "
		if [ ! -e /dev/cpu/0/cpuid ]; then
			pstatus yellow UNKNOWN "couldn't read /dev/cpu/0/cpuidr, is cpuid support enabled in your kernel?"
		else
			# CPUID EAX=0x80000008, ECX=0x00 return EBX[12] indicates support for just IBPB.
			if [ "$opt_verbose" -ge 3 ]; then
				dd if=/dev/cpu/0/cpuid bs=16 skip=2147483656 iflag=skip_bytes count=1 >/dev/null 2>/dev/null
				_debug "cpuid: reading leaf80000008 of cpuid on cpu0, ret=$?"
				_debug "cpuid: leaf80000008 eax-ebx-ecx-edx: "$(dd if=/dev/cpu/0/cpuid bs=16 skip=2147483656 iflag=skip_bytes count=1 2>/dev/null | od -x -A n)
				_debug "cpuid: leaf80000008 ebx 3rd byte is: "$(dd if=/dev/cpu/0/cpuid bs=16 skip=2147483656 iflag=skip_bytes count=1 2>/dev/null | dd bs=1 skip=5 count=1 2>/dev/null | od -x -A n)
			fi
			# getting high byte of edx on leaf7 of cpuinfo in decimal
			ebx_b3=$(dd if=/dev/cpu/0/cpuid bs=16 skip=2147483656 iflag=skip_bytes count=1 2>/dev/null | dd bs=1 skip=5 count=1 2>/dev/null | od -t u -A n | awk '{print $1}')
			_debug "cpuid: leaf80000008 ebx 3rd byte: $ebx_b3 (decimal)"
			ebx_bit12=$(( ebx_b3 & 16 ))
			_debug "cpuid: ebx_bit12=$ebx_bit12"
			if [ "$ebx_bit12" -eq 16 ]; then
				pstatus green YES "IBPB_SUPPORT feature bit"
				cpuid_ibpb=1
			elif [ "$cpuid_spec_ctrl" = 1 ]; then
				pstatus green YES "SPEC_CTRL feature bit"
			else
				pstatus red NO
			fi
		fi

		_info_nol "  * Kernel is compiled with IBRS/IBPB support: "
		ibrs_can_tell=0

		if [ "$opt_live" = 1 ]; then
			ibrs_can_tell=1
			mount_debugfs
			for dir in \
				/sys/kernel/debug \
				/sys/kernel/debug/x86 \
				/proc/sys/kernel; do
				if [ -e "$dir/ibrs_enabled" ]; then
					# if the file is there, we have IBRS compiled-in
					# /sys/kernel/debug/ibrs_enabled: vanilla
					# /sys/kernel/debug/x86/ibrs_enabled: RedHat (see https://access.redhat.com/articles/3311301)
					# /proc/sys/kernel/ibrs_enabled: OpenSUSE tumbleweed
					pstatus green YES
					ibrs_knob_dir=$dir
					ibrs_supported=1
					ibrs_enabled=$(cat "$dir/ibrs_enabled" 2>/dev/null)
					_debug "ibrs: found $dir/ibrs_enabled=$ibrs_enabled"
					if [ -e "$dir/ibpb_enabled" ]; then
						ibpb_enabled=$(cat "$dir/ibpb_enabled" 2>/dev/null)
						_debug "ibpb: found $dir/ibpb_enabled=$ibpb_enabled"
					else
						ibpb_enabled=-1
						_debug "ibpb: no ibpb_enabled file in $dir"
					fi
					break
				else
					_debug "ibrs: $dir/ibrs_enabled file doesn't exist"
				fi
			done
			# on some newer kernels, the spec_ctrl_ibrs flag in /proc/cpuinfo
			# is set when ibrs has been administratively enabled (usually from cmdline)
			# which in that case means ibrs is supported *and* enabled for kernel & user
			# as per the ibrs patch series v3
			if [ "$ibrs_supported" = 0 ]; then
				if grep ^flags /proc/cpuinfo | grep -qw spec_ctrl_ibrs; then
					_debug "ibrs: found spec_ctrl_ibrs flag in /proc/cpuinfo"
					ibrs_supported=1
					# enabled=2 -> kernel & user
					ibrs_enabled=2
					# XXX and what about ibpb ?
				fi
			fi
		fi
		if [ "$ibrs_supported" != 1 -a -n "$opt_map" ]; then
			ibrs_can_tell=1
			if grep -q spec_ctrl "$opt_map"; then
				pstatus green YES
				ibrs_supported=1
				_debug "ibrs: found '*spec_ctrl*' symbol in $opt_map"
			fi
		fi
		if [ "$ibrs_supported" != 1 ]; then
			if [ "$ibrs_can_tell" = 1 ]; then
				pstatus red NO
			else
				# if we're in offline mode without System.map, we can't really know
				pstatus yellow UNKNOWN "in offline mode, we need System.map to be able to tell"
			fi
		fi

		_info     "  * Currently enabled features"
		_info_nol "    * IBRS enabled for Kernel space: "
		if [ "$opt_live" = 1 ]; then
			if [ "$ibpb_enabled" = 2 ]; then
				# if ibpb=2, ibrs is forcefully=0
				pstatus blue NO "IBPB used instead of IBRS in all kernel entrypoints"
			else
				# 0 means disabled
				# 1 is enabled only for kernel space
				# 2 is enabled for kernel and user space
				case "$ibrs_enabled" in
					"") [ "$ibrs_supported" = 1 ] && pstatus yellow UNKNOWN || pstatus red NO;;
					0)     pstatus red NO "echo 1 > $ibrs_knob_dir/ibrs_enabled";;
					1 | 2) pstatus green YES;;
					*)     pstatus yellow UNKNOWN;;
				esac
			fi
		else
			pstatus blue N/A "not testable in offline mode"
		fi

		_info_nol "    * IBRS enabled for User space: "
		if [ "$opt_live" = 1 ]; then
			if [ "$ibpb_enabled" = 2 ]; then
				# if ibpb=2, ibrs is forcefully=0
				pstatus blue NO "IBPB used instead of IBRS in all kernel entrypoints"
			else
				case "$ibrs_enabled" in
					"") [ "$ibrs_supported" = 1 ] && pstatus yellow UNKNOWN || pstatus red NO;;
					0 | 1) pstatus red NO "echo 2 > $ibrs_knob_dir/ibrs_enabled";;
					2) pstatus green YES;;
					*) pstatus yellow UNKNOWN;;
				esac
			fi
		else
			pstatus blue N/A "not testable in offline mode"
		fi

		_info_nol "    * IBPB enabled: "
		if [ "$opt_live" = 1 ]; then
			case "$ibpb_enabled" in
				"") [ "$ibrs_supported" = 1 ] && pstatus yellow UNKNOWN || pstatus red NO;;
				0) pstatus red NO "echo 1 > $ibrs_knob_dir/ibpb_enabled";;
				1) pstatus green YES;;
				2) pstatus green YES "IBPB used instead of IBRS in all kernel entrypoints";;
				*) pstatus yellow UNKNOWN;;
			esac
		else
			pstatus blue N/A "not testable in offline mode"
		fi

		unload_msr
		unload_cpuid

		_info "* Mitigation 2"
		_info_nol "  * Kernel compiled with retpoline option: "
		# We check the RETPOLINE kernel options
		if [ -r "$opt_config" ]; then
			if grep -q '^CONFIG_RETPOLINE=y' "$opt_config"; then
				pstatus green YES
				retpoline=1
				_debug "retpoline: found "$(grep '^CONFIG_RETPOLINE' "$opt_config")" in $opt_config"
			else
				pstatus red NO
			fi
		else
			pstatus yellow UNKNOWN "couldn't read your kernel configuration"
		fi

		_info_nol "  * Kernel compiled with a retpoline-aware compiler: "
		# Now check if the compiler used to compile the kernel knows how to insert retpolines in generated asm
		# For gcc, this is -mindirect-branch=thunk-extern (detected by the kernel makefiles)
		# See gcc commit https://github.com/hjl-tools/gcc/commit/23b517d4a67c02d3ef80b6109218f2aadad7bd79
		# In latest retpoline LKML patches, the noretpoline_setup symbol exists only if CONFIG_RETPOLINE is set
		# *AND* if the compiler is retpoline-compliant, so look for that symbol
		if [ -e "/sys/devices/system/cpu/vulnerabilities/spectre_v2" ]; then
			if grep -qw Minimal /sys/devices/system/cpu/vulnerabilities/spectre_v2; then
				pstatus red NO "kernel reports minimal retpoline compilation"
			elif grep -qw Full /sys/devices/system/cpu/vulnerabilities/spectre_v2; then
				retpoline_compiler=1
				pstatus green YES "kernel reports full retpoline compilation"
			else
				[ "$retpoline" = 1 ] && pstatus yellow UNKNOWN || pstatus red NO
			fi
		elif [ -n "$opt_map" ]; then
			# look for the symbol
			if grep -qw noretpoline_setup "$opt_map"; then
				retpoline_compiler=1
				pstatus green YES "noretpoline_setup symbol found in System.map"
			else
				[ "$retpoline" = 1 ] && pstatus yellow UNKNOWN || pstatus red NO
			fi
		elif [ -n "$vmlinux" ]; then
			# look for the symbol
			if which nm >/dev/null 2>&1; then
				# the proper way: use nm and look for the symbol
				if nm "$vmlinux" 2>/dev/null | grep -qw 'noretpoline_setup'; then
					retpoline_compiler=1
					pstatus green YES "noretpoline_setup found in vmlinux symbols"
				else
					[ "$retpoline" = 1 ] && pstatus yellow UNKNOWN || pstatus red NO
				fi
			elif grep -q noretpoline_setup "$vmlinux"; then
				# if we don't have nm, nevermind, the symbol name is long enough to not have
				# any false positive using good old grep directly on the binary
				retpoline_compiler=1
				pstatus green YES "noretpoline_setup found in vmlinux"
			else
				[ "$retpoline" = 1 ] && pstatus yellow UNKNOWN || pstatus red NO
			fi
		else
			[ "$retpoline" = 1 ] && pstatus yellow UNKNOWN "couldn't find your kernel image or System.map" || pstatus red NO
		fi

		_info_nol "  * Retpoline enabled: "
		if [ "$opt_live" = 1 ]; then
			# kernel adds this flag when retpoline is supported and enabled,
			# regardless of the fact that it's minimal / full and generic / amd
			if grep -qw retpoline /proc/cpuinfo; then
				pstatus green YES
				retpoline_enabled=1
			else
				pstatus red NO
			fi
		else
			pstatus blue N/A "can't check this in offline mode"
		fi
	elif [ "$sys_interface_available" = 0 ]; then
		# we have no sysfs but were asked to use it only!
		msg="/sys vulnerability interface use forced, but it's not available!"
		status=UNK
	fi

	cve='CVE-2017-5715'
	if ! is_cpu_vulnerable 2; then
		# override status & msg in case CPU is not vulnerable after all
		pvulnstatus $cve OK "your CPU vendor reported your CPU model as not vulnerable"
	elif [ -z "$msg" ]; then
		# if msg is empty, sysfs check didn't fill it, rely on our own test
		if [ "$retpoline" = 1 -a "$retpoline_compiler" = 1 ]; then
			pvulnstatus $cve OK "retpoline mitigates the vulnerability"
		elif [ "$opt_live" = 1 ]; then
			if [ "$ibrs_enabled" = 1 -o "$ibrs_enabled" = 2 ] && [ "$ibpb_enabled" = 1 ]; then
				pvulnstatus $cve OK "IBRS/IBPB are mitigating the vulnerability"
			elif [ "$ibrs_enabled" = 1 -o "$ibrs_enabled" = 2 ] && [ "$ibpb_enabled" = -1 ]; then
				# IBPB doesn't seem here on this kernel
				pvulnstatus $cve OK "IBRS is mitigating the vulnerability"
			elif [ "$ibpb_enabled" = 2 ]; then
				pvulnstatus $cve OK "Full IBPB is mitigating the vulnerability"
			else
				pvulnstatus $cve VULN "IBRS hardware + kernel support OR kernel with retpoline are needed to mitigate the vulnerability"
			fi
		else
			if [ "$ibrs_supported" = 1 ]; then
				pvulnstatus $cve OK "offline mode: IBRS/IBPB will mitigate the vulnerability if enabled at runtime"
			elif [ "$ibrs_can_tell" = 1 ]; then
				pvulnstatus $cve VULN "IBRS hardware + kernel support OR kernel with retpoline are needed to mitigate the vulnerability"
			else
				pvulnstatus $cve UNK "offline mode: not enough information"
			fi
		fi
	else
		[ "$msg" = "Vulnerable" ] && msg="IBRS hardware + kernel support OR kernel with retpoline are needed to mitigate the vulnerability"
		pvulnstatus $cve "$status" "$msg"
	fi
}

########################
# MELTDOWN aka VARIANT 3
check_variant3()
{
	_info "\033[1;34mCVE-2017-5754 [rogue data cache load] aka 'Meltdown' aka 'Variant 3'\033[0m"

	status=UNK
	sys_interface_available=0
	msg=''
	if sys_interface_check "/sys/devices/system/cpu/vulnerabilities/meltdown"; then
		# this kernel has the /sys interface, trust it over everything
		sys_interface_available=1
	fi
	if [ "$opt_sysfs_only" != 1 ]; then
		_info_nol "* Kernel supports Page Table Isolation (PTI): "
		kpti_support=0
		kpti_can_tell=0
		if [ -n "$opt_config" ]; then
			kpti_can_tell=1
			if grep -Eq '^(CONFIG_PAGE_TABLE_ISOLATION|CONFIG_KAISER)=y' "$opt_config"; then
				_debug "kpti_support: found option "$(grep -E '^(CONFIG_PAGE_TABLE_ISOLATION|CONFIG_KAISER)=y' "$opt_config")" in $opt_config"
				kpti_support=1
			fi
		fi
		if [ "$kpti_support" = 0 -a -n "$opt_map" ]; then
			# it's not an elif: some backports don't have the PTI config but still include the patch
			# so we try to find an exported symbol that is part of the PTI patch in System.map
			kpti_can_tell=1
			if grep -qw kpti_force_enabled "$opt_map"; then
				_debug "kpti_support: found kpti_force_enabled in $opt_map"
				kpti_support=1
			fi
		fi
		if [ "$kpti_support" = 0 -a -n "$vmlinux" ]; then
			# same as above but in case we don't have System.map and only vmlinux, look for the
			# nopti option that is part of the patch (kernel command line option)
			kpti_can_tell=1
			if ! which strings >/dev/null 2>&1; then
				pstatus yellow UNKNOWN "missing 'strings' tool, please install it, usually it's in the binutils package"
			else
				if strings "$vmlinux" | grep -qw nopti; then
					_debug "kpti_support: found nopti string in $vmlinux"
					kpti_support=1
				fi
			fi
		fi

		if [ "$kpti_support" = 1 ]; then
			pstatus green YES
		elif [ "$kpti_can_tell" = 1 ]; then
			pstatus red NO
		else
			pstatus yellow UNKNOWN "couldn't read your kernel configuration nor System.map file"
		fi

		mount_debugfs
		_info_nol "* PTI enabled and active: "
		if [ "$opt_live" = 1 ]; then
			dmesg_grep="Kernel/User page tables isolation: enabled"
			dmesg_grep="$dmesg_grep|Kernel page table isolation enabled"
			dmesg_grep="$dmesg_grep|x86/pti: Unmapping kernel while in userspace"
			if grep ^flags /proc/cpuinfo | grep -qw pti; then
				# vanilla PTI patch sets the 'pti' flag in cpuinfo
				_debug "kpti_enabled: found 'pti' flag in /proc/cpuinfo"
				kpti_enabled=1
			elif grep ^flags /proc/cpuinfo | grep -qw kaiser; then
				# kernel line 4.9 sets the 'kaiser' flag in cpuinfo
				_debug "kpti_enabled: found 'kaiser' flag in /proc/cpuinfo"
				kpti_enabled=1
			elif [ -e /sys/kernel/debug/x86/pti_enabled ]; then
				# RedHat Backport creates a dedicated file, see https://access.redhat.com/articles/3311301
				kpti_enabled=$(cat /sys/kernel/debug/x86/pti_enabled 2>/dev/null)
				_debug "kpti_enabled: file /sys/kernel/debug/x86/pti_enabled exists and says: $kpti_enabled"
			fi
			if [ -z "$kpti_enabled" ]; then
				dmesg_grep "$dmesg_grep"; ret=$?
				if [ $ret -eq 0 ]; then
					_debug "kpti_enabled: found hint in dmesg: $dmesg_grepped"
					kpti_enabled=1
				elif [ $ret -eq 2 ]; then
					_debug "kpti_enabled: dmesg truncated"
					kpti_enabled=-1
				fi
			fi
			if [ -z "$kpti_enabled" ]; then
				_debug "kpti_enabled: couldn't find any hint that PTI is enabled"
				kpti_enabled=0
			fi
			if [ "$kpti_enabled" = 1 ]; then
				pstatus green YES
			elif [ "$kpti_enabled" = -1 ]; then
				pstatus yellow UNKNOWN "dmesg truncated, please reboot and relaunch this script"
			else
				pstatus red NO
			fi
		else
			pstatus blue N/A "can't verify if PTI is enabled in offline mode"
		fi

		# no security impact but give a hint to the user in verbose mode
		# about PCID/INVPCID cpuid features that must be present to avoid
		# too big a performance impact with PTI
		# refs:
		# https://marc.info/?t=151532047900001&r=1&w=2
		# https://groups.google.com/forum/m/#!topic/mechanical-sympathy/L9mHTbeQLNU
		if [ "$opt_verbose" -ge 2 ]; then
			_info "* Performance impact if PTI is enabled"
			_info_nol "  * CPU supports PCID: "
			if grep ^flags /proc/cpuinfo | grep -qw pcid; then
				pstatus green YES 'performance degradation with PTI will be limited'
			else
				pstatus blue NO 'no security impact but performance will be degraded with PTI'
			fi
			_info_nol "  * CPU supports INVPCID: "
			if grep ^flags /proc/cpuinfo | grep -qw invpcid; then
				pstatus green YES 'performance degradation with PTI will be limited'
			else
				pstatus blue NO 'no security impact but performance will be degraded with PTI'
			fi
		fi

		if [ "$opt_live" = 1 ]; then
			# checking whether we're running under Xen PV 64 bits. If yes, we're not affected by variant3
			_info_nol "* Running under Xen PV (64 bits): "
			if [ "$(uname -m)" = "x86_64" ]; then
				# XXX do we have a better way that relying on dmesg?
				dmesg_grep 'Booting paravirtualized kernel on Xen$'; ret=$?
				if [ $ret -eq 0 ]; then
					pstatus green YES 'Xen PV is not vulnerable'
					xen_pv=1
				elif [ $ret -eq 2 ]; then
					pstatus yellow UNKNOWN "dmesg truncated, please reboot and relaunch this script"
				else
					pstatus blue NO
				fi
			else
				pstatus blue NO
			fi
		fi
	elif [ "$sys_interface_available" = 0 ]; then
		# we have no sysfs but were asked to use it only!
		msg="/sys vulnerability interface use forced, but it's not available!"
		status=UNK
	fi

	cve='CVE-2017-5754'
	if ! is_cpu_vulnerable 3; then
		# override status & msg in case CPU is not vulnerable after all
		pvulnstatus $cve OK "your CPU vendor reported your CPU model as not vulnerable"
	elif [ -z "$msg" ]; then
		# if msg is empty, sysfs check didn't fill it, rely on our own test
		if [ "$opt_live" = 1 ]; then
			if [ "$kpti_enabled" = 1 ]; then
				pvulnstatus $cve OK "PTI mitigates the vulnerability"
			elif [ "$xen_pv" = 1 ]; then
				pvulnstatus $cve OK "Xen PV 64 bits is not vulnerable"
			else
				pvulnstatus $cve VULN "PTI is needed to mitigate the vulnerability"
			fi
		else
			if [ "$kpti_support" = 1 ]; then
				pvulnstatus $cve OK "offline mode: PTI will mitigate the vulnerability if enabled at runtime"
			elif [ "$kpti_can_tell" = 1 ]; then
				pvulnstatus $cve VULN "PTI is needed to mitigate the vulnerability"
			else
				pvulnstatus $cve UNK "offline mode: not enough information"
			fi
		fi
	else
		[ "$msg" = "Vulnerable" ] && msg="PTI is needed to mitigate the vulnerability"
		pvulnstatus $cve "$status" "$msg"
	fi
}

# now run the checks the user asked for
if [ "$opt_variant1" = 1 -o "$opt_allvariants" = 1 ]; then
	check_variant1
	_info
fi
if [ "$opt_variant2" = 1 -o "$opt_allvariants" = 1 ]; then
	check_variant2
	_info
fi
if [ "$opt_variant3" = 1 -o "$opt_allvariants" = 1 ]; then
	check_variant3
	_info
fi

_info "A false sense of security is worse than no security at all, see --disclaimer"

# this'll umount only if we mounted debugfs ourselves
umount_debugfs

# cleanup the temp decompressed config
[ -n "$dumped_config" ] && [ -f "$dumped_config" ] && rm -f "$dumped_config"

if [ "$opt_batch" = 1 -a "$opt_batch_format" = "nrpe" ]; then
	if [ ! -z "$nrpe_vuln" ]; then
		echo "Vulnerable:$nrpe_vuln"
	else
		echo "OK"
	fi
fi

if [ "$opt_batch" = 1 -a "$opt_batch_format" = "json" ]; then
	_echo 0 ${json_output%?}']'
fi

# exit with the proper exit code
[ "$global_critical" = 1 ] && exit 2  # critical
[ "$global_unknown"  = 1 ] && exit 3  # unknown
exit 0  # ok