Debian Codegraph @

gcc/ada/doc/gnat_rm/security_hardening_features.rst

raw
1 .. _Security_Hardening_Features:
2
3 ***************************
4 Security Hardening Features
5 ***************************
6
7 This chapter describes Ada extensions aimed at security hardening that
8 are provided by GNAT.
9
10 The features in this chapter are currently experimental and subject to
11 change.
12
13 .. Register Scrubbing:
14
15 Register Scrubbing
16 ==================
17
18 GNAT can generate code to zero-out hardware registers before returning
19 from a subprogram.
20
21 It can be enabled with the :switch:`-fzero-call-used-regs={choice}`
22 command-line option, to affect all subprograms in a compilation, and
23 with a :samp:`Machine_Attribute` pragma, to affect only specific
24 subprograms.
25
26 .. code-block:: ada
27
28 procedure Foo;
29 pragma Machine_Attribute (Foo, "zero_call_used_regs", "used");
30 -- Before returning, Foo scrubs only call-clobbered registers
31 -- that it uses itself.
32
33 function Bar return Integer;
34 pragma Machine_Attribute (Bar, "zero_call_used_regs", "all");
35 -- Before returning, Bar scrubs all call-clobbered registers.
36
37
38 For usage and more details on the command-line option, on the
39 ``zero_call_used_regs`` attribute, and on their use with other
40 programming languages, see :title:`Using the GNU Compiler Collection
41 (GCC)`.
42
43
44 .. Stack Scrubbing:
45
46 Stack Scrubbing
47 ===============
48
49 GNAT can generate code to zero-out stack frames used by subprograms.
50
51 It can be activated with the :samp:`Machine_Attribute` pragma, on
52 specific subprograms and variables, or their types. (This attribute
53 always applies to a type, even when it is associated with a subprogram
54 or a variable.)
55
56 .. code-block:: ada
57
58 function Foo returns Integer;
59 pragma Machine_Attribute (Foo, "strub");
60 -- Foo and its callers are modified so as to scrub the stack
61 -- space used by Foo after it returns. Shorthand for:
62 -- pragma Machine_Attribute (Foo, "strub", "at-calls");
63
64 procedure Bar;
65 pragma Machine_Attribute (Bar, "strub", "internal");
66 -- Bar is turned into a wrapper for its original body,
67 -- and they scrub the stack used by the original body.
68
69 Var : Integer;
70 pragma Machine_Attribute (Var, "strub");
71 -- Reading from Var in a subprogram enables stack scrubbing
72 -- of the stack space used by the subprogram. Furthermore, if
73 -- Var is declared within a subprogram, this also enables
74 -- scrubbing of the stack space used by that subprogram.
75
76
77 Given these declarations, Foo has its type and body modified as
78 follows:
79
80 .. code-block:: ada
81
82 function Foo (<WaterMark> : in out System.Address) returns Integer
83 is
84 -- ...
85 begin
86 <__strub_update> (<WaterMark>); -- Updates the stack WaterMark.
87 -- ...
88 end;
89
90
91 whereas its callers are modified from:
92
93 .. code-block:: ada
94
95 X := Foo;
96
97 to:
98
99 .. code-block:: ada
100
101 declare
102 <WaterMark> : System.Address;
103 begin
104 <__strub_enter> (<WaterMark>); -- Initialize <WaterMark>.
105 X := Foo (<WaterMark>);
106 <__strub_leave> (<WaterMark>); -- Scrubs stack up to <WaterMark>.
107 end;
108
109
110 As for Bar, because it is strubbed in internal mode, its callers are
111 not modified. Its definition is modified roughly as follows:
112
113 .. code-block:: ada
114
115 procedure Bar is
116 <WaterMark> : System.Address;
117 procedure Strubbed_Bar (<WaterMark> : in out System.Address) is
118 begin
119 <__strub_update> (<WaterMark>); -- Updates the stack WaterMark.
120 -- original Bar body.
121 end Strubbed_Bar;
122 begin
123 <__strub_enter> (<WaterMark>); -- Initialize <WaterMark>.
124 Strubbed_Bar (<WaterMark>);
125 <__strub_leave> (<WaterMark>); -- Scrubs stack up to <WaterMark>.
126 end Bar;
127
128
129 There are also :switch:`-fstrub={choice}` command-line options to
130 control default settings. For usage and more details on the
131 command-line options, on the ``strub`` attribute, and their use with
132 other programming languages, see :title:`Using the GNU Compiler
133 Collection (GCC)`.
134
135 Note that Ada secondary stacks are not scrubbed. The restriction
136 ``No_Secondary_Stack`` avoids their use, and thus their accidental
137 preservation of data that should be scrubbed.
138
139 Attributes ``Access`` and ``Unconstrained_Access`` of variables and
140 constants with ``strub`` enabled require types with ``strub`` enabled;
141 there is no way to express an access-to-strub type otherwise.
142 ``Unchecked_Access`` bypasses this constraint, but the resulting
143 access type designates a non-strub type.
144
145 .. code-block:: ada
146
147 VI : aliased Integer;
148 pragma Machine_Attribute (VI, "strub");
149 XsVI : access Integer := VI'Access; -- Error.
150 UXsVI : access Integer := VI'Unchecked_Access; -- OK,
151 -- UXsVI does *not* enable strub in subprograms that
152 -- dereference it to obtain the UXsVI.all value.
153
154 type Strub_Int is new Integer;
155 pragma Machine_Attribute (Strub_Int, "strub");
156 VSI : aliased Strub_Int;
157 XsVSI : access Strub_Int := VSI'Access; -- OK,
158 -- VSI and XsVSI.all both enable strub in subprograms that
159 -- read their values.
160
161
162 Every access-to-subprogram type, renaming, and overriding and
163 overridden dispatching operations that may refer to a subprogram with
164 an attribute-modified interface must be annotated with the same
165 interface-modifying attribute. Access-to-subprogram types can be
166 explicitly converted to different strub modes, as long as they are
167 interface-compatible (i.e., adding or removing ``at-calls`` is not
168 allowed). For example, a ``strub``-``disabled`` subprogram can be
169 turned ``callable`` through such an explicit conversion:
170
171 .. code-block:: ada
172
173 type TBar is access procedure;
174
175 type TBar_Callable is access procedure;
176 pragma Machine_Attribute (TBar_Callable, "strub", "callable");
177 -- The attribute modifies the procedure type, rather than the
178 -- access type, because of the extra argument after "strub",
179 -- only applicable to subprogram types.
180
181 Bar_Callable_Ptr : constant TBar_Callable
182 := TBar_Callable (TBar'(Bar'Access));
183
184 procedure Bar_Callable renames Bar_Callable_Ptr.all;
185 pragma Machine_Attribute (Bar_Callable, "strub", "callable");
186
187
188 Note that the renaming declaration is expanded to a full subprogram
189 body, it won't be just an alias. Only if it is inlined will it be as
190 efficient as a call by dereferencing the access-to-subprogram constant
191 Bar_Callable_Ptr.
192
193
194 .. Hardened Conditionals:
195
196 Hardened Conditionals
197 =====================
198
199 GNAT can harden conditionals to protect against control-flow attacks.
200
201 This is accomplished by two complementary transformations, each
202 activated by a separate command-line option.
203
204 The option :switch:`-fharden-compares` enables hardening of compares
205 that compute results stored in variables, adding verification that the
206 reversed compare yields the opposite result, turning:
207
208 .. code-block:: ada
209
210 B := X = Y;
211
212
213 into:
214
215 .. code-block:: ada
216
217 B := X = Y;
218 declare
219 NotB : Boolean := X /= Y; -- Computed independently of B.
220 begin
221 if B = NotB then
222 <__builtin_trap>;
223 end if;
224 end;
225
226
227 The option :switch:`-fharden-conditional-branches` enables hardening
228 of compares that guard conditional branches, adding verification of
229 the reversed compare to both execution paths, turning:
230
231 .. code-block:: ada
232
233 if X = Y then
234 X := Z + 1;
235 else
236 Y := Z - 1;
237 end if;
238
239
240 into:
241
242 .. code-block:: ada
243
244 if X = Y then
245 if X /= Y then -- Computed independently of X = Y.
246 <__builtin_trap>;
247 end if;
248 X := Z + 1;
249 else
250 if X /= Y then -- Computed independently of X = Y.
251 null;
252 else
253 <__builtin_trap>;
254 end if;
255 Y := Z - 1;
256 end if;
257
258
259 These transformations are introduced late in the compilation pipeline,
260 long after boolean expressions are decomposed into separate compares,
261 each one turned into either a conditional branch or a compare whose
262 result is stored in a boolean variable or temporary. Compiler
263 optimizations, if enabled, may also turn conditional branches into
264 stored compares, and vice-versa, or into operations with implied
265 conditionals (e.g. MIN and MAX). Conditionals may also be optimized
266 out entirely, if their value can be determined at compile time, and
267 occasionally multiple compares can be combined into one.
268
269 It is thus difficult to predict which of these two options will affect
270 a specific compare operation expressed in source code. Using both
271 options ensures that every compare that is neither optimized out nor
272 optimized into implied conditionals will be hardened.
273
274 The addition of reversed compares can be observed by enabling the dump
275 files of the corresponding passes, through command-line options
276 :switch:`-fdump-tree-hardcmp` and :switch:`-fdump-tree-hardcbr`,
277 respectively.
278
279 They are separate options, however, because of the significantly
280 different performance impact of the hardening transformations.
281
282 For usage and more details on the command-line options, see
283 :title:`Using the GNU Compiler Collection (GCC)`. These options can
284 be used with other programming languages supported by GCC.
285
286
287 .. Hardened Booleans:
288
289 Hardened Booleans
290 =================
291
292 Ada has built-in support for introducing boolean types with
293 alternative representations, using representation clauses:
294
295 .. code-block:: ada
296
297 type HBool is new Boolean;
298 for HBool use (16#5a#, 16#a5#);
299 for HBool'Size use 8;
300
301
302 When validity checking is enabled, the compiler will check that
303 variables of such types hold values corresponding to the selected
304 representations.
305
306 There are multiple strategies for where to introduce validity checking
307 (see :switch:`-gnatV` options). Their goal is to guard against
308 various kinds of programming errors, and GNAT strives to omit checks
309 when program logic rules out an invalid value, and optimizers may
310 further remove checks found to be redundant.
311
312 For additional hardening, the ``hardbool`` :samp:`Machine_Attribute`
313 pragma can be used to annotate boolean types with representation
314 clauses, so that expressions of such types used as conditions are
315 checked even when compiling with :switch:`-gnatVT`:
316
317 .. code-block:: ada
318
319 pragma Machine_Attribute (HBool, "hardbool");
320
321 function To_Boolean (X : HBool) returns Boolean is (Boolean (X));
322
323
324 is compiled roughly like:
325
326 .. code-block:: ada
327
328 function To_Boolean (X : HBool) returns Boolean is
329 begin
330 if X not in True | False then
331 raise Constraint_Error;
332 elsif X in True then
333 return True;
334 else
335 return False;
336 end if;
337 end To_Boolean;
338
339
340 Note that :switch:`-gnatVn` will disable even ``hardbool`` testing.
341
342 Analogous behavior is available as a GCC extension to the C and
343 Objective C programming languages, through the ``hardbool`` attribute,
344 with the difference that, instead of raising a Constraint_Error
345 exception, when a hardened boolean variable is found to hold a value
346 that stands for neither True nor False, the program traps. For usage
347 and more details on that attribute, see :title:`Using the GNU Compiler
348 Collection (GCC)`.
349
350
351 .. Control Flow Redundancy:
352
353 Control Flow Redundancy
354 =======================
355
356 GNAT can guard against unexpected execution flows, such as branching
357 into the middle of subprograms, as in Return Oriented Programming
358 exploits.
359
360 In units compiled with :switch:`-fharden-control-flow-redundancy`,
361 subprograms are instrumented so that, every time they are called,
362 basic blocks take note as control flows through them, and, before
363 returning, subprograms verify that the taken notes are consistent with
364 the control-flow graph.
365
366 Functions with too many basic blocks, or with multiple return points,
367 call a run-time function to perform the verification. Other functions
368 perform the verification inline before returning.
369
370 Optimizing the inlined verification can be quite time consuming, so
371 the default upper limit for the inline mode is set at 16 blocks.
372 Command-line option :switch:`--param hardcfr-max-inline-blocks=` can
373 override it.
374
375 Even though typically sparse control-flow graphs exhibit run-time
376 verification time nearly proportional to the block count of a
377 subprogram, it may become very significant for generated subprograms
378 with thousands of blocks. Command-line option
379 :switch:`--param hardcfr-max-blocks=` can set an upper limit for
380 instrumentation.
381
382 For each block that is marked as visited, the mechanism checks that at
383 least one of its predecessors, and at least one of its successors, are
384 also marked as visited.
385
386 Verification is performed just before a subprogram returns. The
387 following fragment:
388
389 .. code-block:: ada
390
391 if X then
392 Y := F (Z);
393 return;
394 end if;
395
396
397 gets turned into:
398
399 .. code-block:: ada
400
401 type Visited_Bitmap is array (1..N) of Boolean with Pack;
402 Visited : aliased Visited_Bitmap := (others => False);
403 -- Bitmap of visited blocks. N is the basic block count.
404 [...]
405 -- Basic block #I
406 Visited(I) := True;
407 if X then
408 -- Basic block #J
409 Visited(J) := True;
410 Y := F (Z);
411 CFR.Check (N, Visited'Access, CFG'Access);
412 -- CFR is a hypothetical package whose Check procedure calls
413 -- libgcc's __hardcfr_check, that traps if the Visited bitmap
414 -- does not hold a valid path in CFG, the run-time
415 -- representation of the control flow graph in the enclosing
416 -- subprogram.
417 return;
418 end if;
419 -- Basic block #K
420 Visited(K) := True;
421
422
423 Verification would also be performed before tail calls, if any
424 front-ends marked them as mandatory or desirable, but none do.
425 Regular calls are optimized into tail calls too late for this
426 transformation to act on it.
427
428 In order to avoid adding verification after potential tail calls,
429 which would prevent tail-call optimization, we recognize returning
430 calls, i.e., calls whose result, if any, is returned by the calling
431 subprogram to its caller immediately after the call returns.
432 Verification is performed before such calls, whether or not they are
433 ultimately optimized to tail calls. This behavior is enabled by
434 default whenever sibcall optimization is enabled (see
435 :switch:`-foptimize-sibling-calls`); it may be disabled with
436 :switch:`-fno-hardcfr-check-returning-calls`, or enabled with
437 :switch:`-fhardcfr-check-returning-calls`, regardless of the
438 optimization, but the lack of other optimizations may prevent calls
439 from being recognized as returning calls:
440
441 .. code-block:: ada
442
443 -- CFR.Check here, with -fhardcfr-check-returning-calls.
444 P (X);
445 -- CFR.Check here, with -fno-hardcfr-check-returning-calls.
446 return;
447
448 or:
449
450 .. code-block:: ada
451
452 -- CFR.Check here, with -fhardcfr-check-returning-calls.
453 R := F (X);
454 -- CFR.Check here, with -fno-hardcfr-check-returning-calls.
455 return R;
456
457
458 Any subprogram from which an exception may escape, i.e., that may
459 raise or propagate an exception that isn't handled internally, is
460 conceptually enclosed by a cleanup handler that performs verification,
461 unless this is disabled with :switch:`-fno-hardcfr-check-exceptions`.
462 With this feature enabled, a subprogram body containing:
463
464 .. code-block:: ada
465
466 -- ...
467 Y := F (X); -- May raise exceptions.
468 -- ...
469 raise E; -- Not handled internally.
470 -- ...
471
472
473 gets modified as follows:
474
475 .. code-block:: ada
476
477 begin
478 -- ...
479 Y := F (X); -- May raise exceptions.
480 -- ...
481 raise E; -- Not handled internally.
482 -- ...
483 exception
484 when others =>
485 CFR.Check (N, Visited'Access, CFG'Access);
486 raise;
487 end;
488
489
490 Verification may also be performed before No_Return calls, whether
491 only nothrow ones, with
492 :switch:`-fhardcfr-check-noreturn-calls=nothrow`, or all of them, with
493 :switch:`-fhardcfr-check-noreturn-calls=always`. The default is
494 :switch:`-fhardcfr-check-noreturn-calls=never` for this feature, that
495 disables checking before No_Return calls.
496
497 When a No_Return call returns control to its caller through an
498 exception, verification may have already been performed before the
499 call, if :switch:`-fhardcfr-check-noreturn-calls=always` is in effect.
500 The compiler arranges for already-checked No_Return calls without a
501 preexisting handler to bypass the implicitly-added cleanup handler and
502 thus the redundant check, but a local exception or cleanup handler, if
503 present, will modify the set of visited blocks, and checking will take
504 place again when the caller reaches the next verification point,
505 whether it is a return or reraise statement after the exception is
506 otherwise handled, or even another No_Return call.
507
508 The instrumentation for hardening with control flow redundancy can be
509 observed in dump files generated by the command-line option
510 :switch:`-fdump-tree-hardcfr`.
511
512 For more details on the control flow redundancy command-line options,
513 see :title:`Using the GNU Compiler Collection (GCC)`. These options
514 can be used with other programming languages supported by GCC.