Fine and DCIL Secure programming on .NET Nikhil Swamy http://research.microsoft.com/fine Joint work with Juan Chen and Ravi Chugh Secure distributed programming Users download code to browser, phone, etc. Also upload programs to cloud – JavaScript, Flash, Silverlight, Java, .NET, Python, … – Mostly memory-safe languages But, memory safety is not enough for security – Browser+extensions still enforces Same-Origin Policy? – Is entire cloud-hosted DB visible to a user program? Want automated security verification 2 Security-typed programming Language support for security verification Prove software secure by construction 15+ years of research producing MANY Models of secure computation Policy languages Typing disciplines Which model, policy language and type system to pick for secure cloud computing? 3 What’s your favorite flavor? 4 Flavors of security Information flow Label model? Atomic, decentralized, role-based, … Explicit flows + implicit flows? Explicit only? Termination (in)sensitive? Plus declassification Many dimensions, many flavors in each dimension … Access control But which authorization logic? XACML, SecPAL, DKAL, DCC, SD3, Binder, Ponder, RT, … Stateless, history-based, ... Auditing Cryptographic evidence? Explicit proof terms? 5 6 Which flavors to bake into a language? The answer in Fine: None Instead A few general purpose constructs Flexible enough to capture many security idioms 7 What is Fine? A subset of F# with a type system designed around Value-indexed types secretString: labeled<string, High> Dependent refinement types getEmail: p:plugin -> {e:email | CanRead p e } -> string Affine (use-at-most-once) types – Useful for modeling state 8 Why Fine? Why not Coq, Agda, …? 9 DCIL: Type system for .NET bytecode The target language for the Fine compiler – Fine to DCIL translation is type-preserving DCIL backwards compatible with CIL Fine’s type system carefully designed to match what is possible TODAY on the .NET VM Coq, Agda, even Haskell, can’t be compiled to .NET (with high fidelity) 10 Example applications Lookout: A model of a plugin-based email client – Verify that .NET DLLs for plugins: • Respect user’s authorization policy • Never leak email from one contact to another HealthWeb: A model health-record mgmt. website on Windows Azure – Web interface in ASP.NET and C# – Data tier in F#/SQL Server – Reference monitor for data tier verified using in Fine Currently underway – Secure browser extensions for IE – Secure program marshaling – Crypto protocol verification 11 Plan A brief primer on Fine, the structure of our compiler, and experiments A more in-depth look at – Information flow – Stateful authorization Demo: Fine + DCIL on Azure Wrap up 12 Current practice Specifying and enforcing XACML policies <Resource> XACML Policy <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> <ResourceAttributeDesignator AttributeId="resource:datastream:id“ DataType=“…/XMLSchema#string"/> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">PatientRecord</AttributeValue> </ResourceMatch> Resources: patient-records </Resource> <Action> Actions: getData, … <ActionMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">action:getData</AttributeValue> </Action> <Subject> <SubjectMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Doctor</AttributeValue> </SubjectMatch> Subjects: Doctors, … </Subject> <Rule RuleId="1" Effect="Deny"> <Target> … </Target> <Condition> ... </Condition> </Rule> <Rule RuleId=“2" Effect=“Permit"> <Target> … </Target> <Condition> ... </Condition> </Rule> Rules: Grant, Deny, … Does this code properly enforce the policy? Complete mediation? Is this the right query with right parameters? public Data GetData (string subjectName, string recId) { Record rec = DB.GetRecord (subjectName, recId); List queryParams = new {subjectName, rec.datastreamId}; if (XACML.GetAuthCtxt(subjectName).query(“CanGetData”, queryParams)) { return rec.data; } return null; 13 } C# code that mediates access to patient records Fine: Specify and enforce security policies A reference monitor written in Fine Policy specified using logical formulas in a header file assume Rule_docCanRead: forall p:prin, r:record. (InRole<p,Doctor> && Treating<p, r.patient>) => HasPerm<p, CanRead r> assume … Types mention security constraints from policy val readRecord: p:prin -> cred<p> -> {r:record | HasPerm<p, CanRead r>} -> string Type checker ensures authenticity, The type of a function to read complete mediation, information hiding data from a protected record 14 Security verification by type checking module RequestMgr let rec hdlreq () = match next_request () with | p, cred, GetRecordContents r -> let test = checkRole p Doctor && checkTreating p r.patient in if test then Query the policy let record_data = HealthDB.readRecord p cred r in Read records only if respond record_data; test succeeds hdlreq () elseRequestMgr.fine (9.10) – (9.43): Expected Type error {r:recordrespond | HasPerm <p, CanRead r>} insufficient privilege”); (Denied “Sorry, Got evtloop () record 15 Structure of our compiler Fine Z3 Type-checker + Compiler Fine: Functional language with refinement types getEmail: p:plugin -> {e:Email | CanRead<p,e> } -> string Type-checked using Z3 (SMT solver) • Simplifies programming • Extract typeable proof terms from Z3 • Proofs flexible for a variety of logics DCIL DCIL Type-Checker C#, F#,… DCIL .NET Virtual Machine DCIL: Type system for functional core of .NET bytecode • Purely syntactic verification (solver not in TCB) • Verification is fast • Executable on stock .NET VM 16 Reference monitors for example programs An interpreter for (a fragment of) the DKAL authorization logic -- Refinements ensure that substitutions of quantified assumptions An automaton based policy for aaccess control ontracks files A reference monitor filesystem that andpolicy rules are outcorrect A module implementing a lattice-based information flow -- similar to typestateflows tracking illegal information between files 17 Reference monitors for example programs Lookout: A plugin-based email client Reference monitors are for managing a database of a A model of HealthVault, a website A model of the Continue conference management server Tooand many proof terms to Ancompact. auto-generated library of commonly proofs lemmas -- plugins subject to a No stateful authorization and used need to health records --information Stateful authorization policy structured into 9alone, phases, kinds ofhand. actions write by Automation -- verified by pure type checking no 12 use of Z3 flow tracking policy write your whole Web interface in ASP.NET and C# via Z3 is key. application in Fine. Back end in F# and a SQL Server database 18 Translating to DCIL Verifying Compilation DCIL programs times are isstill fast. high. Syntax Includes time spent in code size 2x – 50x Increase directed in Z3, and verification extracting of programs and verifying and proof proofsterms Z3 often produces very verbose proofs Preliminary experiments with SS a custom proof-producing first-order prover yield 25x improvement Increase in code size with Z3 proof: 50x Increase in code size with SS proof: 2x 19 Benefits of compiling with proofs Security verification for mobile code Translation validation for Fine compiler Proof-carrying and code-carrying authorization (Appel & Felten; Maffeis et al.) Verifiable audit trails (Zdancewic et al.) – Log proof terms in support of post-hoc reconstruction of authorization decisions Secure marshaling – DCIL as a verifiable serialization format 20 Plan A brief primer on Fine, the structure of our compiler, and experiments A more in-depth look at – Simple access control – Information flow – Stateful authorization Demo: Fine + DCIL on Azure Wrap up 21 Fine: Simple access control on files Develop a reference monitor for a file system – Enforces a simple access control policy Main idea: Give privileged operations refined types to capture their pre- and post-conditions Principal p authenticated by this credential val fread: p:prin -> credential<p> -> {f:file | CanRead<p,f> } -> string The type of file handles f for which the (CanRead<p, f>) proposition is valid Type check reference monitor to ensure that every call of fread is protected by a suitable check 22 Fine: Simple access control on files type file type prin = Alice | Bob | Admin type credential<prin> login has a dependent function type Constructs a credential for p if the password check succeeds credential<p> is a value-indexed type credential<Alice> is the type of a credential authenticating Alice. Types ensure that this cannot be confused as a credential for Bob. val login: p:prin -> pw:string -> option<credential<p>> type CanRead<prin,file> The CanRead predicate is a binary type constructor assume AdminCR: forall (f:file). CanRead<Admin, f> assume AliceCR: … val fread: p:prin -> credential<p> -> {f:file | CanRead<p,f> } -> string A policy is specified using a series of first-order logic assumptions 23 Simple access control on files module FileSystemRM type CanRead<prin, file> type CanWrite<prin, file> val fread: p:prin -> cred<p> -> {f:file | CanRead<p,f> } -> string val fwrite: p:prin -> cred<p> -> {f:file | CanWrite<p,f> } -> string -> unit But, this API does not prevent a privileged client from copying data from a secret file into a publically visible file 24 Tracking information flows between files type label = File: file -> label tracked<t, q> data of type t | Join: label -> label -> label originated from files in q type tracked<‘a, label> type CanFlow<label,label> assume Atomic_flow: forall f:file, g:file. (forall p:prin. CanRead<p,g> => CanRead<p,f>) => CanFlow<File f, File g> assume Lattice: … val fread: p:prin -> cred<p> -> f:{x:file | CanRead<p,x>} -> Returned data tagged with label f tracked<string, File f> val fwrite: p:prin -> cred<p> -> f:{x:file | CanWrite<p,x>} -> l:{x:label | CanFlow<x, File f>} -> data:tracked<string, l> -> Data allowed to flow to f unit 25 Tracking flows in client programs View tracked<‘a,label> as a lattice of monads (or applicative functors) – Abadi et al. in DCC Apply a labeled function bind: l:label -> tracked<(‘a -> ‘b), l> -> m:label -> tracked<‘a, m> -> To a labeled argument tracked<‘b, Join l m> Result at least as secret as both More effort: programmers use bind explicitly 26 Plan A brief primer on Fine and the structure of our compiler A more in-depth look at – Simple access control – Information flow – Stateful authorization in ConfWeb Demo: Fine + DCIL on Azure 27 ConfWeb: A conference mgmt. tool Based on Continue: Krishnamurthi et al. – A conference management server in PLT Scheme Privileges granted by the policy evolve over time Policy structured into 9 phases, 12 kinds of permissions, ~ 50 rules in policy – “Almost all interesting bugs in Continue have related to access control in some form”--- Krishnamurthi et al. IJCAR 2006 28 Structure of ConfWeb Implemented in Fine Authentication modules Security Policy Database of papers, reviews, … Reference monitor provides authorized access to database Chair Untrusted application code (in F#) Reviewer Author 29 A model of stateful authorization assume canReview: forall u:prin, p:paper, s:authstate. (In (Role u Reviewer) s && In (AssignedPaper p u) s) => GrantedIn (Permit u (Review p)) s … Policies specify an unchanging set of inference rules to derive authorization Authorization policies are defined over an evolving set of relations (authorization attributes) facts from the current authorization state State transition on event CloseSubmissions AuthState s0 (Role (U “Andy”) Chair) (Phase Submission) State transition on event AssignPaper paper17 Bob AuthState s1 (Role (U “Andy”) Chair) (Phase PaperAssignment) AuthState s2 (Role (U “Andy”) Chair) (Phase PaperAssignment) (AssignedPaper paper17 (U “Bob”)) 30 Stateful authorization in ConfWeb(1) A simple data model for ConfWeb module ConfWeb type paper = {id:int; authors:list prin; contents:string; … } type review = {paperid:int; reviewid:int; author:prin; …} type db = list<paper> * list<review> * authstate * … 31 Stateful authorization in ConfWeb(2) A vocabulary for a security policy type role = Author | Reviewer | Chair | … type phase = Submission | Assignment | Meeting | … type attr = Role: prin -> role -> attr | Assigned: prin -> paper -> attr | Phase : phase -> attr Authorization state is a list of authorization attributes type authstate = list<attr> Role memberships, paper type action = Submit: -> assignments, conference phasepaper … | Review: paper -> | ReadScore: paper | CloseSub: action type permission = Permit: prin action action -> action Permit Alice (Submit p) -> action -> permission prop In<attr, authstate> prop GrantedIn<permission, authstate> GrantedIn <q, s> says that permission q is derivable from the authstate s 32 Stateful authorization in ConfWeb(3) A security policy assume canSubmit: forall u:prin, p:paper, s:authstate. (In<Role u Author, s> && In<Phase Submission, s>) => GrantedIn<Permit u (Submit p), s> assume canCloseSubmissions: forall u:prin, s:authstate. (In<Role u Chair, s> && In<Phase Submission, s>) => GrantedIn<Permit u (CloseSub), s> assume canReview: forall u:prin, p:paper, s:authstate. (In<Role u Reviewer, s> && In<Assigned u p, s>) => GrantedIn<Permit u (Review p), s> … Security policies are stated using assumptions in the form of first-order logic formulas 33 Stateful authorization in ConfWeb(4) Connecting policy to code using types Calling principal u authenticated using this credential val submit_paper: u:prin -> credential<u> -> p:paper -> {s:authstate | GrantedIn<Permit u (Submit p), s>} -> unit Prove that u has the Submit p permission in the authstate s 34 Stateful authorization in ConfWeb(4) Connecting policy to code using types val submit_paper: u:prin -> credential<u> -> p:paper -> {s:authstate | GrantedIn<Permit u (Submit p), s>} -> unit val close_submissions: u:prin -> credential<u> -> {s:authstate | GrantedIn<Permit u CloseSub, s> } -> {s’:authstate | In<Phase Assignment, s’> } Pre-condition: u must have the CloseSub permission in the pre-state s Post-condition: (Phase Assignment) is in the post-state s’ 35 Stateful authorization in ConfWeb(5) Modeling state changes with affine types val submit_paper: u:prin -> credential<u> -> p:paper -> {s:authstate | GrantedIn<Permit u (Submit p), s>} -> unit val close_submissions: u:prin -> credential<u> -> {s:authstate | GrantedIn<Permit u CloseSub, s> } -> {s’:authstate | In<Phase Assignment, s’> } s is a stale state. Want to ensure that facts derived from s are unusable in subsequent authorization decisions. 36 Stateful authorization in ConfWeb(5) Modeling state changes with affine types A is the kind of affine types type StateIs :: authstate => A StateIs constructs an affine val submit_paper: type from an authstate value u:prin -> credential<u> -> p:paper -> {s:authstate | GrantedIn<Permit u (Submit p), s>} -> unit val close_submissions: u:prin -> credential<u> -> {s:authstate | GrantedIn<Permit u CloseSub, s> } -> {s’:authstate | In<Phase Assignment, s’> } 37 Stateful authorization in ConfWeb(5) Modeling state changes with affine types A is the kind of affine types StateIs<s> is the type of a token asserting s is the current state type StateIs :: authstate => A val submit_paper: u:prin -> cred u -> p:paper -> s:{s:authstate | GrantedIn<Permit u (Submit p), s>} -> StateIs<s> -> StateIs<s> Leaves the state unchanged val close_submissions: u:prin -> credential<u> -> {s:authstate | GrantedIn<Permit u CloseSub, s> } -> {s’:authstate | In<Phase Assignment, s’> } 38 Stateful authorization in ConfWeb(5) Modeling state changes with affine types A is the kind of affine types StateIs<s> is the type of a token asserting s is the current state type StateIs :: authstate => A val submit_paper: u:prin -> cred u -> p:paper -> s:{s:authstate | GrantedIn (Permit u (Submit p)) s} -> StateIs<s> -> StateIs<s> Leaves the state unchanged val close_submissions: u:prin -> cred u -> s:{s:authstate | GrantedIn<Permit u CloseSub, s> } -> StateIs<s> -> (s’: {s’:authstate | In<Phase Assignment, s’>} * StateIs<s’>) Consumes a (StateIs s) token. Produces a (StateIs s’) token. 39 Stateful authorization in ConfWeb(5) Modeling state changes with affine types A is the kind of affine types StateIs<s> is the type of a token asserting s is the current state type StateIs :: authstate => A val submit_paper: u:prin -> cred u -> p:paper -> s:{s:authstate | GrantedIn (Permit u (Submit p)) s} -> StateIs s -> StateIs s val close_submissions: u:prin -> cred u -> s:{s:authstate | GrantedIn (Permit u CloseSub) s} -> StateIs s -> (s’:{s’:authstate | In (Phase Assignment) s’} * StateIs s’) Kinding rules forbid affine values from appearing in formulas. I.e, in t => A, the type t has to be non-affine 40 Stateful authorization in ConfWeb(6) Handling application requests contains: a:attr -> s:authstate -> {b:bool | b=true <=> In a s} let rec evtloop (s, sTok) = match next_request () with | u, cred, SubmitPaper p -> let test = contains (Role u Author) s && contains (Phase Submission) s in if test then let sTok = submit_paper u cred p s sTok in respond (“Submission received”); evtloop (s, sTok) else (“Request Type errorrespond RequestMgr.fine (6.10) denied”); – (6.43): Expected {s:authstate | GrantedIn <Permit u (Submit p), s> } evtloop (s, sTok) | u,Got cred, CloseSubmissions -> authstate let test = contains (Role u Chair) s && contains (Phase Submission) s in … 41 Plan A brief primer on Fine and the structure of our compiler A more in-depth look at – Simple access control – Information flow – Stateful authorization in ConfWeb Demo: Fine + DCIL on Azure 42 Demo: HealthWeb on Azure Type of enforcement code Logical rules for security policy p InRole Doctor AND p IsTreating r.patient => p CanRead r GetRecords: p: prin -> List< {r:record| CanRead <p,r>} > Security Policy UI Doctor search read App logic Patient GetRecords DB_select consent read Insurance provider search Client (Web browser) SQL Azure ASP.NET/C# Application (Azure Web Role) Fine F# Reference monitor O/R Mapping Database (SQL Azure) http://fine-healthweb.cloudapp.net 44 Summary Fine Many different flavors of security-typed programming Using a few general-purpose primitives DCIL Security verification at the bytecode level Secure distributed computing – Clients and the cloud 45 In progress FX: Hoare triples for programming with affinity – A higher-level surface language for Fine Secure browser extensions using Fine and DCIL – IE and the RiSE Cloud Computing Client (C3) Combining cryptographic proofs with proof-carrying code – Fine + F7 (MSR Cambridge) With Juan Chen, Karthik Bhargavan , Johannes Borgstroem, Cedric Fournet, Arjun Guha, Ben Livshits, Alok Rai, Jean Yang 46 Try it out fine-0.3-alpha: Compiler sources, example programs http://research.microsoft.com/fine 47