scieee AI-readable full text Open interactive document viewer

A fast and verified software stack for secure function evaluation

Almeida, José Bacelar; Barbosa, Manuel; Barthe, Gilles Jacques Denis; Dupressoir, François; Grégoire, Benjamin; Laporte, Vincent; Pereira, Vitor

Abstract

We present a high-assurance software stack for secure function evaluation (SFE). Our stack consists of three components: i. a verified compiler (CircGen) that translates C programs into Boolean circuits; ii. a verified implementation of Yao’s SFE protocol based on garbled circuits and oblivious transfer; and iii. transparent application integration and communications via FRESCO, an open-source framework for secure multiparty computation (MPC). CircGen is a general purpose tool that builds on CompCert, a verified optimizing compiler for C. It can be used in arbitrary Boolean circuit-based cryptography deployments. The security of our SFE protocol implementation is formally verified using EasyCrypt, a tool-assisted framework for building high-confidence cryptographic proofs, and it leverages a new formalization of garbled circuits based on the framework of Bellare, Hoang, and Rogaway (CCS 2012). We conduct a practical evaluation of our approach, and conclude that it is competitive with state-of-the-art (unverified) approaches. Our work provides concrete evidence of the feasibility of building efficient, verified, implementations of higher-level cryptographic systems. All our development is publicly available.

Full text

A Fast and Verified Software Stack for Secure Function Evaluation José Bacelar Almeida INESC TEC and Universidade do Minho, Portugal Manuel Barbosa INESC TEC and FCUP Universidade do Porto, Portugal Gilles Barthe IMDEA Software Institute, Spain François Dupressoir University of Surrey, UK Benjamin Grégoire Inria Sophia-Antipolis, France Vincent Laporte IMDEA Software Institute, Spain Vitor Pereira INESC TEC and FCUP Universidade do Porto, Portugal ABSTRACT We present a high-assurance software stack for secure function evaluation (SFE). Our stack consists of three components: i. a verified compiler (CircGen) that translates C programs into Boolean circuits; ii. a verified implementation of Yao’s SFE protocol based on garbled circuits and oblivious transfer; and iii. transparent application integration and communications via FRESCO, an open-source framework for secure multiparty computation (MPC). CircGen is a general purpose tool that builds on CompCert, a verified optimizing compiler for C. It can be used in arbitrary Boolean circuit-based cryptography deployments. The security of our SFE protocol implementation is formally verified using EasyCrypt, a tool-assisted framework for building high-confidence cryptographic proofs, and it leverages a new formalization of garbled circuits based on the framework of Bellare, Hoang, and Rogaway (CCS 2012). We conduct a practical evaluation of our approach, and conclude that it is competitive with state-of-the-art (unverified) approaches. Our work provides concrete evidence of the feasibility of building efficient, verified, implementations of higher-level cryptographic systems. All our development is publicly available. KEYWORDS Secure Function Evaluation, Verified Implementation, Certified Compilation 1 INTRODUCTION Cryptographic engineering is the domain-specific area of software engineering that brings cryptography to practice. It encompasses projects that maintain widely used cryptographic libraries such Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from [email protected]. CCS ’17, October 30-November 3, 2017, Dallas, TX, USA © 2017 Copyright held by the owner/author(s). Publication rights licensed to Association for Computing Machinery. ACM ISBN 978-1-4503-4946-8/17/10...$15.00 https://doi.org/10.1145/3133956.3134017 as OpenSSL, 1 s2n 2 and Bouncy Castle, 3 as well as prototyping frameworks such as CHARM [ 1 ] and SCAPI [ 31 ]. More recently, a series of groundbreaking cryptographic engineering projects have emerged, that aim to bring a new generation of cryptographic protocols to real-world applications. In this new generation of protocols, which has matured in the last two decades, secure computation over encrypted data stands out as one of the technologies with the highest potential to change the landscape of secure ITC, namely by improving cloud reliability and thus opening the way for new secure cloud-based applications. Projects that aim to bring secure computation over encrypted data to practice include FRESCO 4 [ 27 ], TASTY [38] and Sharemind [21]. In contrast to other areas of software engineering for critical systems, the benefits of formal verification for cryptographic engineering have been very limited, with some recent and notable exceptions [ 2 , 3 , 8 , 18 , 22 , 33 ]. The reasons for this are well known: cryptographic software is a challenge for high-assurance software development due to the tension that arises between complex specifications and the need for very high efficiency—security is supposed to be invisible, and current verification technology comes with a performance penalty. The exceptions mentioned above mark the emergence of a new area of research: high-assurance cryptography. This aims to apply formal verification to both cryptographic security proofs and the functional correctness and security of cryptographic implementations. In this paper we demonstrate that a tight integration of highassurance cryptography and cryptographic engineering can deliver the combined benefits of provable security and best cryptographic engineering practices at a scale that significantly exceeds previous experiments (typically carried out on core cryptographic primitives). We deliver a fast and verified software stack for secure computation over encrypted data. This choice is motivated by several factors. First, as mentioned above, this technology is among the foremost practical applications of cryptography and is a fundamental building block for making cloud computing secure. Second, it is 1http://openssl.org 2http://https://github.com/awslabs/s2n 3https://www.bouncycastle.org/ 4https://github.com/aicis/fresco C program Optimized CircGen CircGen Boolean circuit Circuit reader Circuit description FRESCO application Verified Yao Protocol Suite Verified Yao Evaluator Communications FRESCO Inputs Outputs Figure 1: Verified cryptographic software stack. Blue rectangles identify the verified components of the stack, while black rectangles represent part of our trusting computing base. Dashed blue rectangles are partially verified elements and in dashed black rectangles one can find intermediate input/output items. a tremendous challenge for high-assurance cryptography, as its security proofs are markedly distinct from prior work in formalizing reductionist arguments. Contributions. We present a high-assurance and high-speed software stack for secure multi-party computation. Figure 1 presents the overall architecture of the stack. The lowest-level component is FRESCO [ 27 ]; an existing, practical, open-source, framework for secure multi-party computation, which we use for communications and input/output. The correctness of this framework (but not its security) is part of our trusted computing base, as verifying the correctness of a Java-based communications infrastructure is out of the scope of high-assurance cryptography. The intermediate component of our stack is a verified implementation of Yao’s secure function evaluation (SFE) protocol [ 57 ] based on garbled circuits and oblivious transfer. This protocol allows two parties P1 and P2 , holding private inputs x1 and x2 , to jointly evaluate any function f(x1,x2) and learn its result, whilst being assured that no additional information about their respective inputs is revealed. Two-party SFE provides a general distributed solution to the problem of computing over encrypted data in the cloud [ 41 ]; we allow for both scenarios where the function is public and both sides provide inputs and scenarios where one party provides the (secret albeit with leaked topology) circuit to be computed and the other party provides the input to the computation. Our implementation is machine-checked in EasyCrypt 5 [ 7 , 9 ], an interactive proof assistant with dedicated support to perform gamebased cryptographic proofs in the computational model. Our proof 5https://www.easycrypt.info leverages the foundational framework put forth by Bellare, Hoang and Rogaway [ 12 ] for the security of Yao’s garbled circuits. Our construction of SFE relies on an n -fold extension (where n is the size of the selection string–or the circuit’s input) of the oblivious transfer protocol by Bellare and Micali [ 13 ], in the hashed version presented by Naor and Pinkas [ 47 ]. The implementation is proved secure relative to standard assumptions: the Decisional Diffie-Hellman problem, and the existence of entropy-smoothing hash functions and pseudorandom functions. The higher-level component of our stack is a verified optimizing compiler from C programs to Boolean circuits that we call CircGen. Our compiler is mechanically verified using the Coq proof assistant, and builds on top of CompCert [ 43 ], a verified optimizing compiler for C programs. It reuses the front- and middle-end of CompCert (introducing an extra loop-unrolling optimization) and it provides a new verified back-end producing Boolean circuits. The back-end includes correctness proofs for several program transformations that have not previously been formally verified, including the translation of RTL programs into guarded form and a memory-agnostic static single assignment (SSA) form. Our proof of semantic preservation is conditioned on the existence of an external oracle that provides functionally correct Boolean circuits for basic operations in the C language, such as 32-bit addition and multiplication. The low-level circuits used in our current implementation for these operations have not been formally verified and are hence part of our trusted computing base. Verifying Boolean circuits for native C operations can be done either in Coq or using other verification techniques and it is orthogonal to the reported verification effort. The Boolean circuits generated by CircGen compare well with alternative unverified solutions, namely CBMC-GC 6 [ 34 ], although they are slightly less efficient (as would be expected). To widen the applicability of CircGen to scenarios where speed is more important than assurance, we also implement some (yet unverified) global post-processing optimizations that make CircGen a good alternative to CBMC-GC for high-speed applications. Our work delivers several generic building blocks (the Boolean circuit compiler, a verified implementation of oblivious transfer, ...) that can be reused by many other verified cryptographic systems. However, the main strength of our results resides in the fact that, for the first time, we are able to produce a joining of high-assurance cryptography and cryptography engineering that covers all the layers in a (passively) secure multiparty computation software framework. Challenges. The development of the software stack raised several challenges, which we now highlight. Machine-checked proofs of computational security. EasyCrypt [ 7 , 9 ] is an interactive proof assistant with dedicated support to perform game-based cryptographic proofs. It has been used for several emblematic examples, including signatures and encryption schemes. Formalizing the proof of security for our SFE protocol in EasyCrypt involved formalizing two generic proof techniques that had not previously been considered: hybrid arguments and simulation-based security proofs. 6http://forsyte.at/software/cbmc-gc/ In contrast to other standard techniques, which remain within the realm of the relational program logic that forms the core of EasyCrypt (i.e., it is used to verify transitions between successive games), hybrid arguments and simulation-based proofs lie at the interface between this relational program logic and the higher-order logic of EasyCrypt in which security statements are expressed and proved. Specifically, hybrid arguments combine induction proofs and proofs in the relational program logic. Similarly, simulationbased security proofs intrinsically require existential quantification over adversarial algorithms and the ability to instantiate security models with concrete algorithms (the simulators) that serve as witnesses as to the validity of the security claims. These two forms of reasoning excercise the expressive power of EasyCrypt’s ambient logic, and are thus markedly distinct from the simple security arguments typically addressed by other similar tools like CryptoVerif [ 19 ]. Secure function evaluation is also a challenging test case in terms of its scale. Indeed, EasyCrypt had so far been used primarily for primitives and to a lesser extent for (components) of protocols. While these examples can be intricate to verify, there is a difference of scale with more complex cryptographic systems, such as SFE, which involve several layers of cryptographic constructions. Realizing our broader goal required several improvements to the EasyCrypt tool. In particular, the complexity and scale of the proof developed here guided several aspects of EasyCrypt’s development to support compositional simulation-based proofs, and the aim of producing executable code from machine-checked specifications served as initial motivation for EasyCrypt’s code extraction mechanism. We contribute a generic formalization of hybrid arguments that has since been included in EasyCrypt’s library of game transformations. High-assurance and high-speed implementations. Our implementation of Yao’s protocol can be thought of as a secure virtual machine for securely executing arbitrary computations. The challenge is therefore dual: in addition to a verified implementation of this virtual machine of sorts, one needs to generate correct and efficient computation descriptions in a format that can be executed in this virtual computational platform (in this case Boolean circuits). Generating such circuit representations by hand is not realistic, and appropriate tool support is critical if widespread practical adoption is the goal. The requirement of end-to-end verification further imposes that compilation into circuits must itself be verified. CircGen fills this gap from both a high-assurance cryptography perspective—verified outputs incur a small performance penalty— and a cryptographic engineering perspective—it supports unverified optimizations for speed-critical applications. Highlights of our technical contributions at this level include: (1) the addition of a loop unrolling transformation to the CompCert middle-end that permits converting those programs that can be expressed as circuits into a loop-free form; (2) new intermediate languages in CompCert with corresponding transformations semantics preservation theorems that permit converting loop-free programs gradually into a circuit representation—this includes a new domain-specific transformation into Static Single Assignment (SSA) form; and (3) the formalization of a new target language that captures the semantics of Boolean circuits and permits stating and proving a semantics preservation theorem relating the I/O behavior of an input C program to that of a generated circuit. Access to the development. The EasyCrypt formalisation of Yao’s protocol, as well as its extracted code, can be found at https: //ci.easycrypt.info/easycrypt-projects/yao. The code for CircGen can be found at https://github.com/haslab/circgen. Structure of the paper. In Section 2 we describe the EasyCrypt formalization and the verified implementation of Yao’s protocol. In Section 3 we present CircGen, our certified Boolean circuit compiler. In each of these sections, we give micro-benchmarks for the related software component. We then present an overall performance evaluation of the software stack in Section 4. In Section 5 we discuss related work, before making some concluding remarks in Section 6. Limitations. Our approach covers a comfortable subset of C, but some features are excluded (see Table 2); some of these features will be added in future work, while others are traditionally out of reach for SFE. Moreover, some low-level optimizations have not yet been verified; however, our experiments show that the verified version of the compiler is already surprisingly close to the optimized version for most examples. Finally, our Trusted Computing Base includes the FRESCO platform, Cryptokit (used to instantiate the hash function) and justGarble (used to instantiate the PRF); the formal verification of these components is out of scope of this work. 2 VERIFIED SFE IMPLEMENTATION We first give an overview of what we prove in EasyCrypt, relating this to established results in the field of cryptography. We do not go into the details of the (publicly available) formalization but include in Appendix A an example-driven presentation of its highlights. The formalization is available online and the various files that compose it can be easily matched to the building blocks in the high-level description we give here. At the end of the section we describe how we obtain our verified implementation from the EasyCrypt formalization. Yao’s protocol in a nutshell. Yao’s protocol is based on the concept of garbled circuits. Informally, the idea of garbling a circuit computing f consists of: i. expressing the circuit as a set of truth tables (one for each gate) and meta information describing the wiring between gates; ii. replacing the actual Boolean values in the truth tables with random cryptographic keys, called labels; and iii. translating the wiring relations using a system of locks: truth tables are encrypted one label at a time so that, for each possible combination of the input wires, the corresponding labels are used as encryption keys that lock the label for the correct Boolean value at the output of that gate. Then, given a garbled circuit for f and a set of labels representing (unknown) values for the input wires encoding x1 and x2 , one can obliviously evaluate the circuit by sequentially computing one gate after another: given the labels of the input wires to a gate, only one entry in the corresponding truth table will be decryptable, revealing the label of the output wire. The output of the circuit will comprise the labels at the output wires of the output gates. Dual Masking PRF Double Encryption Ideal Cipher Dual Key Cipher 1 Garble1 Garbling Scheme IND Secure 2 Garbling Scheme SIM Secure 3 Oblivious Transfer 2PPP Secure Yao’s Protocol SFE 2PPP Secure 4 Figure 2: Yao’s protocol security proof by BHR [12]. To build a SFE protocol between two honest-but-curious parties, one can use Yao’s garbled circuits as follows. Bob (holding x2 ) garbles the circuit and provides this to Alice (holding x1 ) along with: i. the label assignment for the input wires corresponding to x2 , and ii. all the information required to decode the Boolean values of the output wires. In order for Alice to be able to evaluate the circuit, she should be able to obtain the correct label assignment for x1 . Obviously, Alice cannot reveal x1 to Bob, as this would violate the input-privacy goals of SFE. Also, Bob cannot reveal information that would allow Alice to encode anything other than x1 , since this would reveal more than f(x1,x2) . To solve this problem, Yao proposed the use of an oblivious transfer (OT) protocol. This is a (lower-level) SFE protocol for a very simple functionality that allows Alice to obtain the labels that encode x1 from Bob, without revealing anything about x1 and learning nothing more than the labels she requires. 7 The protocol is completed by Alice evaluating the circuit, recovering the output, and providing the output value back to Bob. Excellent descriptions of Yao’s SFE protocol with slightly different security proofs can be found in [12, 44]. A modular proof of security. Our starting point for producing a formally verified implementation of Yao’s protocol is to transpose to EasyCrypt the modular security proof by Bellare, Hoang and Rogaway [ 12 ] (BHR). The central component in this proof is a new abstraction called a garbling scheme that captures the functionality and security properties of the circuit garbling technique that is central to Yao’s SFE protocol. This new abstraction was used by BHR to make precise the different security notions that could apply to this garbling step. This permits separating the design and analysis of efficient garbling schemes from higher level protocols, which may rely on different security properties of the garbling component.8 Figure 2 shows the structure of the proof of security for Yao’s protocol given in [ 12 ] (we focus only on the result that is relevant for this paper). We depict constructions as rectangles with grey captions and primitives (i.e., cryptographic abstractions with a welldefined syntax and security model) as rounded rectangles with black captions. Security proofs are represented by dashed arrows and implications between notions as solid arrows. A construction enclosing a primitive in the diagram indicates that the primitive is used as an abstract building block in its security proof. For example, arrow (1) indicates that the first step in the proof is the construction of a dual key cipher (DKC) using a standard PRF security assumption via a construction that we call dual masking. The same primitive is also constructed from an ideal cipher via the double encryption construction. 7 Luckily, efficient protocols for the OT functionality exist, thereby eliminating what could otherwise be a circular dependency. 8 Garbled circuits are used in Yao’s SFE protocol, but have found many other applications in cryptography. A DKC is a tweakable deterministic encryption scheme that can be used to lock secret keys (corresponding to gate output wire labels) and is keyed by two other independent keys (corresponding to gate input wire labels). Informally, the dual masking construction applies two masks to the encrypted key, computed as PRFKi(T) for i= 1 , 2, where T is the tweak. The DKC security model is designed in an ad hoc way to be just strong enough for constructing garbling schemes from a wide range of assumptions, including interesting instantiations such as double encryption. DKC security is a real- or-random notion, where the attacker has an unbounded number of keys to choose from, both for posing as encryption keys and as encrypted keys. One of these secret keys is singled out as the challenge secret key, and it can never be encrypted nor revealed to the attacker (who may see all the other keys). The model also captures the fact that it is convenient to leak the least significant bit of such keys in order to encode the topology of a circuit. The second step in the proof (2) is to construct a garbling scheme from a (DKC). There are two security definitions for garbling schemes: indistinguishability-based (IND) and simulation-based (SIM). The former is used as a stepping stone (hence its dashed presentation in the diagram) to proving SIM-security. Indeed, the two notions are proven to be equivalent for certain classes of garbling schemes (this is shown as step 3 in the diagram). Proving that a concrete construction called Garble1 achieves IND security is the most challenging part of the proof: it involves a hybrid argument over those wires in the circuit that are not visible to an attacker (the security model allows the attacker to observe the opening of the circuit for one concrete input). The final step (4) in the proof is to show that Yao’s technique of combining an oblivious transfer protocol— two-party passively (2PPP) secure—with a SIM-secure garbling scheme yields a 2PPP secure SFE protocol. This step consists of a game-based argument with two relatively simple transitions, but involving simulation-based definitions and combined universal and existential quantifications over adversarial algorithms. Our Proof. We show in Figure 3 the structure of our EasyCrypt formalization. It is visible in the figure that the main structure of the proof, steps 1-4 are very close to the original proof of [ 12 ]. The only deviation here is that we simplify the Dual Key Cipher security game to a slightly stronger variant that is still satisfied by the dual masking instantiation, but which has an internal structure that makes the proof of security of the garbling scheme significantly easier. Intuitively, the difference is that one imposes that the tweak effectively makes encryptions of the same value indistinguishable from each other. This excludes some secure DKC instantiations that we do not consider in this paper. To further simplify our proofs, our DKC security definition is also parametrized by two integer parameters cand pos . The first parameter provides an upper-bound on the number of keys in the game, so that they can all be sampled at the beginning of the security experiment. The second parameter specifies an index in the range [1 .. c]that will be used in oracle queries as the index for the hidden secret key. Figure 3 also shows three additional proof steps (5, 7 and 8, shown in blue). These correspond to instantiation (i.e., restricted forms of composition) steps that are often implicit in hand-written cryptographic proofs. For example, suppose construction CP2 1 is proven Dual Masking PRF Dual Key Cipher’ 1 SomeGarble Garbling Scheme IND Secure 2 Garbling Scheme SIM Secure 3 5 DDH Entropy Smoothing SomeOT Oblivious Transfer 2PPP Secure 6 Yao’s Protocol SFE 2PPP Secure 4 Implementation 7 8 Figure 3: Structure of our verified security proof of an implementation of Yao’s protocol. to be a valid instantiation for primitive P1 under the assumption that instantiations for abstract primitive P2 exist. Suppose also that construction CP3 2 is proven to be a valid instantiation of primitive P2 , assuming the existence of a valid instantiation for (lower level) primitive P3 . Then, this implies that CC2 1 is also a valid instantiation of P1under assumption P3. Such steps are critical in making our main Theorem (Theorem 2.1 below) apply to a concrete and efficient implementation of Yao’s protocol that can readily be extracted in to OCaml code from its EasyCrypt description. To obtain such a result our formalization needs to explicitly include theorems that instantiate abstract security results into concrete security bounds for the implementation. More precisely, one needs to prove i. that the implementation is functionally equivalent to the composition of a concrete oblivious transfer and garbling schemes; and ii. that this implies that the security bound for the generic SFE security theorem (4 in the figure) can be instantiated into a concrete overall bound by plugging in security bounds obtained by instantiating all intermediate results all the way down to the PRF, DDH and entropy smoothing assumptions. EasyCrypt enables formalizing both the complex abstract security proofs and the instantiation steps (with very little overhead in the case of the latter). The main theorem in our formalization states the following, for any upper bound con the total number of wires in the circuit and any upper bound non the number of input wires in the circuit. Theorem 2.1. For all SFE adversaries A against the EasyCrypt implementation Impl of Yao’s protocol, there exist efficient simulator S and adversaries BDDH,BES and Bi PRF for i∈[1..c], such that: AdvSFE Impl,S(A)≤c·εPRF +n·AdvDDH(BDDH)+n·AdvES(BES) where εPRF =max1≤i≤c(Adv(Bi PRF)) , and AdvPRF , AdvDDH and AdvES represent the advantages against the PRF, the Diffie-Hellman group and entropy smoothing hash function used as primitives. Using Generic Lemmas. In Cryptography, it is common to repeat proof techniques in different proofs or even inside the same proof. As a side contribution of our work, we formalize a generic hybrid argument that is included as part of EasyCrypt’s library of verified transformations. The objective of this library is to formalize often-used proof techniques once and for all, enabling the user to perform proofs “by a hybrid argument”, or “by eager sampling”, whilst formally checking that all side conditions are fulfilled at the time the lemma is applied. We now describe the generic hybrid argument. type input, output, inleaks, outleaks. module type Orcl = { proc o(_:input) : output }. module type Orclb= { proc leaks(_:inleaks): outleaks proc oL(_:input) : output proc oR(_:input) : output }. module type AdvHy (Ob:Orclb, O:Orcl) = { proc main () : bool }. module Ln(Ob:Orclb,A:AdvHy)={ module O: Orcl = { (∗increment C.c and call Ob.oL∗) } module A'=A(Ob, O); proc main () : bool = { C.c = 0; return A'.main(); } }. module Rn(Ob:Orclb,A:Adv) = { (∗Same as Lnbut use Ob.oR∗) }. op q : int. module B(A:AdvHy, Ob:Orclb, O:Orcl) = { module LR = { var l, l0:int proc orcl(m:input):output = { var r : output; if (l0<l)r=Ob.oL(m); else if (l0= l) r = O.orcl(m); else r=Ob.oR(m); l = l + 1; return r; } } module A'=A(Ob,LR) proc main():outputA = { var r:outputA; LRB.l0←$ [0..q−1]; LRB.l = 0; return A'.main(); } }. lemma Hybrid: ∀(Ob:Orclb{C,B}) (A:AdvHy {C,B,Ob}), Pr[Ln(Ob,A): res∧C.c ≤n] −Pr[Rn(Ob,A): res∧C.c ≤n] = q∗(Pr[Ln(Ob,B(A)): res∧ B.l ≤n∧C.c ≤1] − Pr[Rn(Ob,B(A)): res∧ B.l ≤n∧C.c ≤1]). Figure 4: Hybrid argument lemma. As described in Figure 4, consider an adversary parameterized by two modules. The first parameter Ob , implementing the module type Orclb , provides a leakage oracle, a left oracle oL and right oR . The second parameter O , implementing module type Orcl , provides a single oracle o . The goal of an adversary implementing type AdvHy is to guess, in at most n queries to O.o , if it is implementing the left oracle Ob.oL or the right oracle Ob.oR . To express the advantage of such an adversary, we write two modules: the first one, Ln , defines a game where the adversary is called with O.o equal to Ob.oL , the second one, Rn , uses Ob.oR instead. Both Ln and Rn use a variable C.c to count the number of queries made to their oracle by the adversary. We define the advantage of an adversary A in distinguishing Ob.oL from Ob.oR as the difference of the probability of games Ln(Ob,A) and Rn(Ob,A) returning 0. Given any distinguishing adversary A , we construct a distinguishing adversary B that may use A but always makes at most one query to oracle O.o. The Hybrid lemma relates the advantages of any adversary A with the advantage of its constructed adversary B when A is known to make at most q queries to O.o . Note that the validity of the Hybrid lemma is restricted to adversaries that do not have a direct access to the counter C.c , or to the memories of B and Ob ; this is denoted by the notation AdvHy{C,B,Ob} in the EasyCrypt code. Other lemmas shown in this paper also have such restrictions in their formalizations, but they are as expected (that is, they simply enforce a strict separation of the various protocols’, simulators’ and adversaries’ memory spaces) and we omit them for clarity. The construction of B is generic in the underlying adversary A , which can remain completely abstract. We underline that, for all A implementing module type AdvHy , the partially-applied module B(A) implements AdvHy as well and can therefore be plugged in anywhere a module of type AdvHy is expected. This ability to generically construct over abstract schemes or adversaries is central to handling modularity in EasyCrypt. Finally, we observe that the Hybrid lemma applies even to an adversary that may place queries to the individual Ob.oL and Ob.oR oracles. It is of course applicable (and is in fact often applied) to adversaries that do not place such queries. An application example of the generic hybrid argument is our proof of security of the oblivious transfer protocol. In Figure 5, we describe the concrete two-party OT protocol in a purely functional manner, making explicit local state shared between the various stages of each party. For example, step1 outputs the sender’s local state sts, later used by step3. op step1(m:(msg ∗msg) array) (r:int array ∗G) = let (c,hkey) = r in let sts= (m,дc,hkey) in let m1= (hkey,дc) in (sts,m1). op step2(b:bool array) (r:Garray) m1= let (hkey,gc)=m1in let stc= (b,hkey,r) in let m2=if bthen gc /дrelse дrin (stc,m2). op step3 sts(r:G)m2= let (m,gc,hkey) = stsin let e= (H(hkey,m2r)⊕m0, H(hkey,(gc/m2)r)⊕m1) in let m3= (дr,e) in m3. op finalize stcm3= let (b,hkey,x) = stcin let (gr,e)=m3in let res = H(hkey,grx)⊕ebin res. clone OTProt as SomeOT with type rand1=Garray, type rand2= (Garray ∗G)∗G, op prot (b:input1) (rc:rand1) (m:input2) (rs:rand2) = let (sts,m1) = step1 m(fst rs) in let (stc,m2) = step2 b rcm1in let m3= step3 sts(snd rs)m2in let res = finalize stcm3in let conv = (m1,m2,m3) in (conv,(res,())). Figure 5: A Concrete Oblivious Transfer Protocol. We prove this protocol secure in the standard model via a reduction to the decisional Diffie-Hellman assumption and an entropysmoothing assumption on the hash function. We let AdvDDH(A) and AdvES(A) be the advantage of an adversary A breaking the DDH and the Entropy Smoothing assumptions, respectively. Theorem 2.2 ( OT -security of SomeOT). For all i∈ { 1 , 2 } and OTi adversary Ai of type AdvOT i against the SomeOT protocol, we can construct two efficient adversaries DDDH and DES , and a efficient simulator Ssuch that AdvOTi SomeOT,S(Ai)≤n·AdvDDH(DDDH)+n·AdvES(DES). In the proof of Theorem 2.2, both reductions first go to n -ary versions of the DDH and Entropy-Smoothing hypotheses before reducing these further to standard assumptions using the generic hybrid argument lemma. Extraction and Micro Benchmarks. Our verified implementation of Yao’s protocol is obtained via the extraction mechanism included in recent versions of EasyCrypt. The only exceptions to this are the low-level operations left abstract in the formalisation, namely: i. abstract core libraries for randomness generation, the cyclic group algebraic structure, a PRF relying on AES and the entropy-smoothing hash of SomeOT . These are implemented using Table 1: Timings (ms): P1 and P2 denote the parties, S1 and S2 the SFE protocol stage; TTime denotes total time, OT the time for OT computation, GT the garbling time and ET the evaluation time. Circuit NGatesTTimeP2 S1 GTP2 S1 OTP1 S1 OTP2 S2 OTP1 S2 OTP1 S2 ET COMP32 301 272 1 54 53 109 53 0.3 ADD32 408 275 1 55 54 112 53 0.5 ADD64 824 545 3 109 107 217 106 1 MUL32 12438 329 44 98 54 111 54 10 AES 33744 1233 118 345 216 435 215 24 SHA1 106761 2638 349 780 431 868 430 77 the CryptoKit library; 9 and ii. a wrapper that handles parameter passing (circuits, messages and input/output) and calls the extracted SFE code. We fix the bound con circuit sizes to be the largest OCaml integer (2 k-1- 1on a k -bit machine) allowing us to represent circuits without having to use arbitrary precision arithmetic whilst remaining large enough to encode all practical circuits. We use this same value to instantiate n. We conclude this section with microbenchmarking results focusing only on the extracted OCaml implementation. Our results show that, whilst being slower than (unverified) optimized implementations of SFE that use similar cryptographic techniques [ 11 , 35 , 40 , 56 ], the performance of the extracted program is compatible with real-world deployment, providing evidence that the (unavoidable) overhead implied by our code extraction approach is not prohibitive. The overhead of our solution is not intrinsic to the verification and extraction methodology. Indeed, the more modern (unverified) implementations showing significant improvements rely on either cryptographic optimizations [ 35 ] or on new SFE protocols [ 56 ]. Moreover, although these changes have implications on the security proofs, these can be addressed using the same techniques presented here to obtain a verified implementation that benefits from these recent cryptographic advances. In addition to the overall execution time of the SFE protocol and the splitting of the processing load between the two involved parties, we also measure various speed parameters that permit determining the weight of the underlying components: the time spent in executing the OT protocol, and the garbling and evaluation speeds for the garbling scheme. Our measured execution times do not include serialization and communication overheads nor do they include the time to sample the randomness, all of which we account for in Section 4. Our measurements are conducted over circuits made publicly available by the cryptography group at the University of Bristol, 10 precisely for the purpose of enabling the testing and benchmarking of multiparty-computation and homomorphic encryption implementations. A simple conversion of the circuit format is carried out to ensure that the representation matches the conventions adopted in the formalization. We run our experiments on an x86-64 Intel Core i5 clocked at 2.4 GHz with 256KB L2 cache per core. The extracted code and parser are compiled with ocamlopt version 4.02.3. The tests are run in isolation, using the OCamlSys.time operator for time readings. We run tests in batches of 100 runs each, noting the median of the times recorded in the runs. 9See http://forge.ocamlcore.org/projects/cryptokit/ 10http://www.cs.bris.ac.uk/Research/CryptographySecurity/MPC/ A subset of our results is presented in Table 1, for circuits COMP32 (32-bit signed number less-than comparison), ADD32 (32-bit number addition), ADD64 (64-bit number addition), MUL32 (32-bit number multiplication), AES (AES block cipher), SHA1 (SHA-1 hash algorithm). The semantics of the evaluation of the arithmetic circuits is that each party holds one of the operands. In the AES evaluation we have that P1 holds the 128-bit input block, whereas P2 holds the 128-bit secret key. Finally, in the SHA1 example we model the (perhaps artificial) scenario where each party holds half of a 512-bit input string. We present the number of gates for each circuit as well as the execution times in milliseconds. A rough comparison with results for unverified implementations of the same protocol such as, say, that in [ 40 ] where an execution of the AES circuit takes roughly 1.6 seconds (albeit including communications overhead and randomness generation time), allows us to conclude that real-world applications are within the reach of the implementations our approach generates. Furthermore, additional optimization effort can lead to significant performance gains, e.g., by resorting to hardware support for low-level cryptographic implementations as in [ 11 , 56 ], or implementing garbled-circuit optimizations such as those allowed by XOR gates or component based garbled-circuits [ 35 , 42 ]. Indeed, we do not aim or claim to produce the fastest implementation of Yao’s protocol, but simply to demonstrate that the new formal verification techniques that we introduce open the way to verifying a whole new class of provable security arguments, where modularity, abstraction, and composition (e.g., hybrid arguments) mechanisms are essential to dealing with scale and complexity. 3 CERTIFIED BOOLEAN CIRCUIT COMPILER In this section we describe a new certified compiler called CircGen that can convert (a large subset of) C programs into Boolean circuit descriptions. This is a self-contained, standalone tool that can be used in arbitrary contexts where computation needs to be specified as Boolean circuits. By a certified compiler we mean a compiler that is coupled with a formal proof asserting that the semantics of the source program is preserved through the compilation process. In other words, whenever the source program exhibits a well-defined behavior on some input, the behavior of the target program will match it. The tool is based on the CompCert certified compiler [ 43 ], ensuring the adoption of a widely accepted formal semantics for the C language. Relevant CompCert features. CompCert is in fact a family of compilers for implementations of the C programming language for various architectures (PowerPC, ARM, x86). It is moderately optimizing, sometimes compared to GCC at optimization level 1 or 2. It is formally verified: the semantics of the programming languages involved in the compiler (in particular C and the assembly languages) are formally specified; and correctness theorems are proved. The correctness of a compiler is stated as a behavior inclusion property: each possible behavior of the target program is a possible behavior of the source program. A behavior of a program is a (maybe infinite) sequence of events that describe the interactions of the program with its environment. For the current prototype we have adapted the 2.5 distribution of CompCert.11 11http://compcert.inria.fr/ Figure 6: Architecture of the certified compiler CircGen 3.1 CircGen architecture The meaning of a C program is normally specified as a set of traces that captures the interactions with the execution environment triggered by the execution of the program (I/O of data, calls to the operating system, ...). In order to match it with the behavior of evaluating a Boolean circuit, we need to be somewhat more strict on the semantics of programs and, consequently, on the class of programs deemed acceptable to be translated by the tool. The overarching assumption underlying CircGen is that the input C program is coupled with a specification of two memory regions (an input region and an output region) and that we are able to identify the meaning of the C program with a Boolean function acting on those memory regions. The tool should then generate a circuit implementing that specific Boolean function, thus capturing the meaning of the source program. The CircGen architecture is shown in Figure 6. It is split in two components: i. the front-end, whose task is to convert the source program into an intermediate language that has been tailored to already admit a Boolean circuit interpretation; and ii. the backend, that formalises the intended Boolean circuit interpretation of programs, and carries out the (certified) transformations up to an explicit Boolean circuit. In other words, the front-end will reject programs for which it cannot determine that there exists a valid Boolean circuit interpretation; whereas the back-end will make explicit the Boolean circuit interpretation. The front-end follows closely the first few compilation passes of CompCert, adapting and extending it to meet the specific requirements imposed by our domain. We develop and verify the back-end from scratch. 3.2 C features/usage restrictions The driving goal in our design is to let the programmer use most of the C language constructs (memory, functions, control structures such as loops and conditional branches, ...) that are convenient to program complex, large circuits. However, in our presentation we will use a very simple running example. The circuit that compares its two inputs to decide which is the largest can be described by the C program shown in Figure 7 (function millionaires). In order to be correctly handled by the compiler, the program specifying the circuit must be wrapped in a main function that declares what are the inputs and the outputs of the circuit. The declaration of inputs and outputs also allows us to state the correctness of the compiler; intuitively, the trace of this program will include the Table 2: CircGen features/restrictions Features Recursion × GOTO’s × Dynamic memory × Static memory ✓ Loop unfolding ✓ Integer computations ✓ Non-integer computation × incoming inputs and the outgoing outputs of the produced circuit. The dedicated header file provides convenient macros. Note that boolean circuits produced by our compiler are “party-agnostic”. In the workflow, one specifies which input bits correspond to each party only when providing the circuit to underlying frameworks. #include "circgen.h" int millionaires(int x, int y) { if (x < y) return 1; else return 0; } int main(void) { static int a, b, result; AddInput(a); AddInput(b); BeginCirc(); result = millionaires(a, b); EndCirc(); AddOutput(result); return 0; } Figure 7: Example C program Assumptions on Input Programs. We start by enumerating natural high-level restrictions imposed on input programs: i. the program must consist of a single compilation unit; ii. input and output memory regions must be properly identified; iii. any feature that produces observable events under CompCert’s semantics is disallowed (e.g. volatile memory accesses; external calls; inline assembly; etc); and iv. so far, only integral types are allowed. A summary of the most relevant features and restrictions of CircGen can be found in Table 2. The fragment of C that we support is aligned with similar tools. Most of the limitations at this level are inherent to the problem of describing programs as (relatively small) Boolean circuits. Functions. The source C program can be structured in different functions, but the tool will force all function calls to be inlined (independently of the presence of the inline keyword in function headers). As a consequence, we exclude any form of recursion in source programs (either direct or indirect). In practical terms, we adapt the function inlining pass of CompCert, which refuses to inline any kind of recursive function (each time it inlines a function f, it removes ffrom the context). Therefore, this restriction amounts to enforcing that, after inlining, the program entry point does not include function calls. Control structure and termination. In order to extract a Boolean function from a C program we need to enforce termination on all possible inputs. Since recursion has already been excluded, possible non-terminating behavior can only be caused by C loop statements or unstructured use of gotos. For loops, we consider a main() { x18 = volatile load int8u(&__circgen_io) int8u[a] = x18 x18 = volatile load int8u(&__circgen_io) int8u[a + 1] = x18 . . . int8u[b + 3] = x335 x9 = __circgen_fence() –: x7 = int32[a] x8 = int32[b] if (x7 <s x8) goto 14 else goto 13 14: x332 = 1; goto 12 13: x332 = 0 12: int32[result] = x332 x6 = __circgen_fence() x329 = int8u[result] _ = volatile store int8u(&__circgen_io, x329) . . . x323 = int8u[result + 3] _ = volatile store int8u(&__circgen_io, x323) x2 = 0 return x2 } Figure 8: Front-end RTL output specific compiler pass that attempts to remove them by a suitable number of unfoldings (detailed below). We choose not to support gotos in the tool; in particular, any attempt to build a loop using gotos will cause the program to be rejected. Variables and memory. During the conversion of C programs into Boolean circuits, variables need to be converted into wires connecting gates. Specifically, each live range of a variable gives rise to a set of wires (with the number of wires matching the number of bits stored in the variable)—writing to a variable means that the wires corresponding to that variable originate in the output ports of some gate that produces the value to be stored; and reading from a variable means that the associated wires are connected to the input wires of some gate that is consuming the variable value to perform an operation. Memory accesses to fixed locations behave (in this respect) similarly to variables: a store and load to a fixed location correspond to a write and read of a specific variable, respectively. Memory accesses can, however, be subtler when the location of the access (address) depends on additional data, as in the case of indexed memory accesses (e.g., array operations). When reading from such a composite address, one is led to a selection of specific wires from a much larger pool of wires, which amounts to a multiplexing operation in Boolean circuit jargon. Conversely, storing to an indexed address is akin to a demultiplexer gate. The problem lies in the fact that these (meta-)gates are very expensive if built from elementary logic operations, leading to exponential circuit sizes on the number of selection bits. This clearly makes unrestricted (32-bit) indices out of reach, leading to the necessity of adopting a strategy to bound them to reasonable limits. We therefore exclude any form of dynamic memory allocation (both in the heap and in the stack) and consider only programs that i. allocate memory statically; and ii. for which memory usage is determined at compile-time. 3.3 Front-end compiler passes The front-end of CompCert, for the most part unchanged, is used to parse, unroll loops, inline functions, and perform general optimizations at the Register Transfer Language (RTL) level (constant propagation, common subexpression elimination, and redundancy elimination). The RTL intermediate representation produced by the front-end for the example input program of Figure 7 is given in Figure 8. We can observe that, because of inlining, only the main function is left. It starts with a sequence of volatile loads that take the circuit inputs from the environment into the designated global variables, one octet at a time. Then, following the code of the circuit (between the lines marked ‘–’ and ‘12’, in red on the Figure), comes a final sequence of volatile stores that sends the circuit outputs to the environment, one octet at a time. These three sections of the RTL program are delimited by dummy external calls (to __circ- gen_fence ); they block any optimization across these boundaries that could prevent the correct recognition of inputs and outputs in the next compilation pass. Loop unroll. The loop-elimination pass is split into two elementary transformations: i. one that unrolls the loop by an arbitrary number of iterations, but leaves the loop unchanged at the end; and ii. one that establishes that the loop kept after all the unrollings is indeed redundant (i.e., that it is unreachable). By doing this, we simplify significantly the semantic preservation proof, since the first transformation follows directly from the operational semantics of loops and is always sound, independently of the number of unrolls. The second transformation can be seen as a specific instance of dead-code elimination. We implement the first transformation as a new compiler pass in CompCert and prove its semantic preservation theorem. This pass is performed at the Cminor intermediate language since it has a unified treatment for all C loop constructors, but still retains enough structure in the loops to support a simple semantic preservation proof. The number of unfolds for each loop is received by the tool as external advice. For the second transformation we rely on the pre-existing dead code elimination pass of CompCert to remove the remaining loops that are kept after the unfolds. Note that dead code elimination is performed after loop unrolling, function inlining and constant propagation passes, which ensures that loops with simple control structure are successfully eliminated as dead-code (provided that sufficient large unroll estimates are given at the loop unroll pass; otherwise compilation will fail). To make this transformation more effective, we had to slightly improve the abstract domain used in CompCert’s value analysis to improve the accuracy of the constant-propagation pass. 3.4 Back-End compiler passes RTL Circuits. The first intermediate language of the back-end is a variant of RTL that we have called RTLC (RTL Circuits). The language is itself very similar to RTL, with the exception that the control-flow is enforced by conditional execution. Specifically, each conditional test is assigned to a propositional variable. These propositional variables are then used to build path-condition formulas that are assigned to each instruction; the execution of each instruction is conditioned on the validity of a path condition that encodes the combination of branches that can possibly lead to it. Note that RTLC retains all the memory accesses from RTL, that is, writes and reads to and from global variables and stack data. The semantics of RTLC is sequential (each and every instruction is evaluated following the order of appearance in the program), but the execution of an instruction is guarded by the corresponding INPUTS: a[0..3] b[0..3] OUTPUTS: result[0..3] x6 = int32[a] | T x7 = int32[b] | T test b14 = x6 <s x7 | T x16 = 1 | b14 x16 = 0 | ¬b14 int32[result] = x16 | T INPUTS: a[0..3] b[0..3] OUTPUTS: result[0..3] 0: int32[a] | 1: int32[b] | 2: w0 <s w1 | T 3: 1 | 4: 0 | 5: (w2?w3:w4) | 6: int32[result] := w5 | T Figure 9: Guarded instructions instead of control-flow (left) and corresponding SSA conversion (right). path condition. We have adopted Ordered-Reduced Binary Decision Trees [ 23 ] as canonical representatives of path-conditions, where nodes are tagged with propositional variables (branching points) and leaves are Boolean values. Figure 9 (left) shows the test program after the path-condition computation pass. Path-conditions are the guards shown at the end of each line (propositional variables are denoted by their index). From RTL to RTLC. The translation from RTL to RTLC amounts essentially to the computation of path-conditions for every instruction in the program. This computation is part of the RTL structural validation that occurs as the final pass of the compiler front-end component. This validation ensures that a Boolean circuit interpretation can be assigned to the RTL program, making it ready to be processed by the CircGen back-end. This is accomplished by a traversal of the control-flow graph in topological order that: i. identifies boundaries of the three segments of the program (sequence of inputs, body, and sequence of outputs); ii. checks that the body only includes forward jumps; and iii. checks that it does not execute any unsupported instruction (function call, volatile memory access, etc.). Note that check ii. ensures that the control-flow graph is acyclic, which in particular validates that every loop was discharged by the redundancy elimination pass. Path conditions for the instructions of the body are also constructed during this traversal by applying the following rules: i. initially, all instructions have the ⊥ path condition (unreachable instruction), except for the first instruction of the body that is assigned the ⊤ path condition (unconditionally executed); ii. when a nonbranching instruction is visited, its path condition is propagated to its successor (joining it with any previously computed path condition for that program point); and iii. when a branching instruction (condition test) is visited, the corresponding propositional variable (resp. its negation) is added to the path condition which gets propagated to the then successor (resp. the else successor). Constant Expansion. The guarded execution model of RTLC is particularly well-suited to perform an optimization with significant impact on the size of the resulting circuit for certain classes of C programs: for some operations it is possible to determine that their arguments will be constant once the execution path is fixed. For those operations we expand the associated instruction into multiple instances with constant arguments, and use the associated pathconditions to differentiate between the paths. In our implementation we have instrumented this optimization exclusively for memory operations; the impact for algorithms that rely on array indexing clone Protocol as OT with type input1=bool array, type output1= msg array, type leak1=int, type input2= (msg ∗msg) array, type output2=unit, type leak2=int, op ϕ1(i1:bool array) = length i1, op ϕ2(i2: (msg ∗msg) array) = length i2, op f (i1:bool array) (i2: (msg ∗msg) array) = i1i2. op validInputs(i1:bool array) (i2: (msg ∗msg) array) = 0 < length i1≤nmax ∧length i1= length i2, . . . Figure 13: Instantiating Two-Party Protocols. non-adaptive adversary). We omit module types for the randomness generators R1 and R2 , as they only provide a single procedure gen taking some leakage and producing some randomness. We also omit the dual security game for Party 2. The security game, modelled as module Sec1 , is explicitly parameterized by two randomness-producing modules R1 and R2 , a simulator S1 and an adversary A1 . This enables the code of procedures defined in Sec1 to make queries to any procedure that appears in the module types of its parameters. However, they may not directly access the internal state or procedures that are implemented by concrete instances of the module parameters, when these are hidden by the module type. We omit the indices representing randomness generators whenever they are clear from the context. The game implements, in a single experiment, both the real and ideal worlds. In the real world, the protocol prot is used with adversary-provided inputs to construct the adversary’s view of the protocol execution. In the ideal world, the functionality is used to compute Party 1’s output, which is then passed along with Party 1’s input and Party 2’s leakage to the simulator, which produces the adversary’s view of the system. We prevent the adversary from trivially winning by denying it any advantage when it chooses invalid inputs. A two-party protocol prot (parameterized by its randomnessproducing modules) is said to be secure with leakage Φ=(ϕ1,ϕ2) whenever, for any adversary Ai implementing AdvProt i ( i∈{1,2} ), there exists a simulator Siimplementing Simisuch that AdvProti,Φ prot,Si,R1,R2(Ai)=|2·Pr[Seci(R1,R2,Si,Ai):res]−1| is small, where res denotes the Boolean output of procedure main. Intuitively, the existence of such a simulator S i implies that the protocol conversation and output cannot reveal any more information than the information revealed by the simulator’s input. Oblivious Transfer Protocols. We can now define oblivious transfer, restricting our attention to a specific notion useful for constructing general SFE functionalities. To do so, we clone the Protocol theory, which makes a literal copy of it and allows us to instantiate its abstract declarations with concrete definitions. When cloning a theory, everything it declares or defines is part of the clone, including axioms and lemmas. Note that lemmas proved in the original theory are also lemmas in the clone. The partial instantiation is shown in Figure 13. We restrict the input, output and leakage types for the parties, as well as the leakage functions and the functionality f . The chooser (Party 1) takes as input a list of Boolean values (i.e., a bit-string) she needs to encode, and the sender (Party 2), takes as input a list of pairs of messages (which can also be seen as alternative encodings for the Boolean values in Party 1’s inputs). Together, they compute the array encoding the chooser’s input, revealing only the lengths of each other’s inputs. We declare an abstract constant n that bounds the size of the chooser’s input. This introduces an implicit quantification on the bound nin all results we prove. Defining OT security is then simply a matter of instantiating the general notion of security for two-party protocols via cloning. Looking ahead, we use AdvOTi to denote the resulting instance of AdvProti,Φ , where Φ=(length,length) , and similarly we write AdvOT ithe types for adversaries against the OT instantiation. Garbling schemes. Garbling schemes [ 12 ] (Figure 14) are operators on functionalities of type func . Such functionalities can be evaluated on some input using an eval operator. In addition, a functionality can be garbled using three operators (all of which may consume randomness). funG produces the garbled functionality, inputK produces an input-encoding key, and outputK produces an output-encoding key. The garbled evaluation evalG takes a garbled functionality and some encoded input and produces the corresponding encoded output. The input-encoding and output-decoding functions are self-explanatory. In practice, we are interested in garbling functionalities encoded as type func, input, output. op eval : func →input →output. op valid: func →input →bool. type rand, funcG, inputK, outputK. op funcG : func →rand →funcG. op inputK : func →rand →inputK. op outputK: func →rand →outputK. type inputG, outputG. op evalG : funcG →inputG →outputG. op encode: inputK →input →inputG. op decode: outputK →outputG →output. Figure 14: Abstract Garbling Scheme. Boolean circuits and therefore fix the func and input types and the eval function. Circuits themselves are represented by their topology and their gates. A topology is a tuple (n,m,q,A,B) , where n is the number of input wires, m is the number of output wires, q is the number of gates, and A and B map to each gate its first and second input wire respectively. A circuit’s gates are modelled as a map G associating output values to a triple containing a gate number and the values of the input wires. Gates are modelled polymorphically, allowing us to use the same notion of circuit for Boolean circuits and their garbled counterparts. We only consider projective schemes [ 12 ], where Boolean values on each wire are encoded using a fixed-length random token. This fixes the type funcG of garbling schemes, and the outputK and decode operators. Following the Garble1 construction of Bellare et al. [ 12 ], we construct our garbling scheme using a variant of Yao’s garbled circuits based on a pseudo-random permutation, via an intermediate Dual- Key Cipher (DKC) construction. We denote the DKC encryption type leak. op Φ: func →leak. module type Sim = { fun sim(x: output, l: leak): funcG ∗inputG }. module type AdvGb = { fun choose(): func ∗input fun distinguish(F: funcG, X: inputG) : bool }. module SIM(R: Rand, S: Sim, A:AdvGb)={ fun main() : bool = { var real, adv, f, x, F, X; (f,x) = A.gen_query(); real ←${0,1}; if (!valid f x) adv ←${0,1}; else { if (real) { r = R.gen(Φf); F = funcG f r; X = encode (inputK f r) x; }else { (F,X) = S.sim(f(x),Φf); } adv = A.dist(F,X); } return (adv = real); } }. Figure 16: Security of garbling schemes. with E , and DKC decryption with D . Both take four tokens as argument: a tweak that we generate with an injective function and use as unique IV, two keys, and a plaintext (or ciphertext). We give functional specifications to the garbling algorithms in Figure 15. For clarity, we denote functional folds using stateful for loops. type topo = int ∗int ∗int ∗int array ∗int array. type αcircuit = topo ∗(int ∗α∗α,α)map. type leak = topo. type input, output = bool array. type func = bool circuit. type funcG = token circuit. type inputG, outputG = token array. op evalG f i = let ((n,m,q,A,B),G)=fin let evalGate = λg x1x2, let x1,0= lsb x1and x2,0= lsb x2in D (tweak g x1,0x2,0) x1x2G[g,x1,0,x2,0] in let wires = extend i q in (∗extend the array with q zeroes ∗) let wires = map (λg, evalGate g A[g] B[g]) wires in (∗decrypt wires ∗) sub wires (n + q −m) m. type rand, inputK = ((int ∗bool),token) map. op encode iK x = init (length x) (λk, iK[k,x[k]]). op inputK (f:func) (r:((int ∗bool),token) map) = let ((n,_,_,_,_),_) = f in filter (λx y, 0 ≤fst x < n) r. op funcG (f:func) (r:rand) = let ((n,m,q,A,B),G)=fin for (g,xa,xb)∈[0..q] ∗bool ∗bool let a = A[g] and b = B[g] in let ta= r[a,xa] and tb= r[b,xb] in H G[g,ta,tb] = E (tweak g tatb) tatbr[g,G[g,xa,xb]] ((n,m,q,A,B), H G). Figure 15: SomeGarble: our Concrete Garbling Scheme. Security of Garbling Schemes. The privacy property of garbling schemes required by Yao’s SFE protocol is more conveniently captured using a simulation-based definition. Like the security notions for protocols, the privacy definition for garbling schemes is parameterized by a leakage function upper-bounding the information about the functionality that may be leaked to the adversary. (We consider only schemes that leak at most the topology of the circuit.) Consider efficient non-adaptive adversaries that provide two procedures: i. choose takes no input and outputs a pair (f,x) composed of a functionality and some input to that functionality; ii. on input a garbled circuit and garbled input pair (F,X) , distinguish outputs a bit b representing the adversary’s guess as to whether he is interacting with the real or ideal functionality. Formally, we define the SIM-CPAΦ advantage of an adversary A of type AdvGb against garbling scheme Gb =(funcG,inputK,outputK) and simulator Sas AdvSIM-CPAΦ Gb,R,S(A)=|2·Pr[SIM(R,S,A):res]−1|. A garbling scheme Gb using randomness generator R is SIM-CPAΦ - secure if, for all adversary A of type AdvGb , there exists an efficient simulator Sof type Sim such that AdvSIM-CPAΦ Gb,R,S(A)is small. Following [ 12 ], we establish simulation-based security via a general result that leverages a more convenient indistinguishabilitybased security notion denoted IND-CPAΦtopo : we formalize a general theorem stating that, under certain restrictions on the leakage function Φ , IND-CPAΦ -security implies SIM-CPAΦ security. This result is discussed below as Lemma A.1. A modular proof. The general lemma stating that IND-CPA -security implies SIM-CPA -security is easily proved in a very abstract model, and is then as easily instantiated to our concrete garbling setting. We describe the abstract setting to illustrate the proof methodology enabled by EasyCrypt modules on this easy example. module type AdvIND = { fun choose(): ptxt ∗ptxt fun distinguish(c:ctxt): bool }. module IND (R:Rand, A:AdvIND)={ fun main(): bool = { var p0, p1, p, c, b, b', ret, r; (p0,p1) = A.choose(); if (valid p0∧valid p1∧Φp0=Φp1) { b←${0,1}; p = if bthen p1else p0; r = R.gen(|p|); c = enc p r; b'=A.distinguish(c); ret = (b = adv); } else ret ←${0,1}; return ret; } }. Figure 17: Indistinguishability-based Security for Garbling Schemes. The module shown in Figure 17 is a slight generalization of the standard IND-CPA security notions for symmetric encryption, where some abstract leakage operator Φ replaces the more usual check that the two adversary-provided plaintexts have the same length.We formally prove an abstract result that is applicable to any circumstances where indistinguishability-based and simulation-based notions of security interact. We define the IND-CPA advantage of an adversary A of type AdvIND against the encryption operator enc using randomness generator Rwith leakage Φas AdvIND-CPAΦ enc,R(A)=|2·Pr[Game_IND(R,A): res] −1| where Ris the randomness generator used in the concrete theory. In the rest of this subsection, we use the following notion of invertibility. A leakage function Φ on plaintexts (when we instantiate this notion on garbling schemes these plaintexts are circuits and their inputs) is efficiently invertible if there exists an efficient algorithm that, given the leakage corresponding to a given plaintext, can find a plaintext consistent with that leakage. Lemma A.1 ( IND-CPA -security implies SIM-CPA -security). If Φ is efficiently invertible, then for every efficient SIM-CPA adversary A of type AdvGb , one can build an efficient IND-CPA adversary B and an efficient simulator Ssuch that AdvSIM-CPAΦ enc,S(A)=AdvIND-CPAΦ enc (B). Proof (Sketch). Using the inverter for Φ , B computes a second plaintext from the leakage of the one provided by A and uses this as the second part of her query in the IND-CPA game. Similarly, simulator Sgenerates a simulated view by taking the leakage it receives and computing a plaintext consistent with it using the Φ -inverter. The proof consists in establishing that A is called by B in a way that coincides with the SIM-CPA experiment when Sis used in the ideal world, and is performed by code motion. □ Finishing the proof. We reduce the IND-CPAΦtopo -security of SomeGarble to the DKC -security of the underlying DKC primitive (see [ 12 ]). In the lemma statement, c is an abstract upper bound on the size of circuits (in number of gates) that are considered valid. The lemma holds for all values of c that can be encoded in a token minus two bits. Lemma A.2 (SomeGarble is IND-CPAΦtopo -secure). For every efficient IND-CPA adversary A of type AdvGb−IND , we can construct a efficient DKC adversary Bsuch that AdvIND-CPAΦtopo SomeGarble (A)≤(c+1)·AdvDKC SomeGarble(B). Proof (Sketch). The constructed adversary B , to simulate the garbling scheme’s oracle, samples a wire ℓ0 which is used as pivot in a hybrid construction where: i. all tokens that are revealed by the garbled evaluation on the adversary-chosen inputs are garbled normally, using the real DKC scheme; otherwise ii. all tokens for wires less than ℓ0 are garbled using encryptions of random tokens (instead of the real tokens representing the gates’ outputs); iii. tokens for wire ℓ0 uses the real-or-random DKC oracle; and iv. all tokens for wires greater than ℓ0are garbled normally. Here again, the generic hybrid argument (Figure 4) can be instantiated and applied without having to be proved again, yielding a reduction to an adaptive DKC adversary. A further reduction allows us to then build a non-adaptive DKC adversary, since all DKC queries made by Bare in fact random and independent. □ From Lemmas A.1 and A.2, we can conclude with a security theorem for our garbling scheme. Theorem A.3 (SomeGarble is SIM-CPAΦtopo -secure). For every SIM-CPA adversary A that implements AdvGb , one can construct an efficient simulator Sand a DKC adversary Bsuch that AdvSIM-CPAΦtopo SomeGarble,S(A)≤(c+1)·AdvDKC SomeGarble(B). Proof (Sketch). Lemma A.1 allows us to construct from A the simulator S and an IND-CPA adversary C . From C , Lemma A.2 allows us to construct Band conclude. □