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