Docsity

Verifying High-Performance Cryptographic Assembly Code, Exams of Cryptography and System Security

Toggle sidebar
bg1
Vale: Verifying High-Performance Cryptographic Assembly Code
Barry Bond⋆, Chris Hawblitzel⋆, Manos Kapritsos†, K. Rustan M. Leino⋆, Jacob R. Lorch⋆,
Bryan Parno‡, Ashay Rane§, Srinath Setty⋆, Laure Thompson
⋆Microsoft Research †University of Michigan ‡Carnegie Mellon University
§The University of Texas at Austin Cornell University
Abstract
High-performance cryptographic code often relies on
complex hand-tuned assembly language that is cus-
tomized for individual hardware platforms. Such code
is difficult to understand or analyze. We introduce a new
programming language and tool called Vale that supports
flexible, automated verification of high-performance as-
sembly code. The Vale tool transforms annotated assem-
bly language into an abstract syntax tree (AST), while
also generating proofs about the AST that are verified via
an SMT solver. Since the AST is a first-class proof term,
it can be further analyzed and manipulated by proven-
correct code before being extracted into standard assem-
bly. For example, we have developed a novel, proven-
correct taint-analysis engine that verifies the code’s free-
dom from digital side channels. Using these tools, we
verify the correctness, safety, and security of implemen-
tations of SHA-256 on x86 and ARM, Poly1305 on x64,
and hardware-accelerated AES-CBC on x86. Several im-
plementations meet or beat the performance of unverified,
state-of-the-art cryptographic libraries.
1 Introduction
The security of the Internet rests on the correctness of the
cryptographic code used by popular TLS/SSL implemen-
tations such as OpenSSL [
61
]. Because this cryptographic
code is critical to TLS performance, implementations of-
ten use hand-tuned assembly, or even a mix of assembly,
C preprocessor macros, and Perl scripts. For example, the
Perl subroutine in Figure 1 generates optimized ARM
code for OpenSSL’s SHA-256 inner loop.
Unfortunately, while the flexibility of script-generated
assembly leads to excellent performance (§5.1) and helps
support dozens of different platforms, it makes the cryp-
tographic code difficult to read, understand, or analyze. It
also makes the cryptographic code more prone to inadver-
tent bugs or maliciously inserted backdoors. For instance,
in less than a month last year, three separate bugs were
found just in OpenSSL’s assembly implementation of the
MAC algorithm Poly1305 [64–66].
Since cryptographic code is so critical for security,
we argue that it ought to be verifiably correct, safe, and
leakage-free.
sub BODY_00_15 {
my ($i,$a,$b,$c,$d,$e,$f,$g,$h)=@_;
$code.=<<___ if ($i<16);
#if __ARM_ARCH__>=7
@ ldr $t1,[$inp],#4@$i
# if $i==15
str $inp,[sp,#17*4]@ make room for $t4
# endif
eor $t0,$e,$e,ror#‘$Sigma1[1]-$Sigma1[0]‘
add $a,$a,$t2 @ h+=Maj(a,b,c) from the past
eor $t0,$t0,$e,ror#‘$Sigma1[2]-$Sigma1[0]‘@Sigma1(e)
# ifndef __ARMEB__
rev $t1,$t1
# endif
#else
@ ldrb $t1,[$inp,#3]@$i
add $a,$a,$t2 @ h+=Maj(a,b,c) from the past
ldrb $t2,[$inp,#2]
ldrb $t0,[$inp,#1]
orr $t1,$t1,$t2,lsl#8
ldrb $t2,[$inp],#4
orr $t1,$t1,$t0,lsl#16
# if $i==15
str $inp,[sp,#17*4]@ make room for $t4
# endif
eor $t0,$e,$e,ror#‘$Sigma1[1]-$Sigma1[0]‘
orr $t1,$t1,$t2,lsl#24
eor $t0,$t0,$e,ror#‘$Sigma1[2]-$Sigma1[0]‘@Sigma1(e)
#endif
FIGURE 1—
Snippet of a SHA-256 code-generating Perl script
from OpenSSL, with spacing adjusted to fit in one column.
§4.1 helps decode and explain the motivations for this style.
Existing approaches to verifying assembly code fall
roughly into two camps. On one side, frameworks like
Bedrock [
19
], CertiKOS [
23
], and x86proved [
42
] are
built on very expressive higher-order logical frameworks
like Coq [
22
]. This allows great flexibility in how the
assembly is generated and verified, as well as high as-
surance that the verification matches the semantics of
the assembly language. On the other side, systems like
BoogieX86 [
37
,
77
], VCC [
56
], and various assembly lan-
guage analysis tools [
9
] are built on satisfiability-modulo-
theories (SMT) solvers like Z3 [
25
]. Such solvers can
potentially blast their way through large blocks of as-
sembly and tricky bitwise reasoning, making verification
faster and easier.
In this paper, we present Vale, a new language for ex-
pressing and verifying high-performance assembly code
that strives to combine the advantages of both approaches;
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download Verifying High-Performance Cryptographic Assembly Code and more Exams Cryptography and System Security in PDF only on Docsity!

Vale: Verifying High-Performance Cryptographic Assembly Code

Barry Bond⋆, Chris Hawblitzel⋆, Manos Kapritsos†, K. Rustan M. Leino⋆, Jacob R. Lorch⋆,

Bryan Parno‡, Ashay Rane§, Srinath Setty⋆, Laure Thompson¶

⋆ Microsoft Research † University of Michigan ‡ Carnegie Mellon University

§ The University of Texas at Austin ¶ Cornell University

Abstract

High-performance cryptographic code often relies on complex hand-tuned assembly language that is cus- tomized for individual hardware platforms. Such code is difficult to understand or analyze. We introduce a new programming language and tool called Vale that supports flexible, automated verification of high-performance as- sembly code. The Vale tool transforms annotated assem- bly language into an abstract syntax tree (AST), while also generating proofs about the AST that are verified via an SMT solver. Since the AST is a first-class proof term, it can be further analyzed and manipulated by proven- correct code before being extracted into standard assem- bly. For example, we have developed a novel, proven- correct taint-analysis engine that verifies the code’s free- dom from digital side channels. Using these tools, we verify the correctness, safety, and security of implemen- tations of SHA-256 on x86 and ARM, Poly1305 on x64, and hardware-accelerated AES-CBC on x86. Several im- plementations meet or beat the performance of unverified, state-of-the-art cryptographic libraries.

1 Introduction

The security of the Internet rests on the correctness of the cryptographic code used by popular TLS/SSL implemen- tations such as OpenSSL [ 61 ]. Because this cryptographic code is critical to TLS performance, implementations of- ten use hand-tuned assembly, or even a mix of assembly, C preprocessor macros, and Perl scripts. For example, the Perl subroutine in Figure 1 generates optimized ARM code for OpenSSL’s SHA-256 inner loop. Unfortunately, while the flexibility of script-generated assembly leads to excellent performance (§5.1) and helps support dozens of different platforms, it makes the cryp- tographic code difficult to read, understand, or analyze. It also makes the cryptographic code more prone to inadver- tent bugs or maliciously inserted backdoors. For instance, in less than a month last year, three separate bugs were found just in OpenSSL’s assembly implementation of the MAC algorithm Poly1305 [64–66]. Since cryptographic code is so critical for security, we argue that it ought to be verifiably correct, safe, and leakage-free.

sub BODY_00_15 { my ($i,$a,$b,$c,$d,$e,$f,$g,$h) = @; $code.=<<__ if ($i<16); #if ARM_ARCH>= @ ldr $t1,[$inp],# 4 @ $i

if $i==

str $inp,[sp,#17*4] @ make room for $t

endif

eor $t0,$e,$e,ror#‘$Sigma1[1]-$Sigma1[0]‘ add $a,$a,$t2 @ h+=Maj(a,b,c) from the past eor $t0,$t0,$e,ror#‘$Sigma1[2]-$Sigma1[0]‘@Sigma1(e)

ifndef ARMEB

rev $t1,$t

endif

#else @ ldrb $t1,[$inp,#3] @ $i add $a,$a,$t2 @ h+=Maj(a,b,c) from the past ldrb $t2,[$inp,#2] ldrb $t0,[$inp,#1] orr $t1,$t1,$t2,lsl# 8 ldrb $t2,[$inp],# 4 orr $t1,$t1,$t0,lsl# 16

if $i==

str $inp,[sp,#17*4] @ make room for $t

endif

eor $t0,$e,$e,ror#‘$Sigma1[1]-$Sigma1[0]‘ orr $t1,$t1,$t2,lsl# 24 eor $t0,$t0,$e,ror#‘$Sigma1[2]-$Sigma1[0]‘@Sigma1(e) #endif FIGURE 1—Snippet of a SHA-256 code-generating Perl script from OpenSSL, with spacing adjusted to fit in one column. §4.1 helps decode and explain the motivations for this style.

Existing approaches to verifying assembly code fall roughly into two camps. On one side, frameworks like Bedrock [ 19 ], CertiKOS [ 23 ], and x86proved [ 42 ] are built on very expressive higher-order logical frameworks like Coq [ 22 ]. This allows great flexibility in how the assembly is generated and verified, as well as high as- surance that the verification matches the semantics of the assembly language. On the other side, systems like BoogieX86 [ 37 , 77 ], VCC [ 56 ], and various assembly lan- guage analysis tools [ 9 ] are built on satisfiability-modulo- theories (SMT) solvers like Z3 [ 25 ]. Such solvers can potentially blast their way through large blocks of as- sembly and tricky bitwise reasoning, making verification faster and easier. In this paper, we present Vale, a new language for ex- pressing and verifying high-performance assembly code that strives to combine the advantages of both approaches;

untrusted

trusted

hand-written libraries (Dafny)

masm code

Information Leakage Analyzer

Vale tool

Dafny/Z Verifier

verified

Cryptographic code (Vale)

generated proofs (Dafny)

generated code AST (Dafny)

Assembler

Assembly printer

yes no

yes no

crypto spec (Dafny)

semantics

machine (Dafny)

FIGURE 2—Verifying cryptographic code with Vale and Dafny.

i.e., it combines flexible generation of high-performance assembly with automated, rigorous, machine-checked ver- ification. For any assembly program written in Vale, the Vale tool constructs an abstract syntax tree (AST) rep- resenting the program’s code, and produces a proof that this AST obeys a desired specification for any possible evaluation of the code (Figure 2). The specification, the AST, and the proofs are currently expressed in Dafny [ 50 ], an off-the-shelf logical framework supporting SMT-based verification, higher-order reasoning, datatypes, functions, lemmas, and extraction of executable code. Dafny uses Z3 to verify the proofs generated by Vale. After verification, the AST is available in the logical framework for further analysis and manipulation. As a powerful example of this post-analysis, we have devel- oped a verified analyzer that checks Vale ASTs for po- tential information leakage through timing and memory- access channels. Although we trust our crypto specs, Dafny, and the assembly language semantics to be correct, as shown in Figure 2, neither Vale nor the information leakage ana- lyzer is part of the trusted computing base. The former merely produces ASTs and proofs that are then checked against trusted specifications by Dafny; the latter is writ- ten directly in Dafny and verified once and for all to be correct for all possible ASTs. Working directly on as- sembly language means we trust an assembler but not a higher-level compiler, so we need not worry about com- pilers that introduce information leaks into cryptographic code [43].

Contributions In summary, this paper makes the follow- ing contributions.

  • The design and implementation of Vale (§2), which combines flexible generation of high-performance assembly with automated machine-checked verifica- tion. - A machine-verified analyzer that checks verified Vale programs for side channels based on a novel combination of dataflow analysis and Hoare-style proofs (§3). - A series of case studies applying Vale to standard algorithms like Poly1305, AES, and SHA on x86, x64, and ARM platforms with support for both the GNU assembler and MASM (§4). They show that Vale is flexible enough to express and verify even highly scripted code generation like that in Figure 1. In particular, it replaces the use of chaotic Perl scripts with a principled approach based on verification and partial evaluation. - An evaluation demonstrating that, because Vale can match the expressiveness of OpenSSL’s code- generation techniques, the verified assembly code generated by Vale can match the performance of highly-optimized implementations like OpenSSL (§5). Hence, verification does not require compro- mising on performance. We believe that Vale is the first system to demonstrate formally verified assem- bly language cryptographic code whose performance matches that of comparable OpenSSL code. All Vale code and case studies are available on GitHub at https://github.com/project-everest/vale.

2 Vale Design and Implementation

Vale is currently targeted towards verifying cryptographic assembly language code, which tends to have simple struc- tured control flow and heavy inlining. Therefore, the Vale language includes control constructs such as inline pro- cedures, conditionals, and loops. Note that these control constructs are independent of any particular features in the underlying logical framework. For example, even when using Dafny as a logical framework, Vale procedures are not executable Dafny methods, Vale while loops are not executable Dafny while loops, and executable Vale code is not compiled with Dafny’s compiler, which compiles Dafny’s own control constructs to C#. Instead, Vale relies on the logical framework mainly for mathematical reason- ing in proofs, and uses executable Dafny code only for specialized tasks like printing assembly language code and static analysis of Vale code. The Vale language does not contain anything specific to a particular architecture such as x86 or ARM or to a par- ticular assembler such as the GNU assembler or MASM. Instead, programmers write Dafny code that defines the syntax and semantics for the architecture of their choice, then use Vale to manipulate the syntax and semantics. §2. introduces examples of such Dafny declarations. §2.2 and §2.3 then present Vale code, demonstrating the flexibility and expressiveness of the Vale language. §2.4 describes how Vale generates Dafny proofs that make the best use of Dafny and Z3. Finally, §2.5 describes how Vale handles

modifies clauses). The effect on the state is expressed using preconditions (requires clauses) and postcondi- tions (ensures clauses). The Add3ToR7 procedure, for example, promises to add three to register r7 under the condition that the initial value or r7 isn’t so big that adding three would cause overflow.

var{:state ok()} ok:bool; var{:state reg(R0)} r0:uint32; var{:state reg(R1)} r1:uint32; ... var{:state reg(R12)} r12:uint32; var{:state reg(LR)} lr:uint32; var{:state mem()} mem:map(int, uint32);

procedure AddOne(inout operand r:uint32) requires r < 0xffffffff; ensures r == old(r) + 1; { ADD(r, r, 1); }

procedure Add3ToR7() modifies r7; requires r7 < 0xfffffffd; ensures r7 == old(r7) + 3; { AddOne(r7); AddOne(r7); AddOne(r7); }

FIGURE 5—Examples of state declarations and inline proce- dure declarations in Vale.

In addition to preconditions and postconditions, Vale also requires loop invariants for loops:

while (r7 <= 100) // example loop in Vale invariant r7 <= 103; // loop invariant { Add3ToR7(); }

For each procedure, the Vale tool generates a Dafny function that produces an AST value of type code. For ex- ample, for the code in Figure 5, it generates the following Dafny code: function method{:opaque} code_AddOne(r:op):code { Block(cons(code_ADD(r, r, op_const(1)), nil())) } function method{:opaque} code_Add3ToR7():code { Block(cons(code_AddOne(op_reg(R7)), cons(code_AddOne(op_reg(R7)), cons(code_AddOne(op_reg(R7)), nil())))) }

Here, function method is Dafny’s syntax for a func- tion whose code can be extracted and executed. Both Vale and Dafny use the syntax {:...} for attributes. The opaque attribute indicates that the function definition will be hidden during proofs except where explicitly revealed.

procedure{:instruction Ins(Add(dst,src1,src2))} ADDW(out operand dst:uint32, operand src1:uint32, operand src2:uint32) ensures dst == (src1 + src2) % 0x100000000;

procedure{:instruction Ins(Add(dst,src1,src2))} ADD(out operand dst:uint32, operand src1:uint32, operand src2:uint32) requires 0 <= src1 + src2 < 0x100000000; ensures dst == src1 + src2;

procedure{:instruction Ins(Ldr(dst,base,offset))} LDR(out operand dst:uint32, operand base:uint32, operand offset:uint32) reads mem; requires InMem(base + offset, mem); ensures dst == mem[base + offset];

procedure{:instruction Ins(Str(src,base,offset))} STR(operand src:uint32, operand base:uint32, operand offset:uint32) modifies mem; requires InMem(base + offset, mem); ensures mem == old(mem)[base + offset := src]; FIGURE 6—Example Vale instruction declarations, including two for the same instruction: both a wrapping (ADDW) and non- wrapping (ADD) specification of the Add instruction.

The leaves of the AST are the individual instructions declared in Figure 3. Programmers declare instructions as Vale procedures with specifications of their choice. They must prove that the specifications are sound with respect to the semantics given by evalCode, so these specifications do not have to be trusted. Multiple procedures with different specifications may be given for the same instruction if different specifications will be more convenient in different situations. For ex- ample, the ADDW (wrapping add) and ADD (non-wrapping add) procedures in Figure 6 both have the same body, a single Add instruction. However, ADD restricts its input operands so it can provide a simpler postcondition that need not consider the consequences of overflow. This hiding often makes code easier to verify in cases when wrapping is not intended. The generation of first-class AST values allows pro- grammers to customize the analysis and processing of assembly language code. For example, the PrintCode method in Figure 3 can be customized to print assem- bly language in various formats; our current PrintCode emits either GNU assembler or MASM assembly code, depending on a command-line argument. This makes Vale more flexible than tools like BoogieX86 [ 77 ] and VCC [ 56 ] that hard-wire the generation of assembly language output. Indeed, Vale initially only supported MASM output, but adding support for the GNU assem- bler took less than two hours. §3 pushes this flexibility even further, implementing an entire verified information leakage analysis with no modifications to Vale.

procedure ReadA(ghost a:seq(uint32),inline b:bool) reads r0; mem; modifies r1; requires length(a) >= 3; a[0] <= 100; a[1] <= 100; forall i :: 0 <= i < length(a) ==> InMem(r0 + 4 * i, mem) && mem[r0 + 4 * i] == a[i]; ensures b ==> r1 == a[0] + 1; !b ==> r1 == a[1] + 1; { inline if (b) { LDR(r1, r0, 0); //load memory [r0+0] into r AddOne(r1); } else { LDR(r1, r0, 4); //load memory [r0+4] into r AddOne(r1); } } procedure{:recursive} AddNToR7(inline n:nat) modifies r7; requires r7 + n <= 0xffffffff; ensures r7 == old(r7) + n; { inline if (n > 0) { AddOne(r7); AddNToR7(n - 1); } } FIGURE 7—Ghost and inline parameters in Vale.

2.3 Operands, ghost variables, and inline variables

Parameters to procedures may be operands, ghost vari- ables, or inline variables. The AddOne procedure in Fig- ure 5, for example, takes an operand r as a parameter. Operands are marked as in, out, or inout to indicate whether the operand is read, written, or both, where in is the default. These labels are used in place of reads and modifies clauses. Register and CISC-style mem- ory operands may be read and/or written, while constant operands may only be read. Ghost parameters may be used to make specifications about the state easier to express. For example, the ReadA procedure in Figure 7 uses a ghost parameter a to help express the memory pointed to by register r0. In this case, each 4-byte word of the memory contains one element of the sequence a. Ghost parameters are used in the proofs (but not the ASTs) that Vale generates. Inline parameters, on the other hand, do appear in the ASTs and may be used to specialize the generated code before passing it to PrintCode, as seen in Figure 7. The ReadA procedure uses an inline bool to generate code to load from r0 + 0 if b = true, and to load from r0 + 4 if b = false. The AddNToR7 procedure uses an inline natural number n to repeat the AddOne instruction n times, generating a completely unrolled loop. From these, Vale generates functions parameterized

function method{:opaque} code_ReadA(b:bool):code { Block(cons(( if b then Block(cons(code_LDR( op_reg(R1), op_reg(R0), op_const(0)) ... else ... ))) } function method{:opaque} code_AddNToR7(n:nat):code { Block(cons(( if (n > 0) then Block(cons( code_AddOne(sp_op_reg(R7)) ... else ...))) } FIGURE 8—Dafny code that generates varying assembly code.

over the inline b and n variables, so that each b and n produces a possibly different AST (see Figure 8). In these functions, inline if statements turn into conditional expressions that generate different code for different in- line variable assignments, in contrast to ordinary if state- ments that turn into IfElse nodes in the AST. Neverthe- less, the proofs generated by Vale verify the correctness of the procedures for all possible b and n. From the proof’s perspective, inline variables are no different from ordi- nary variables and inline if statements are no different from traditional if statements. The proofs are checked before picking particular b and n values to generate and print the code. This may be thought of as a simple form of partial evaluation, analogous to systems like MetaML [ 73 ] that type-check a program before partially evaluating it. This sort of partial evaluation provides a principled re- placement for Perl scripts and ifdefs; §4.1 describes how these features are used to express and verify the code in Figure 1.

2.4 Vale proofs Although Vale ultimately proves properties in terms of the underlying machine semantics, it still structures its proofs to take advantage of the automated SMT-based reasoning provided by Dafny and Z3. For each procedure p, the Vale tool generates a Dafny lemma which proves that if p’s preconditions hold then it does not crash and its postcon- ditions hold. A Dafny lemma is quite similar to a Dafny method: the desired property is declared as the postcon- dition (i.e., via ensures clauses) and proof assumptions are declared as preconditions (i.e., via requires clauses). In its simplest form, a Vale proof looks much like the as- sertion in Figure 4; i.e., it consists of a Dafny lemma

  • taking an initial state s1 and a final state s2 as pa- rameters,
  • requiring evalCode(p.code, s1, s2),
  • requiring s1.ok,
  • requiring that all of p’s preconditions hold for s1,

3.1 Specifying leakage freedom

Below, we first provide some intuition for what it means for a method to be leakage free. We then conclude the section with our formal definition of leakage freedom, a definition based on non-interference [34].

Secret inputs. A method is leakage free if it does not leak secret inputs to an adversary. Thus, part of the specifica- tion of leakage freedom is a specification of which inputs are secret. To be conservative, we have the programmer specify the opposite: the set of locations PubStartLocs she is sure contain non-secret information. We then treat all other locations as containing secrets.

State leakage. Secrets leak when they can be deduced from architectural state visible to the adversary when the method terminates. Thus, part of the specification of leakage freedom is a specification of which outputs are visible to the adversary. For this, we have the programmer specify a set of locations PubEndLocs that are visible to the adversary upon method termination. To prove leak- age freedom, we must prove that these locations’ final contents do not depend on secrets. The programmer may omit from PubEndLocs any lo- cations whose final contents are fully determined by the functional-correctness specification. One useful applica- tion of this principle is declassification; e.g., we leave the 32-byte hash computed by SHA-256 out of PubEndLocs since it is a fully specified function of the hash’s input. Another common application of this principle is framing, i.e., when the calling convention for a method specifies that it must leave a location unchanged. Since functional correctness prevents changes to the location, there is no need to check that location for leakage.

Cache-based side channels. As shown by Barthe et al., a program is free of cache-based side channels if it does not branch on secrets, and if it performs no secret- dependent memory accesses [ 12 ]. Thus, to prove freedom from cache-based side channels, it suffices to show that an execution trace, which records all branches and memory- access locations, does not depend on secret inputs. To enable machine-checked verification of cache-based side-channel freedom in Vale, we expand the architectural model of the state with an additional ghost field trace that represents the execution trace defined above. We also update our machine semantics to ensure the execution trace captures all branches and memory access locations. For instance, we ensure that a store instruction appends the accessed memory address to the execution trace.

Timing-based side channels. Closing cache-based side channels is an important step in closing timing-based side channels, but it is not sufficient. We must also show that inputs to any variable-latency instructions do not depend on secrets [ 69 ]. Thus, we update our machine

predicate isLeakageFree( code:code, pubStartLocs:set, pubEndLocs:set) { forall s, t, s’, t’ :: ( evalCode(code, s, s’) && evalCode(code, t, t’) && (forall loc :: loc in pubStartLocs ==> s[loc] == t[loc]) && s.trace == t.trace ) ==> ( s’.trace == t’.trace && (forall loc :: loc in pubEndLocs ==> s’[loc] == t’[loc]) ) } FIGURE 9—Correctness specification for leakage freedom.

semantics to also capture in trace all inputs to variable- latency instructions. This way, if we prove that the trace is independent of secrets then we also prove that the running time is independent of secrets. Attacker model. In summary, we model a strong at- tacker capable of fully observing detailed digital side channel information. We assume the attacker sees a full execution trace of our code, including each instruction executed, all memory locations each instruction accesses, and any other instruction inputs that can influence tim- ing. We also assume the attacker sees all architectural state resulting from running our code, except for locations where our specification explicitly says we store secrets (e.g., decrypted messages). Formal definition of leakage freedom. We now present a formal definition of leakage freedom; for its encoding in Dafny, see Figure 9. A Vale method with code Code is leakage free if, for any two successful runs of Code, the following two conditions:

  • the two initial states, s and t, match in every location in PubStartLocs; and
  • the execution traces in those initial states, s.trace and t.trace, are identical imply the following two outcomes:
  • the two final states, s’ and t’, match in every loca- tion in PubEndLocs; and
  • the execution traces in those final states are identical. This is an intuitive specification for leakage freedom: for any pair of executions of the program with the same public values but potentially different secrets, the timing and cache behavior of the program are the same in both executions. Hence, any adversary’s observations must be independent of the secret values. It is reasonable to only consider successful runs since our functional verification proves that the code always executes successfully.

3.2 Analyzer implementation Rather than directly proving that each Vale program sat- isfies our leakage specification, we invest in a one-time effort to write and prove correct a leakage analyzer that

can run on any Vale program. Our analyzer takes as input:

  • a Vale code value (§2) Code,
  • a set of locations (e.g., register names) PubStartLocs assumed to be free of secrets when the code begins, and
  • a set of locations PubEndLocs that must be free of secrets when the code ends. It outputs a Boolean LeakageFree indicating whether the code is leakage free under these conditions. The analyzer’s top-level specification states that the analysis is sound (though it may not be complete); i.e., when the analyzer claims that Code is leakage free, then it satisfies isLeakageFree (Figure 9). More formally, we prove that the analyzer satisfies the following postcondi- tion:

LeakageFree ⇒ isLeakageFree(Code, PubStartLocs, PubEndLocs).

We prove this correctness property via machine-checked proofs in Vale’s underlying logical framework Dafny [ 50 ]. The analyzer’s implementation is a straightforward flow-sensitive dataflow analysis [ 45 ] in the tradition of Denning et al. [ 27 ]. The main novelties are that we for- mally verify the implementation relative to a succinct correctness condition, and that we leverage the knowl- edge of aliasing present in the functional verification of the Vale programs, as described further in §3.3. The dataflow analysis checks the code one instruc- tion at a time, keeping track of the set of untainted lo- cations PubLocs. In other words, it maintains the invari- ant that each location in PubLocs contains only public information. Initially, it sets PubLocs to PubStartLocs. If at any point it concludes that the execution trace may depend on state outside of PubLocs, the analyzer returns False to indicate it cannot guarantee leakage freedom. This may happen if a branch predicate might use a loca- tion not in PubLocs, or a memory dereference might use the contents of a register not in PubLocs as its base ad- dress or offset. Loops are iterated until PubLocs reaches a fixed point. Taint values are chosen from a lattice of two elements (Public and Secret, with the partial order Secret > Public), which helps in conservatively merging taints. For instance, when the analysis merges taints for a given destination across multiple program paths (e.g., at the end of a loop), the analysis conservatively sets the destination’s taint to the least upper bound of the desti- nation’s taint across all paths. Similarly, if an instruction partially overwrites a destination, then the destination’s taint is chosen as the least upper bound of the destina- tion’s existing taint and the new taint. However, if an instruction completely overwrites a destination, then the destination’s taint is set to the new taint value. As a result, the taint of a destination (e.g. a register) can change be- tween Secret and Public many times during the analysis

of the program, thus affecting the size of the PubLocs set. If the analyzer reaches the end of Code, it returns True if PubEndLocs ⊆ PubLocs.

3.3 Memory taint analysis The main challenge for taint analysis is tracking the taint associated with memory locations. However, given our focus on proving functional correctness of cryptographic code, we observe that we can carefully leverage the work already done to prove functional correctness, to drastically simplify memory taint analysis. Memory taint analysis is challenging because typically one cannot simply look at an instruction and determine which memory address it will read or write: the effective address depends on the particular dynamic values in the registers used as the base and/or offset of the access. Thus, existing tools for analyzing leakage of assembly language code depend on alias analysis, which is often too con- servative to verify existing cryptographic code without making potentially unsound assumptions [9]. Our approach to memory taint analysis carefully lever- ages the work already done to prove functional correct- ness, since some of that work requires reasoning about the flow of information to and from memory. After all, a program cannot be correct unless it manages that flow correctly. For example, the developer cannot prove SHA- 256 correct without proving that the output hash buffer does not overlap the unprocessed input. We can push some of the work of memory taint analysis to the developer by relying on her to provide lightweight annotations in the code. In addition to specifying which addresses are expected to contain public information on entry and exit, she must make a similar annotation for each load and store. This annotation consists of a bit in- dicating whether she expects the instruction to access public or secret information. For CISC instructions where each operand may implicitly specify a load or store, she must annotate each such memory-accessing operand with a bit. Crucially, however, we do not rely on the correct- ness of these annotations for security. If the developer makes a mistake, it will be caught during either functional- correctness verification or during leakage analysis. These annotations make our analyzer’s handling of memory taint straightforward. The analyzer simply labels any value resulting from a load public or secret based on the load instruction’s annotation. The analyzer also checks, for each store annotated as public, that the value being stored is actually public. To ensure that annotation errors will be caught during functional correctness verification, we expand the archi- tectural model of the state with an additional ghost field pubaddrs, representing the set of addresses currently containing public information. A store adds its address to, or removes it from, pubaddrs, depending on whether the

To demonstrate that our implementation is not only correct but side-channel and leakage free, we run our ver- ified analysis tool (§3) on the Vale-generated AST. To our surprise (given that the code is a direct translation of OpenSSL’s implementation), the tool reports that the im- plementation is free of leakage via side channels, but not via state. Indeed, further investigation shows that while OpenSSL’s C implementation carefully scrubs its inter- mediate state, after OpenSSL’s assembly implementation returns, the stack still contains most of the caller’s reg- isters and 16 words from the expanded version of the final block of hash input. We do not know of an attack to exploit this leakage, but in general, leakage like this can undermine security [20]. Discussions with the OpenSSL security team indicate that while they aim to always scrub key material from memory, the remainder of their scrubbing efforts are ad hoc due to their unusual threat model [ 67 ]. On the one hand, OpenSSL usually runs in process with an applica- tion, and hence everything in the address space is trusted; nonetheless, they feel an instinctual need to scrub memory when they can do so without too much performance over- head. Because they do not have a precise and systematic way to identify “tainted” memory and scrub it efficiently, leaks like the one we identified are tolerated. In our case, the developers acknowledge the leak but have declined to change the code. Tools like Vale offer one approach to systematically track leakage and provably and efficiently block it. In- deed, after we add the appropriate stack scrubbing to our implementation, our analyzer confirms that it is free of both side channels and leakage.

4.2 SHA-256 on x

To demonstrate Vale’s generality across platforms, we have also used it to write an x86 version of SHA-256’s core. This required writing a trusted semantics for a sub- set of Intel’s architecture, a trusted printer to translate instructions into assembly code, and a verified proof li- brary (which in many cases differs very little from our corresponding ARM library). For the implementation, we wrote the code from scratch, rather than copying the algo- rithm from OpenSSL. At no point did we need to change Vale itself. One of the benefits of Vale’s platform generality is that we can write and use high-level lemmas that are platform-independent. We took advantage of this to reuse most of the lemmas from §4.1. For instance, our lemma lemma_SHA256TransitionOKAfterSettingAtoH es- tablishes that a certain step of the SHA-256 procedure has been followed correctly; we invoke this lemma from the ARM, x86, and x64 versions of SHA-256. We also lever- age Vale’s platform generality to reuse the specification for SHA-256 across all platforms.

When we run our verified analysis tool on our code, it confirms that it is leakage free.

4.3 Poly1305 on x We have also ported the 64-bit non-SIMD code for Poly1305 [ 14 ] from OpenSSL to Vale. OpenSSL’s Poly1305 is a mix of C and assembly language code. We began by writing a trusted semantics for a subset of x64. We then verify the OpenSSL assembly language code for the Poly1305 main loop and add our own initialization and finalization code in assembly language to replace the C code, resulting in a complete Vale implementation of Poly1305. Except for an extra instruction for the while- loop condition, our main loop code is identical to the OpenSSL code. This forces us to verify the mathematical tricks that underlie OpenSSL’s efficient 130-bit multipli- cation and mod implementations. For this verification, Z3’s automated reasoning about linear integer arithmetic is quite useful, helping us, for example, to maintain in- variants on the size of intermediate values that sometimes exceed 130 bits by various amounts. These invariants are crucial to establish that numbers are eventually reduced all the way to their 130-bit form and that enough carry bits are propagated through larger intermediate values. In fact, a bug fixed in March 2016 [ 65 ] was due to not propagat- ing carry bits through enough digits; Vale’s verification, of course, catches this bug.

4.4 AES-CBC using x86 AES-NI instructions Our final case study illustrates Vale’s ability to support complex, specialized instructions. Specifically, we have used Vale to implement the AES-128 CBC encryption mode using the AES-NI instructions provided by recent Intel CPUs [ 36 ]. AES is a block cipher that takes a fixed amount of plaintext; cipher-block chaining (CBC) is an encryption mode that applies AES repeatedly to encrypt an arbitrary amount of plaintext. In 2008, Intel introduced AES-NI instructions to both increase the performance of the core AES block cipher and make it easier to write side-channel free code, since software implementations of AES typically rely on in-memory lookup tables which are expensive to make side-channel free. As we quantify in §5.1, implementations that take advantage of this hard- ware support are easily 3.5–4.0× faster than traditional hand-tuned assembly that does not. For this case study, we extended our x86 model from §4.2 by adding support for 128-bit XMM registers, defi- nitions for Intel’s six AES-support instructions [ 35 ], and four generic XMM instructions [ 39 ]. None of these exten- sions requires changes to Vale. We also wrote a formal specification for AES-CBC based on the official FIPS specification [59]. Our implementation follows Intel’s recommendations for how to perform AES-128 [ 35 ]. However, unlike the

0

10

20

30

40

50

60

OpenSSL BoringSSL

Botan Crypto++^ libgcrypt mbedTLS

Hash time (usec)

FIGURE 10—Time for various libraries to compute the SHA- 256 hash of 10 KB of random data. Each data point averages 100 runs.

0

5

10

15

20

25

30

OpenSSL BoringSSL

Botan Crypto++^ libgcrypt mbedTLS

Time (usec)

Encrypt Decrypt

FIGURE 11—Time for various libraries to encrypt and decrypt 10 KB of random data using AES-CBC. Decryption is gener- ally faster because it is more parallelizable. Each data point averages 100 runs.

code provided by Intel, our code includes a proof of its correctness. We also run our verified analysis tool on the code to confirm that it is leakage free. The implementation involves an elaborate sequence of AES-NI instructions interwoven with generic XMM instructions. Proving it correct is non-trivial, particularly since Intel’s specifications for its instructions assume var- ious properties of the AES specification that we must prove. For example, we must prove that the AES RotWord step commutes with its SubWord step.

5 Evaluation

In our evaluation, we aim to answer two questions: (1) Can our verified code meet or exceed the perfor- mance of state-of-the-art unverified cryptographic li- braries? (2) How much time and effort is required to verify our cryptographic code?

5.1 Comparative performance To compare our performance to a state-of-the-art imple- mentation, we first measure the performance of six pop- ular cryptographic libraries: BoringSSL [ 1 ], Botan [ 2 ], Crypto++ [ 3 ], GNU libgcrypt [ 5 ], ARM mbedTLS (for- merly PolarSSL) [ 6 ], and OpenSSL [ 7 ]. We collect the measurements on a G5 Azure virtual machine running Ubuntu 16.04 on an Intel Xeon E5 v3 CPU and config- ured with enough dedicated CPUs to ensure sole tenancy. Each reported measurement is the average from 100 runs

0

5000

10000

15000

20000

25000

30000

16 64 256 1024 8192 16,

Throughput (KB/s)

Number of input bytes per SHA-256 hash

C ASM

FIGURE 12—Throughput comparison of two OpenSSL SHA- 256 routines for ARM: one written in C and one written in hand-tuned assembly. Each data point averages 10 runs.

0

200

400

600

800

1000

16 64 256 1024 8192 16,

Throughput (MB/s)

Number of input bytes per AES-CBC-128 encryption

C ASM without AES-NI ASM with AES-NI

FIGURE 13—Throughput comparison of three OpenSSL AES-CBC-128 routines for x86: one written in C, one writ- ten in hand-tuned assembly with only scalar instructions, and one written in hand-tuned assembly using SSE and AES-NI instructions. Each data point averages 10 runs.

and, as is the case in all figures in this paper, error bars indicate 95% confidence intervals. As shown in Figures 10 and 11, our results support the anecdotal belief that, in addition to being one of the most popular TLS libraries [ 61 ], OpenSSL’s cryptographic im- plementations are the fastest available. Hence, in our re- maining evaluation, we compare our performance with OpenSSL’s. These strong OpenSSL performance results suggest that OpenSSL’s Byzantine mix of Perl and hand- written assembly code (recall Figure 1) does result in noticeable performance improvements compared to the competition. As further support for the need for hand- written assembly code, Figures 12 and 13 compare the performance of OpenSSL’s C implementations (compiled with full optimizations) to that of its hand-written assem- bly routines. We see that OpenSSL’s assembly code for SHA-256 on ARM gets up to 67% more throughput than its C code, and its assembly code for AES-CBC-128 on x86 gets 247–300% more throughput than its C code due to the use of SSE and AES-NI instructions. To accurately compare our performance with OpenSSL’s, we make use of its built-in benchmarking tool openssl speed and its support for extensible cryp- tographic engines. We register our verified Vale routines as a new engine and link against our static library. Surpris- ingly, in collecting our initial measurements, we discov- ered that OpenSSL’s benchmarking tool does not actually

1

10

100

1000

10000

Verification time (s) 0 20 40 60 80 100 Number of instructions after unrolling

Add one to register AES Key Inversion AES Key Expansion

FIGURE 15—Time to verify various loops, if verification is done after unrolling.

Vale Taint 1st SHA AES-CBC SHA port Poly 12 6 6 5 0.75 0.

TABLE 2—Person-months per component.

when developing and debugging it. A key design decision in Vale is the verification of inlined procedures and unrolled loops before the inlining and unrolling occurs. Furthermore, as discussed in §4.1, Vale supports operand renaming for inlined procedures and unrolled loops, allowing us to match OpenSSL’s Perl- based register renaming. Figure 15 quantifies the benefits of this decision by showing the cost of verifying code after unrolling. (Note the log scale.) The three lines show:

  • the cost of verifying an unrolled loop consisting en- tirely of x86 add eax, 1 instructions, ranging from 10 to 100 total instructions;
  • the cost of verifying an unrolled loop of x86 AES key inversions, up to the maximum 9 iterations per- formed by AES, where each iteration consists of 3 instructions; and
  • the cost of verifying an unrolled loop of x86 AES key expansions, up to the maximum 10 iterations performed by AES, where each iteration consists of 10 instructions. If 100 adds are unrolled before verification, verification takes 58 seconds, which is tolerable, though much slower than verifying before unrolling. If all 10 AES key ex- pansion iterations are unrolled, verification takes 2300 seconds, compared to 105 seconds for verifying before unrolling. Finally, Dafny/Z3 fails to verify the AES key in- version for 6 unrolled iterations and 9 unrolled iterations, indicating that SMT solvers like Z3 are still occasion- ally unpredictable. Verifying code before inlining and unrolling helps mitigate this unpredictability and speeds up verification.

5.3 Verification effort

Table 2 summarizes the approximate amount of time we spent building Vale, our verified taint analyzer, and our

case studies. Our first implementations of SHA-256 and of AES-CBC were developed in parallel with Vale itself. They helped push the tool to evolve, but they also required multiple rewrites as Vale changed. Once Vale stabilized, porting SHA-256 to other architectures and implementing Poly1305 from scratch (including specifications, code, and proof) went much more rapidly, though the effort required was still non-trivial. In general, proving func- tional correctness was far more challenging than proving absence of leakage. For example, the SHA port initially only proved functional correctness. We then spent less than three days extending the functional proof to handle memory tainting and correcting errors identified by the taint analysis. As further evidence for Vale’s usability, an independent project is using Vale to develop a microkernel. Several researchers in that project are new to software verifica- tion and yet are able to make progress using Vale. Their efforts have also proceeded without the need to modify Vale, even though they have enriched our relatively sim- ple machine semantics, which we use to reason about cryptographic code, with details needed to program a mi- crokernel, e.g., program status registers, privilege modes, interrupts, exceptions, and user-mode execution.

6 Related Work

Other projects have verified correctness and security prop- erties of cryptographic implementations written in C or other high-level languages, either using Coq [ 11 ] or SMT solvers [ 28 , 80 ]. The SAW tool [ 28 ], for example, verifies C code (via LLVM) and Java code against mathemati- cal specifications written in the Cryptol language. Like Vale, SAW can use SMT solvers for verification, although unlike Vale, SAW unrolls loops before verification and assumes a static layout of data structures in memory. We hope to connect verified assembly language code to veri- fied high-level language code in the future. Vale, like other cryptography verification efforts, re- lies on formal specifications to define the correctness of implementations. The growing number of verified imple- mentations, both in high-level languages and assembly language, motivates standardization and thorough testing of such formal specifications. Cryptol [ 30 ], for exam- ple, may be used as a common specification language. In the future, we hope to check our Dafny specifications against specifications in Cryptol or similar languages. Vale also depends on formal semantics for the assem- bly language instructions used by Vale programs; these could be checked against existing architecture specifi- cations [ 71 ] or extended using more detailed ISA mod- els [33]. The Vale language follows in the path of Bedrock [ 19 ] and x86proved [ 42 , 44 ], which use Coq to build assem- bly language macros for various control constructs like

IF, WHILE, and CASE. Vale attempts to make these ap- proaches easier to use by leveraging an SMT-based logical framework and providing features like mutable ghost vari- ables and inline variables. Furthermore, although earlier tools have been used to synthesize cryptography code [ 29 ], Vale has been used to verify existing OpenSSL assembly language code, where optimizations are nontrivial. Vale also includes a verified analyzer that checks for leakage and side channels. Chen et al. [ 18 ] embed a simple Hoare logic in Coq, which they use to verify the “core part” of a Curve implementation written in the qhasm language, which is very close to assembly language. Like Vale, they use an SMT solver to complete the verification, although they only handle loop-free code and some of the SMT queries take hours to complete. A successor project uses a computer algebra system to reduce this verification time, at least in some initial experiments [ 15 ]; this technique seems promising and could help to better automate many of Vale’s lemmas about modular arithmetic. mCertiKOS [ 23 ], based on Coq, addresses information flow, although they do not consider timing and memory channels. In contrast to the verification done for mCer- tiKOS, which is targeted at a single difficult system (a small kernel), our information analysis tool can run auto- matically on many pieces of code. Such a tool is useful for verifying large suites of cryptographic code. Dam et al. [ 24 ] do address timing, but they approximate by assuming each instruction takes one machine cycle. Other assembly language verifiers like BoogieX86 [ 77 ], used by Ironclad [ 37 ], and VCC’s assembly language [ 56 ] have built on SMT solvers, but do not expose ASTs and as- sembly language semantics as first-class constructs. They thus are neither as flexible nor as semantically founda- tional as Vale, Bedrock, and x86proved. For example, BoogieX86 and Ironclad cannot support verified loop un- rolling and are tied to the x86 architecture; hence, they would require tool changes to support ARM and x64. Both BoogieX86 and Almeida et al. [ 9 ] leverage SMT solvers for information flow analysis. BoogieX86’s analy- sis is very flexible, but is considerably slower than Vale’s taint-based approach and does not address timing and memory channels. As discussed in more detail in §3, Almeida et al. detect a subset of side channels, but do not prove correctness of the cryptographic code, and resort to unproven assumptions about aliasing. Furthermore, they analyze intermediate code emitted by the LLVM compiler, whereas Vale verifies assembly code. This distinction is relevant since a compiler may choose to implement an IR- level instruction (e.g., srem) using a sequence of variable- latency assembly instructions (e.g., idiv). Also, their analysis is tied to the LLVM compiler’s code-generation strategy, whereas ours is not. Myreen et al. [ 58 ] apply common proofs across similar

pieces of code for multiple architectures by decompiling the assembly language code to a common format. We use a different approach to sharing across architectures: write each architecture’s code as a separate Vale procedure, but share lemmas about abstract state between the procedures. Many attacks based on side channels have been demon- strated [ 8 , 10 , 17 , 38 , 41 , 76 , 78 ]. We focus on detect- ing digital side channels by statically verifying precise constant-time execution. Side channels can also be miti- gated via compiler transformations [ 4 , 21 , 57 , 69 , 70 , 79 ], operating system or hypervisor modifications [ 46 , 54 ], microarchitectural modifications [ 52 , 53 ], and new cache designs [74, 75].

7 Conclusions and Future Work

Vale is our programming language and tool for writing and proving properties of high-performance cryptographic as- sembly code. It is assembler-neutral and platform-neutral in that developers can customize it for any assembler by writing a trusted printer, or for any architecture by writing a trusted semantics. It can thus support even advanced in- structions, as we demonstrate with an x86 implementation of AES-128/CBC that leverages SSE and AES-NI instruc- tions. Also, as we have shown with our implementations of SHA-256 on both ARM and x86, developers can reuse proofs and specifications for code across architectures. Vale supports reasoning about extracted code objects in a general-purpose high-level verification language; as an illustration of this style of reasoning, we have built and verified an analyzer that can declare a program free of digital information leaks. This analyzer uses taint track- ing with a unique approach to alias analysis: instead of settling for a conservative, unsound, or slow analysis, it leverages the address-tracking proofs that the developer already writes to prove her code functionally correct. Vale uses Dafny as a target verification language but only as an off-the-shelf tool with no customization, sug- gesting that we can also support other back ends. We hope to soon target F⋆^ [72], Lean [26], and Coq [22]. By porting OpenSSL’s SHA-256 ARM code and Poly1305 x64 code, we have shown that Vale can prove correctness, safety, and security properties for existing code, even if it is highly complex. The proofs ensure that the verified code meets its mathematical specification, ruling out bugs like those that appeared in OpenSSL’s Poly1305 code [ 64 – 66 ], as well as other correctness and memory safety bugs that have appeared in OpenSSL’s cryptographic code. We plan to continue porting addi- tional variants of these algorithms (e.g., adding SIMD support for SHA and Poly1305 for a performance boost of 23–41% [ 62 , 63 ]) and many others. Ultimately, we hope Vale will enable the creation of a complete crypto- graphic library providing fast, provably safe, correct, and leakage-free code for a wide variety of platforms.

Intel Technology Journal, 13(2), 2009. [37] C. Hawblitzel, J. Howell, J. R. Lorch, A. Narayan, B. Parno, D. Zhang, and B. Zill. Ironclad Apps: End- to-end security via automated full-system verification. In Proceedings of the USENIX Symposium on Operating Sys- tems Design and Implementation (OSDI), October 2014. [38] C. Hunger, M. Kazdagli, A. Rawat, A. Dimakis, S. Vish- wanath, and M. Tiwari. Understanding contention-based channels and using them for defense. In Symposium on High Performance Computer Architecture, Feb. 2015. [39] Intel. Intel ⃝R^ 64 and IA-32 Architectures Software Devel- oper’s Manual, Aug. 2012. [40] M. S. Islam, M. Kuzu, and M. Kantarcioglu. Access pat- tern disclosure on searchable encryption: Ramification, attack and mitigation. In Proceedings of the Network and Distributed System Security Symposium (NDSS), 2012. [41] S. Jana and V. Shmatikov. Memento: Learning secrets from process footprints. In Proceedings of the IEEE Sym- posium on Security and Privacy, May 2012. [42] J. B. Jensen, N. Benton, and A. Kennedy. High-level separation logic for low-level code. In Proceedings of ACM POPL, 2013. [43] T. Kaufmann, H. Pelletier, S. Vaudenay, and K. Villegas. When constant-time source yields variable-time binary: Exploiting Curve25519-donna built with MSVC 2015. In Proceedings of the International Conference on Cryptol- ogy and Network Security (CANS), Nov. 2016. [44] A. Kennedy, N. Benton, J. B. Jensen, and P.-E. Dagand. Coq: The world’s best macro assembler? In Proceedings of the Symposium on Principles and Practice of Declarative Programming (PPDP), 2013. [45] G. A. Kildall. A unified approach to global program opti- mization. In Proceedings of ACM POPL, 1973. [46] T. Kim, M. Peinado, and G. Mainar-Ruiz. STEALTH- MEM: System-level protection against cache-based side channel attacks in the cloud. In Proceedings of the USENIX Security Symposium, Aug. 2012. [47] P. C. Kocher. Timing attacks on implementations of Diffie- Hellman, RSA, DSS, and other systems. In Proceedings of the International Cryptology Conference (CRYPTO),

[48] P. C. Kocher, J. Jaffe, and B. Jun. Differential power analysis. In Proceedings of the International Cryptology Conference (CRYPTO), Aug. 1999. [49] N. Lawson. Optimized memcmp leaks useful timing differences. https://rdist.root.org/2010/08/ 05/optimized-memcmp-leaks-useful-timing- differences, Aug. 2010. [50] K. R. M. Leino. Dafny: An automatic program verifier for functional correctness. In Proceedings of the Conference on Logic for Programming, Artificial Intelligence, and Reasoning (LPAR), 2010. [51] K. R. M. Leino and N. Polikarpova. Verified calculations. In Verified Software: Theories, Tools, Experiments, 2014. [52] C. Liu, A. Harris, M. Maas, M. Hicks, M. Tiwari, and E. Shi. GhostRider: A hardware-software system for mem- ory trace oblivious computation. In Proceedings of the Conference on Architectural Support for Programming Languages and Operating Systems, Mar. 2015.

[53] M. Maas, E. Love, E. Stefanov, M. Tiwari, E. Shi, K. Asanovic, J. Kubiatowicz, and D. Song. PHANTOM: Practical oblivious computation in a secure processor. In Proceedings of ACM CCS, Nov. 2013. [54] R. Martin, J. Demme, and S. Sethumadhavan. Time- Warp: Rethinking timekeeping and performance moni- toring mechanisms to mitigate side-channel attacks. In Proceedings of the Symposium on Computer Architecture, June 2012. [55] R. J. Masti, D. Rai, A. Ranganathan, C. Müller, L. Thiele, and S. Capkun. Thermal covert channels on multi-core platforms. In Proceedings of the USENIX Security Sympo- sium, Aug. 2015. [56] S. Maus, M. Moskal, and W. Schulte. Vx86: x86 assembler simulated in C powered by automated theorem proving. In Proceedings of the Conference on Algebraic Methodology and Software Technology, 2008. [57] D. Molnar, M. Piotrowski, D. Schultz, and D. Wagner. The program counter security model: Automatic detection and removal of control-flow side channel attacks. In Proceed- ings of the Workshop on Fault Diagnosis and Tolerance in Cryptography (FDTC), Dec. 2005. [58] M. O. Myreen, M. J. C. Gordon, and K. Slind. Decom- pilation into logic — improved. In Proceedings of the Conference on Formal Methods in Computer-Aided De- sign (FMCAD), Oct. 2012. [59] National Institute of Standards and Technology. Announc- ing the ADVANCED ENCRYPTION STANDARD (AES). Federal Information Processing Standards Publication 197, Nov. 2001. [60] National Institute of Standards and Technology. Secure Hash Standard (SHS), 2012. FIPS PUB 180-4. [61] Netcraft Ltd. September 2016 Web server survey, 2016. [62] OpenSSL. Poly1305-x86_x64. https://github. com/openssl/openssl/blob/master/crypto/ poly1305/asm/poly1305-x86_64.pl. [63] OpenSSL. Sha256-armv4. https://github.com/ openssl/openssl/blob/master/crypto/sha/asm/ sha256-armv4.pl. [64] OpenSSL. Chase overflow bit on x and ARM platforms. GitHub commit dc3c5067cd90f3f2159e5d53c57b92730c687d7e, 2016. [65] OpenSSL. Don’t break carry chains. GitHub commit 4b8736a22e758c371bc2f8b3534dc0c274acf42c, 2016. [66] OpenSSL. Don’t loose [sic] 59-th bit. GitHub commit bbe9769ba66ab2512678a87b0d9b266ba970db05, 2016. [67] OpenSSL Developer Team. Private communication, Jan.

[68] C. Percival. Cache missing for fun and profit, 2005. [69] A. Rane, C. Lin, and M. Tiwari. Raccoon: Closing digital side-channels through obfuscated execution. In Proceed- ings of the USENIX Security Symposium, Aug. 2015. [70] A. Rane, C. Lin, and M. Tiwari. Secure, precise, and fast floating-point operations on x86 processors. In Proceed- ings of the USENIX Security Symposium, Aug. 2016. [71] A. Reid. Trustworthy specifications of ARM v8-A and v8-M system level architecture. In Formal Methods in Computer-Aided Design (FMCAD 2016), 2016. [72] N. Swamy, J. Chen, C. Fournet, P. Strub, K. Bhargavan,

and J. Yang. Secure distributed programming with value- dependent types. In Proceedings of ACM ICFP, 2011. [73] W. Taha and T. Sheard. Multi-stage programming with explicit annotations. In Proceedings of the ACM SIGPLAN Symposium on Partial Evaluation and Semantics-based Program Manipulation (PEPM), 1997. [74] Z. Wang and R. B. Lee. New cache designs for thwarting software cache-based side channel attacks. In Proceedings of the Symposium on Computer Architecture, June 2007. [75] Z. Wang and R. B. Lee. A novel cache architecture with enhanced performance and security. In Proceedings of the International Symposium on Microarchitecture (MICRO), Nov. 2008. [76] Y. Xu, W. Cui, and M. Peinado. Controlled-channel at- tacks: Deterministic side channels for untrusted operating systems. In Proceedings of the IEEE Symposium on Secu- rity and Privacy, May 2015. [77] J. Yang and C. Hawblitzel. Safe to the last instruction: Automated verification of a type-safe operating system. In Proceedings of ACM PLDI, 2010. [78] Y. Yarom, D. Genkin, and N. Heninger. CacheBleed: A timing attack on OpenSSL constant time RSA. In Proceed- ings of the International Conference on Cryptographic Hardware and Embedded Systems (CHES), Aug. 2010. [79] D. Zhang, A. Askarov, and A. C. Myers. Language-based control and mitigation of timing channels. In Proceedings of ACM PLDI, June 2012. [80] J. K. Zinzindohoue, E.-I. Bartzia, and K. Bhargavan. A ver- ified extensible library of elliptic curves. IEEE Computer Security Foundations Symposium (CSF), 2016.

A Vale Grammar

For reference, this appendix contains an annotated gram- mar for the Vale language. We use ∗^ to indicate zero or more repetitions, ∗,^ to indicate zero or more repetitions separated by commas, +,^ to indicate one or more repe- titions separated by commas, and ∗;^ to indicate zero or more repetitions, each terminated by a semi-colon. In most places, vertical bars divide grammar alternatives and square brackets surround optional grammatical com- ponents, but in a few places where we think their us- age is clear, we abuse this notation and use vertical bars and square brackets to stand for themselves in the gram- mar. Other punctuation stands for itself. Lowercase letters stand for identifiers and are suggestive of what kind of identifiers they represent. At the top level, a Vale program consists of some num- ber of declarations.

PROGRAM ::= | DECL∗

A declaration introduces a variable, function, or pro- cedure, or provides some declarations in the underlying logical framework (Dafny) to be included verbatim.

DECL ::= | var x : TYPE ;

| function f ( FORMAL∗,^ ) : TYPE [:= f] ; | procedure p ( PFORMAL∗,^ ) [returns ( PRET∗,^ )] SPEC∗^ { STMT∗^ } | procedure p ( PFORMAL∗,^ ) [returns ( PRET∗,^ )] SPEC∗^ extern ; | procedure p ( PFORMAL∗,^ ) [returns ( PRET∗,^ )] := p ; | VERBATIM-DECL-BLOCK

A FORMAL represents a formal parameter of a func- tion or a bound variable. It is simply an identifier and an optional type. An attempt is made to infer any omitted types. Procedure parameters are broken down into two categories, PFORMAL and PRET, the latter of which is used for parameters that are only being returned from the procedure.

FORMAL ::= | x [: TYPE]

PFORMAL ::=

| ghost x : TYPE | inline x : TYPE | TYPE x : TYPE | out TYPE x : TYPE | inout TYPE x : TYPE

PRET ::=

| ghost x : TYPE | TYPE x : TYPE

Types are declared in the underlying logical framework and referred to in Vale by name. Types can be parameter- ized by other types. Vale also supports tuple types.

TYPE ::= | t | TYPE ( TYPE∗,^ ) | tuple ( TYPE∗,^ ) | ( TYPE )

A procedure can be declared with specification clauses. A reads or modifies clause says which global variables the procedure may read or write, respectively. The key- words requires and ensures are used to introduce pre- and postconditions. Since it often happens that a proce- dure both requires and ensures some invariant condition, there is a specification clause that avoids the syntactic repetition of such conditions.

SPEC ::= | reads x∗; | modifies x∗; | requires LEXP∗; | ensures LEXP∗; | requires / ensures LEXP∗;