1//===-- llvm-cfi-verify.cpp - CFI Verification tool for LLVM --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This tool verifies Control Flow Integrity (CFI) instrumentation by static
10// binary analysis. See the design document in /docs/CFIVerify.md for more
11// information.
12//
13// This tool is currently incomplete. It currently only does disassembly for
14// object files, and searches through the code for indirect control flow
15// instructions, printing them once found.
16//
17//===----------------------------------------------------------------------===//
18
19#include "lib/FileAnalysis.h"
20#include "lib/GraphBuilder.h"
21
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Error.h"
24#include "llvm/Support/FormatVariadic.h"
25#include "llvm/Support/SpecialCaseList.h"
26#include "llvm/Support/VirtualFileSystem.h"
27
28#include <cstdlib>
29
30using namespace llvm;
31using namespace llvm::object;
32using namespace llvm::cfi_verify;
33
34static cl::OptionCategory CFIVerifyCategory("CFI Verify Options");
35
36static cl::opt<std::string> InputFilename(cl::Positional,
37 cl::desc("<input file>"),
38 cl::Required,
39 cl::cat(CFIVerifyCategory));
40static cl::opt<std::string> IgnorelistFilename(cl::Positional,
41 cl::desc("[ignorelist file]"),
42 cl::init(Val: "-"),
43 cl::cat(CFIVerifyCategory));
44static cl::opt<bool> PrintGraphs(
45 "print-graphs",
46 cl::desc("Print graphs around indirect CF instructions in DOT format."),
47 cl::init(Val: false), cl::cat(CFIVerifyCategory));
48static cl::opt<unsigned> PrintBlameContext(
49 "blame-context",
50 cl::desc("Print the blame context (if possible) for BAD instructions. This "
51 "specifies the number of lines of context to include, where zero "
52 "disables this feature."),
53 cl::init(Val: 0), cl::cat(CFIVerifyCategory));
54static cl::opt<unsigned> PrintBlameContextAll(
55 "blame-context-all",
56 cl::desc("Prints the blame context (if possible) for ALL instructions. "
57 "This specifies the number of lines of context for non-BAD "
58 "instructions (see --blame-context). If --blame-context is "
59 "unspecified, it prints this number of contextual lines for BAD "
60 "instructions as well."),
61 cl::init(Val: 0), cl::cat(CFIVerifyCategory));
62static cl::opt<bool> Summarize("summarize", cl::desc("Print the summary only."),
63 cl::init(Val: false), cl::cat(CFIVerifyCategory));
64
65ExitOnError ExitOnErr;
66
67static void printBlameContext(const DILineInfo &LineInfo, unsigned Context) {
68 auto FileOrErr = MemoryBuffer::getFile(Filename: LineInfo.FileName);
69 if (!FileOrErr) {
70 errs() << "Could not open file: " << LineInfo.FileName << "\n";
71 return;
72 }
73
74 std::unique_ptr<MemoryBuffer> File = std::move(FileOrErr.get());
75 SmallVector<StringRef, 100> Lines;
76 File->getBuffer().split(A&: Lines, Separator: '\n');
77
78 for (unsigned i = std::max<size_t>(a: 1, b: LineInfo.Line - Context);
79 i < std::min<size_t>(a: Lines.size() + 1, b: LineInfo.Line + Context + 1);
80 ++i) {
81 if (i == LineInfo.Line)
82 outs() << ">";
83 else
84 outs() << " ";
85
86 outs() << i << ": " << Lines[i - 1] << "\n";
87 }
88}
89
90static void printInstructionInformation(const FileAnalysis &Analysis,
91 const Instr &InstrMeta,
92 const GraphResult &Graph,
93 CFIProtectionStatus ProtectionStatus) {
94 outs() << "Instruction: " << format_hex(N: InstrMeta.VMAddress, Width: 2) << " ("
95 << stringCFIProtectionStatus(Status: ProtectionStatus) << "): ";
96 Analysis.printInstruction(InstrMeta, OS&: outs());
97 outs() << " \n";
98
99 if (PrintGraphs)
100 Graph.printToDOT(Analysis, OS&: outs());
101}
102
103static void printInstructionStatus(unsigned BlameLine, bool CFIProtected,
104 const DILineInfo &LineInfo) {
105 if (BlameLine) {
106 outs() << "Ignorelist Match: " << IgnorelistFilename << ":" << BlameLine
107 << "\n";
108 if (CFIProtected)
109 outs() << "====> Unexpected Protected\n";
110 else
111 outs() << "====> Expected Unprotected\n";
112
113 if (PrintBlameContextAll)
114 printBlameContext(LineInfo, Context: PrintBlameContextAll);
115 } else {
116 if (CFIProtected) {
117 outs() << "====> Expected Protected\n";
118 if (PrintBlameContextAll)
119 printBlameContext(LineInfo, Context: PrintBlameContextAll);
120 } else {
121 outs() << "====> Unexpected Unprotected (BAD)\n";
122 if (PrintBlameContext)
123 printBlameContext(LineInfo, Context: PrintBlameContext);
124 }
125 }
126}
127
128static void
129printIndirectCFInstructions(FileAnalysis &Analysis,
130 const SpecialCaseList *SpecialCaseList) {
131 uint64_t ExpectedProtected = 0;
132 uint64_t UnexpectedProtected = 0;
133 uint64_t ExpectedUnprotected = 0;
134 uint64_t UnexpectedUnprotected = 0;
135
136 std::map<unsigned, uint64_t> BlameCounter;
137
138 for (object::SectionedAddress Address : Analysis.getIndirectInstructions()) {
139 const auto &InstrMeta = Analysis.getInstructionOrDie(Address: Address.Address);
140 GraphResult Graph = GraphBuilder::buildFlowGraph(Analysis, Address);
141
142 CFIProtectionStatus ProtectionStatus =
143 Analysis.validateCFIProtection(Graph);
144 bool CFIProtected = (ProtectionStatus == CFIProtectionStatus::PROTECTED);
145
146 if (!Summarize) {
147 outs() << "-----------------------------------------------------\n";
148 printInstructionInformation(Analysis, InstrMeta, Graph, ProtectionStatus);
149 }
150
151 if (IgnoreDWARFFlag) {
152 if (CFIProtected)
153 ExpectedProtected++;
154 else
155 UnexpectedUnprotected++;
156 continue;
157 }
158
159 auto InliningInfo = Analysis.symbolizeInlinedCode(Address);
160 if (!InliningInfo || InliningInfo->getNumberOfFrames() == 0) {
161 errs() << "Failed to symbolise " << format_hex(N: Address.Address, Width: 2)
162 << " with line tables from " << InputFilename << "\n";
163 exit(EXIT_FAILURE);
164 }
165
166 const auto &LineInfo = InliningInfo->getFrame(Index: 0);
167
168 // Print the inlining symbolisation of this instruction.
169 if (!Summarize) {
170 for (uint32_t i = 0; i < InliningInfo->getNumberOfFrames(); ++i) {
171 const auto &Line = InliningInfo->getFrame(Index: i);
172 outs() << " " << format_hex(N: Address.Address, Width: 2) << " = "
173 << Line.FileName << ":" << Line.Line << ":" << Line.Column
174 << " (" << Line.FunctionName << ")\n";
175 }
176 }
177
178 if (!SpecialCaseList) {
179 if (CFIProtected) {
180 if (PrintBlameContextAll && !Summarize)
181 printBlameContext(LineInfo, Context: PrintBlameContextAll);
182 ExpectedProtected++;
183 } else {
184 if (PrintBlameContext && !Summarize)
185 printBlameContext(LineInfo, Context: PrintBlameContext);
186 UnexpectedUnprotected++;
187 }
188 continue;
189 }
190
191 unsigned BlameLine = 0;
192 for (auto &K : {"cfi-icall", "cfi-vcall"}) {
193 if (!BlameLine) {
194 auto [FileIdx, Line] =
195 SpecialCaseList->inSectionBlame(Section: K, Prefix: "src", Query: LineInfo.FileName);
196 BlameLine = Line;
197 }
198 if (!BlameLine) {
199 auto [FileIdx, Line] =
200 SpecialCaseList->inSectionBlame(Section: K, Prefix: "fun", Query: LineInfo.FunctionName);
201 BlameLine = Line;
202 }
203 }
204
205 if (BlameLine) {
206 BlameCounter[BlameLine]++;
207 if (CFIProtected)
208 UnexpectedProtected++;
209 else
210 ExpectedUnprotected++;
211 } else {
212 if (CFIProtected)
213 ExpectedProtected++;
214 else
215 UnexpectedUnprotected++;
216 }
217
218 if (!Summarize)
219 printInstructionStatus(BlameLine, CFIProtected, LineInfo);
220 }
221
222 uint64_t IndirectCFInstructions = ExpectedProtected + UnexpectedProtected +
223 ExpectedUnprotected + UnexpectedUnprotected;
224
225 if (IndirectCFInstructions == 0) {
226 outs() << "No indirect CF instructions found.\n";
227 return;
228 }
229
230 outs() << formatv(Fmt: "\nTotal Indirect CF Instructions: {0}\n"
231 "Expected Protected: {1} ({2:P})\n"
232 "Unexpected Protected: {3} ({4:P})\n"
233 "Expected Unprotected: {5} ({6:P})\n"
234 "Unexpected Unprotected (BAD): {7} ({8:P})\n",
235 Vals&: IndirectCFInstructions, Vals&: ExpectedProtected,
236 Vals: ((double)ExpectedProtected) / IndirectCFInstructions,
237 Vals&: UnexpectedProtected,
238 Vals: ((double)UnexpectedProtected) / IndirectCFInstructions,
239 Vals&: ExpectedUnprotected,
240 Vals: ((double)ExpectedUnprotected) / IndirectCFInstructions,
241 Vals&: UnexpectedUnprotected,
242 Vals: ((double)UnexpectedUnprotected) / IndirectCFInstructions);
243
244 if (!SpecialCaseList)
245 return;
246
247 outs() << "\nIgnorelist Results:\n";
248 for (const auto &KV : BlameCounter) {
249 outs() << " " << IgnorelistFilename << ":" << KV.first << " affects "
250 << KV.second << " indirect CF instructions.\n";
251 }
252}
253
254int main(int argc, char **argv) {
255 cl::HideUnrelatedOptions(Categories: {&CFIVerifyCategory, &getColorCategory()});
256 cl::ParseCommandLineOptions(
257 argc, argv,
258 Overview: "Identifies whether Control Flow Integrity protects all indirect control "
259 "flow instructions in the provided object file, DSO or binary.\nNote: "
260 "Anything statically linked into the provided file *must* be compiled "
261 "with '-g'. This can be relaxed through the '--ignore-dwarf' flag.");
262
263 InitializeAllTargetInfos();
264 InitializeAllTargetMCs();
265 InitializeAllAsmParsers();
266 InitializeAllDisassemblers();
267
268 if (PrintBlameContextAll && !PrintBlameContext)
269 PrintBlameContext.setValue(V: PrintBlameContextAll);
270
271 std::unique_ptr<SpecialCaseList> SpecialCaseList;
272 if (IgnorelistFilename != "-") {
273 std::string Error;
274 SpecialCaseList = SpecialCaseList::create(Paths: {IgnorelistFilename},
275 FS&: *vfs::getRealFileSystem(), Error);
276 if (!SpecialCaseList) {
277 errs() << "Failed to get ignorelist: " << Error << "\n";
278 exit(EXIT_FAILURE);
279 }
280 }
281
282 FileAnalysis Analysis = ExitOnErr(FileAnalysis::Create(Filename: InputFilename));
283 printIndirectCFInstructions(Analysis, SpecialCaseList: SpecialCaseList.get());
284
285 return EXIT_SUCCESS;
286}
287