http://d3s.mff.cuni.cz
http://d3s.mff.cuni.cz/
Martin Děcký
decky@d3s.mff.cuni.cz
Formal Verification
of Functional Code
Formal Verification
of Functional Code
2Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
MotivationMotivation
Software dependability
IEEE definition
“Dependability is a measurable and provable degree of
system’s availability, reliability and its maintenance
support.”
Laprie J. C.: Dependable Computing and Fault
Tolerance
“Dependability is also affected by other measures, such as
safety, security, integrity and confidentiality.”
3Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Formal VerificationFormal Verification
casual talk on formal methods
4Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Formal VerificationFormal Verification
Casual (informal) definition
Mathematically proving or disproving the
correctness of intended algorithmic properties with
respect to certain formal specification
Properties of the mathematical model of the system
Correspondence of the mathematical model and the
actual system
Mathematical proof vs. proof
Exhaustive deductive reasoning
Inductive reasoning
5Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Did You Do Formal Verification Ever?Did You Do Formal Verification Ever?
I bet you did!
Proving asymptotic time/space complexity of some algorithms
Lookup in a search tree?
Lookup in a hash table?
Proving termination of some algorithms
Minimal spanning tree algorithm?
Proving properties of some algorithms
Rotation in red-black tree preserves the binary search tree property?
All terminal states of a parser are either accepting or rejecting?
Hoare logic?
6Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Formal Methods for Everyone?Formal Methods for Everyone?
There are various software engineering tools
Some are like a screwdriver
Documentation
Version control
QA
Some are like an atom bomb
Formal verification
Sorry if you won’t be able to start
using formal verification tomorrow
morning.
7Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Formal Methods Are for Someone!Formal Methods Are for Someone!
Mission-critical systems
Losses due to outages greater than the investment
into formal methods
Safety-critical systems
Obviously (human lives are priceless)
8Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Cautionary Tale: Therac-25Cautionary Tale: Therac-25
Radiotherapeutic medical device
Derived from Therac-6
Two basic modes of operation
Safety features in hardware instead of software
6 confirmed accidents between
1985 – 1987
3 confirmed deaths with a root cause
of radiation burns
Software race condition
Poor software design and QA
Misleading user interface
Root cause: Poor understanding of software
reliability issues
9Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Cautionary Tale: Ariane 5Cautionary Tale: Ariane 5
ESA heavy lift launch vehicle
Derived from Ariane 4
A reliable and time-proven vehicle
Exploded on its maiden voyage
on June 4th 1996
39 seconds after lift-of
$370 million in damage
64bit float containing velocity truncated
to a 16bit integer in a non-critical software
component
Caused an uncaught exception that propagated
to the control component
A safety component triggered mission abort
The non-critical component served no actual purpose
10Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Formal Verification MethodsFormal Verification Methods
Model checking
Explicit state model checking
Finite state machines, labeled transition systems
Abstract model checking
Abstract interpretation, symbolic execution
Iterative abstraction refinement
Bounded model checking
Potentially infinite models
Typical properties
Unreachability of assertions
Temporal logic (first-order/second-order modal logic)
11Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Model Checking in a NutshellModel Checking in a Nutshell
(open → close)
temporal logic formula
model checker
label transition system
OK
or
line 10: …
line 14: …
line 22: …
line 47: ...
error trace
12Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Linear Temporal LogicLinear Temporal Logic
Captures which properties should hold at which
states
Propositional atomic variables (representing atomic
conditions) and propositional logic operators
Temporal modal operators
Next: X a  a
Globally: G a  a
Finally: F a  a
Until: a U b
Release: a R b
a
aa a a a
a
aa a b
bb b a, b
13Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Formal Verification Methods (2)Formal Verification Methods (2)
Solving proof obligations
Typical properties
Unreachability of assertions
Logical theorem built out of branch conditions and the negation of the assertion
Pre-conditions, post-conditions, invariants
Interactive theorem prover
Automatic theorem prover
SMT (Satisfiability Modulo Theories) solver
Frequently with a SAT solver backend
Extra-functional properties
Timed automata, stochastic model checking (Markov chains)
14Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Caveat: UndecidabilityCaveat: Undecidability
Remember Kurt Gödel’s incompleteness
theorems?
Many interesting non-trivial properties are
actually undecidable
Statements can be fundamentally neither provable
nor refutable in a specific deductive system
Statements can form a non-recursive set where no
finite algorithm can solve the decision problem
E.g. Halting problem, Kolmogorov complexity
Model checking
Undecidable for multithreaded programs with recursion
Decidable for single-threaded boolean programs
Kurt Gödel (1906 – 1978)
Andrey Kolmogorov (1903 – 1987)
15Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
But Wait a Minute ...But Wait a Minute ...
… real computers are not Turing machines!
Finite memory → finite number of states
Enumerating all possible states and testing finite
properties should be always possible
Thus model checking is safe from undecidability
Yeah, but then there is this shit ...
StateState
spacespace
explosionexplosion
17Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
State Space ExplosionState Space Explosion
Making the state space smaller
Fine-grained software components with well-defined
interfaces
Verification of component properties and component
communication independently (composabilitity)
Microkernel multiserver operating systems
Functional programming
Limiting global state, side-efects
Composability on the level of function contracts
Executable specification
18Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
What about Testing?What about Testing?
This talk says formal verification is better than
testing ...
No! They are incomparable!
Only testing deals with the real environment, hardware, users
Formal verification abstracts this as model assumptions
Testing with formal methods (e.g. model-based testing)
Precise, formal definition of correctness
Formal validation of tests
Algorithmic test generation
Fine-tuning test coverage, time consumption, etc.
Commercial
break
Formal Verification of Functional Code
21Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
miTLSmiTLS
Formally verified reference TLS implementation
Microsoft Research, INRIA
SSL 3.0 to TLS 1.2 (w/o elliptic curves, AES-GCM and TLS extensions)
Interoperable with common SSL/TLS implementations
Stable (0.9): Implementation in F#, specification in F7
Automated, modular verification (45 modules) from API to computational assumptions on
cryptographic algorithms
Security properties of stream encryption (privacy, integrity), handshake key establishment
Timing properties (e.g. side channels) not verified
– Basic timing channels mitigation via uniform flow
Development version: Implementation and specification in F*
Performance: ~20 % of OpenSSL transfer rate
Using Bouncy Castle C# cipher suite
Lot of space for optimizations (naive data structures)
22Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
miTLS (2)miTLS (2)
Component F# (LOC) F7 (LOC) F7 (S)
Base 945 581 11
TLS Record 826 511 77
Handshake/CCS 2 400 777 413
Alert Protocol 184 119 105
AppData Protocol 139 113 34
TLS API 640 426 309
Total 5 134 2 527 949
[1] Bhargavan K., Fournet C., Kohlweiss M., Pironti A., Strub P.-Y.: Implementing TLS with Verified
Cryptographic Security, Technical Report, INRIA, Microsoft Research, IMDEA Software, 2013
23Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
F7F7
Refinement type checker
Typed lambda-calculus
All F# types and their refined subtypes
E.g. positive integer, byte array of length 16, etc.
Abstract types (function types with pre-conditions and post-conditions)
Generates proof obligations of type assignments of F# functions
and custom first-order logical formulas
Uses the Z3 SMT solver
“A program is safe if, in every run of the program, every formula
logically follows from prior assumes. The main property of the
type system is that well-typed expressions are always safe.” [1]
24Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
F# and F7F# and F7
// F#
let f x = x + 1
// F7 type contract
val f: x: int -> r: int { r > x }
// F7 type contract that does not hold for f
val f: x: int -> r: int { r = x }
25Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
F7 for miTLSF7 for miTLS
// Predicate specifying the security of TLS connections
predicate OpenState of epoch
definition !e. OpenState(e) <=>
(?r. (r = Client / r = Server) /
((IsFullEpoch(e) / SentCCS(r, EpochSI(e)) /
(SafeVD(EpochSI(e)) => SentCCS(DualRole(r), EpochSI(e)))) /
(IsAbbrEpoch(e) / SentCCSAbbr(r, EpochAI(e)) /
(SafeVD(EpochSI(e)) => SentCCSAbbr(DualRole(r), EpochAI(e))))))
predicate Safe of epoch
definition !e. Safe(e) <=> (SafeId(Id(e)) / OpenState(e))
val safe: (e : epoch) -> b: bool { b = true <=> Safe(e) }
predicate Auth of epoch
definition !e. Auth(e) <=> (AuthId(Id(e)) / OpenState(e))
val auth: (e : epoch) -> b: bool { b = true <=> Auth(e) }
// Verify privacy and integrity properties
ask !e. Safe(e) => Auth(e)
ask !e. not(Auth(e)) => not(Safe(e))
ask !e. OpenState(e) => (AuthId(Id(e)) => Auth(e))
ask !e. OpenState(e) => (SafeId(Id(e)) => Safe(e))
ask !e. Auth(e) => OpenState(e)
26Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
F*F*
Functional language aimed at formal
verification
Type system with polymorphism, dependent types,
monadic efects, refinement types, weakest pre-
condition calculus
F* programs translated to OCaml, F# or C
Essentially similar expressive power as F7
Uses Z3 SMT solver or manual proofs
27Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
F* for miTLSF* for miTLS
// Predicate specifying the security of TLS connections
type OpenState (e: epoch) = (exists (r: role).
(((FullEpoch? e / sentCSS r (epochSI e) / safeVD (epochSI e))
==> sentCCS (dualRole r) (epochSI e))) /
(((AbbrEpoch? E / sentCCSAbbr r (epochAI e) / safeVD (epochSI e))
==> sentCCSAbbr (dualRole r) (epochAI e))))
type Safe (e: epoch) = safeId (mk_id e) / OpenState e
assume val safe: e: epoch -> b: bool { b = true <==> Safe e }
type Auth (e: epoch) = authId (mk_id e) / OpenState e
assume val auth: e: epoch -> b: bool { b = true <==> Auth e }
// No properties to be verified yet
28Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
seL4seL4
Formally verified microkernel
Originally NICTA and General Dynamics C4 Systems, now Data61/CSIRO
Capability-based, reactive microkernel
Thread scheduler
Except during bootstrap, all resource management delegated to user space
Supports ARMv6, ARMv7, x86
Executable specification in Haskell
Properties verified using Isabelle/HOL interactive theorem prover
Safe memory accesses, data integrity (no arithmetic overflows and exceptions,
no undefined behavior), confidentiality, worst case execution time (upper bound
on interrupt handling latency)
Functional correctness of the C source code and compiled binary with the
Haskell specification
29Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Where to Learn MoreWhere to Learn More
Lectures at Faculty of Mathematics and
Physics, Charles University
System Behavior Models and Verification (NSWI101)
Formal Foundations of Software Engineering
(NTIN043)
Program Analysis and Code Verification (NSWI132)
Software Engineering for Dependable Systems
(NSWI054)
Software Requirements Specification (NSWI028)
30Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Q&A
31Martin Děcký, FSharping Meetup, April 25th
2017 Formal Verification of Functional Code
Image ReferencesImage References
Male dress code, AtomicRed, public domain
Screwdriver, Clker, public domain
Atom bomb, OpenClipart, public domain
Therac-25 photo & schematics, Troy Gallagher, included under the
fair use doctrine
Ariane 5, Ignis, Creative Commons
Gears, susannp4, public domain
Photo of Kurt Gödel, Aldo Cavini Benedetti, Creative Commons
Photo of Andrey Kolmogorov, Konrad Jacobs, Creative Commons
Nuclear explosion, James Vaughan, Creative Commons

More Related Content

PDF
IPC in Microkernel Systems, Capabilities
PDF
Unikernels, Multikernels, Virtual Machine-based Kernels
PDF
Microkernels in the Era of Data-Centric Computing
PDF
Hardware/Software Co-Design for Efficient Microkernel Execution
PDF
Lessons Learned from Porting HelenOS to RISC-V
PDF
LO-PHI: Low-Observable Physical Host Instrumentation for Malware Analysis
PDF
Hardware Implementation of Algorithm for Cryptanalysis
PDF
Design and implementation of proposed 320 bit RC6-cascaded encryption/decrypt...
IPC in Microkernel Systems, Capabilities
Unikernels, Multikernels, Virtual Machine-based Kernels
Microkernels in the Era of Data-Centric Computing
Hardware/Software Co-Design for Efficient Microkernel Execution
Lessons Learned from Porting HelenOS to RISC-V
LO-PHI: Low-Observable Physical Host Instrumentation for Malware Analysis
Hardware Implementation of Algorithm for Cryptanalysis
Design and implementation of proposed 320 bit RC6-cascaded encryption/decrypt...

What's hot (20)

PDF
Final report
DOCX
PDF
Parallella: Embedded HPC For Everybody
PDF
COMPARATIVE ANALYSIS OF DIFFERENT ENCRYPTION TECHNIQUES IN MOBILE AD HOC NETW...
PDF
40520130101005
PDF
Efficient Data Mining Of Association Rules in Horizontally Distributed Databases
PDF
Fpga based encryption design using vhdl
PDF
Biomedical image transmission based on Modified feistal algorithm
PDF
An Efficient PDP Scheme for Distributed Cloud Storage
DOCX
Reconfiguration based vlsi design for security
PDF
Building a Distributed Generic Layer for Multiple Personality Support on top ...
DOCX
Signotron Software India Projects
PDF
Optimization of latency of temporal key Integrity protocol (tkip) using graph...
PPT
Bringing The Grid Home for Grid2008
PPTX
Shilpa ppt
PDF
GEC23Demo-SDNTrace
PDF
Final Year Project Synopsis: Post Quantum Encryption using Neural Networks
PDF
Ipsn08 tiny ecc-ieee
PDF
NEW ALGORITHM FOR WIRELESS NETWORK COMMUNICATION SECURITY
PDF
Sequence learning and modern RNNs
Final report
Parallella: Embedded HPC For Everybody
COMPARATIVE ANALYSIS OF DIFFERENT ENCRYPTION TECHNIQUES IN MOBILE AD HOC NETW...
40520130101005
Efficient Data Mining Of Association Rules in Horizontally Distributed Databases
Fpga based encryption design using vhdl
Biomedical image transmission based on Modified feistal algorithm
An Efficient PDP Scheme for Distributed Cloud Storage
Reconfiguration based vlsi design for security
Building a Distributed Generic Layer for Multiple Personality Support on top ...
Signotron Software India Projects
Optimization of latency of temporal key Integrity protocol (tkip) using graph...
Bringing The Grid Home for Grid2008
Shilpa ppt
GEC23Demo-SDNTrace
Final Year Project Synopsis: Post Quantum Encryption using Neural Networks
Ipsn08 tiny ecc-ieee
NEW ALGORITHM FOR WIRELESS NETWORK COMMUNICATION SECURITY
Sequence learning and modern RNNs
Ad

Similar to Formal Verification of Functional Code (20)

PDF
Formal Verification
PPTX
#1 formal methods – introduction for software engineering
PPT
Formal Method for Avionics Software Verification
PDF
Modularity for Accurate Static Analysis of Smart Contracts
PDF
EXTENT-2016: Industry Practices of Advanced Program Analysis
PDF
Formal Verification Of Objectoriented Software International Conference Foveo...
PDF
We hear you like papers
PDF
PDF
A General Framework for Electronic Circuit Verification
PPTX
Application of theorem proving for safety-critical vehicle software
PDF
Formal Methods: Whence and Whither? [Martin Fränzle Festkolloquium, 2025]
PPTX
Case Study of End to End Formal Verification Methodology
PDF
Functional Programming in C# and F#
PDF
Is it important to explain a theorem? A case study in UML and ALCQI
PDF
Formal verification
PPTX
20100522 software verification_sharygina_lecture01
PDF
Basics of Functional Verification - Arrow Devices
PDF
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
PPTX
RTS fault tolerance, Reliability evaluation
PPTX
real time systems fault tolerance, Redundancy
Formal Verification
#1 formal methods – introduction for software engineering
Formal Method for Avionics Software Verification
Modularity for Accurate Static Analysis of Smart Contracts
EXTENT-2016: Industry Practices of Advanced Program Analysis
Formal Verification Of Objectoriented Software International Conference Foveo...
We hear you like papers
A General Framework for Electronic Circuit Verification
Application of theorem proving for safety-critical vehicle software
Formal Methods: Whence and Whither? [Martin Fränzle Festkolloquium, 2025]
Case Study of End to End Formal Verification Methodology
Functional Programming in C# and F#
Is it important to explain a theorem? A case study in UML and ALCQI
Formal verification
20100522 software verification_sharygina_lecture01
Basics of Functional Verification - Arrow Devices
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
RTS fault tolerance, Reliability evaluation
real time systems fault tolerance, Redundancy
Ad

More from Martin Děcký (9)

PDF
2024 in Microkernels (a year in review lightning talk)
PDF
HelenOS: 20 Years of History, 20 Years of Future Vision
PDF
Code Instrumentation, Dynamic Tracing
PDF
Nízkoúrovňové programování
PDF
Porting HelenOS to RISC-V
PDF
What Could Microkernels Learn from Monolithic Kernels (and Vice Versa)
PDF
FOSDEM 2014: Read-Copy-Update for HelenOS
PDF
FOSDEM 2013: Operating Systems Hot Topics
PDF
HelenOS: State of the Union 2012
2024 in Microkernels (a year in review lightning talk)
HelenOS: 20 Years of History, 20 Years of Future Vision
Code Instrumentation, Dynamic Tracing
Nízkoúrovňové programování
Porting HelenOS to RISC-V
What Could Microkernels Learn from Monolithic Kernels (and Vice Versa)
FOSDEM 2014: Read-Copy-Update for HelenOS
FOSDEM 2013: Operating Systems Hot Topics
HelenOS: State of the Union 2012

Recently uploaded (20)

PDF
“A New Era of 3D Sensing: Transforming Industries and Creating Opportunities,...
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
Flame analysis and combustion estimation using large language and vision assi...
PPT
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Comparative analysis of machine learning models for fake news detection in so...
PDF
OpenACC and Open Hackathons Monthly Highlights July 2025
PPTX
Build Your First AI Agent with UiPath.pptx
PDF
Statistics on Ai - sourced from AIPRM.pdf
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PPTX
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
PPTX
Training Program for knowledge in solar cell and solar industry
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PPTX
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
PPT
What is a Computer? Input Devices /output devices
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
“A New Era of 3D Sensing: Transforming Industries and Creating Opportunities,...
sustainability-14-14877-v2.pddhzftheheeeee
NewMind AI Weekly Chronicles – August ’25 Week III
Flame analysis and combustion estimation using large language and vision assi...
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
Getting started with AI Agents and Multi-Agent Systems
Comparative analysis of machine learning models for fake news detection in so...
OpenACC and Open Hackathons Monthly Highlights July 2025
Build Your First AI Agent with UiPath.pptx
Statistics on Ai - sourced from AIPRM.pdf
sbt 2.0: go big (Scala Days 2025 edition)
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
Training Program for knowledge in solar cell and solar industry
Final SEM Unit 1 for mit wpu at pune .pptx
Improvisation in detection of pomegranate leaf disease using transfer learni...
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
What is a Computer? Input Devices /output devices
Enhancing plagiarism detection using data pre-processing and machine learning...

Formal Verification of Functional Code

  • 2. 2Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code MotivationMotivation Software dependability IEEE definition “Dependability is a measurable and provable degree of system’s availability, reliability and its maintenance support.” Laprie J. C.: Dependable Computing and Fault Tolerance “Dependability is also affected by other measures, such as safety, security, integrity and confidentiality.”
  • 3. 3Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Formal VerificationFormal Verification casual talk on formal methods
  • 4. 4Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Formal VerificationFormal Verification Casual (informal) definition Mathematically proving or disproving the correctness of intended algorithmic properties with respect to certain formal specification Properties of the mathematical model of the system Correspondence of the mathematical model and the actual system Mathematical proof vs. proof Exhaustive deductive reasoning Inductive reasoning
  • 5. 5Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Did You Do Formal Verification Ever?Did You Do Formal Verification Ever? I bet you did! Proving asymptotic time/space complexity of some algorithms Lookup in a search tree? Lookup in a hash table? Proving termination of some algorithms Minimal spanning tree algorithm? Proving properties of some algorithms Rotation in red-black tree preserves the binary search tree property? All terminal states of a parser are either accepting or rejecting? Hoare logic?
  • 6. 6Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Formal Methods for Everyone?Formal Methods for Everyone? There are various software engineering tools Some are like a screwdriver Documentation Version control QA Some are like an atom bomb Formal verification Sorry if you won’t be able to start using formal verification tomorrow morning.
  • 7. 7Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Formal Methods Are for Someone!Formal Methods Are for Someone! Mission-critical systems Losses due to outages greater than the investment into formal methods Safety-critical systems Obviously (human lives are priceless)
  • 8. 8Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Cautionary Tale: Therac-25Cautionary Tale: Therac-25 Radiotherapeutic medical device Derived from Therac-6 Two basic modes of operation Safety features in hardware instead of software 6 confirmed accidents between 1985 – 1987 3 confirmed deaths with a root cause of radiation burns Software race condition Poor software design and QA Misleading user interface Root cause: Poor understanding of software reliability issues
  • 9. 9Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Cautionary Tale: Ariane 5Cautionary Tale: Ariane 5 ESA heavy lift launch vehicle Derived from Ariane 4 A reliable and time-proven vehicle Exploded on its maiden voyage on June 4th 1996 39 seconds after lift-of $370 million in damage 64bit float containing velocity truncated to a 16bit integer in a non-critical software component Caused an uncaught exception that propagated to the control component A safety component triggered mission abort The non-critical component served no actual purpose
  • 10. 10Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Formal Verification MethodsFormal Verification Methods Model checking Explicit state model checking Finite state machines, labeled transition systems Abstract model checking Abstract interpretation, symbolic execution Iterative abstraction refinement Bounded model checking Potentially infinite models Typical properties Unreachability of assertions Temporal logic (first-order/second-order modal logic)
  • 11. 11Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Model Checking in a NutshellModel Checking in a Nutshell (open → close) temporal logic formula model checker label transition system OK or line 10: … line 14: … line 22: … line 47: ... error trace
  • 12. 12Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Linear Temporal LogicLinear Temporal Logic Captures which properties should hold at which states Propositional atomic variables (representing atomic conditions) and propositional logic operators Temporal modal operators Next: X a  a Globally: G a  a Finally: F a  a Until: a U b Release: a R b a aa a a a a aa a b bb b a, b
  • 13. 13Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Formal Verification Methods (2)Formal Verification Methods (2) Solving proof obligations Typical properties Unreachability of assertions Logical theorem built out of branch conditions and the negation of the assertion Pre-conditions, post-conditions, invariants Interactive theorem prover Automatic theorem prover SMT (Satisfiability Modulo Theories) solver Frequently with a SAT solver backend Extra-functional properties Timed automata, stochastic model checking (Markov chains)
  • 14. 14Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Caveat: UndecidabilityCaveat: Undecidability Remember Kurt Gödel’s incompleteness theorems? Many interesting non-trivial properties are actually undecidable Statements can be fundamentally neither provable nor refutable in a specific deductive system Statements can form a non-recursive set where no finite algorithm can solve the decision problem E.g. Halting problem, Kolmogorov complexity Model checking Undecidable for multithreaded programs with recursion Decidable for single-threaded boolean programs Kurt Gödel (1906 – 1978) Andrey Kolmogorov (1903 – 1987)
  • 15. 15Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code But Wait a Minute ...But Wait a Minute ... … real computers are not Turing machines! Finite memory → finite number of states Enumerating all possible states and testing finite properties should be always possible Thus model checking is safe from undecidability Yeah, but then there is this shit ...
  • 17. 17Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code State Space ExplosionState Space Explosion Making the state space smaller Fine-grained software components with well-defined interfaces Verification of component properties and component communication independently (composabilitity) Microkernel multiserver operating systems Functional programming Limiting global state, side-efects Composability on the level of function contracts Executable specification
  • 18. 18Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code What about Testing?What about Testing? This talk says formal verification is better than testing ... No! They are incomparable! Only testing deals with the real environment, hardware, users Formal verification abstracts this as model assumptions Testing with formal methods (e.g. model-based testing) Precise, formal definition of correctness Formal validation of tests Algorithmic test generation Fine-tuning test coverage, time consumption, etc.
  • 21. 21Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code miTLSmiTLS Formally verified reference TLS implementation Microsoft Research, INRIA SSL 3.0 to TLS 1.2 (w/o elliptic curves, AES-GCM and TLS extensions) Interoperable with common SSL/TLS implementations Stable (0.9): Implementation in F#, specification in F7 Automated, modular verification (45 modules) from API to computational assumptions on cryptographic algorithms Security properties of stream encryption (privacy, integrity), handshake key establishment Timing properties (e.g. side channels) not verified – Basic timing channels mitigation via uniform flow Development version: Implementation and specification in F* Performance: ~20 % of OpenSSL transfer rate Using Bouncy Castle C# cipher suite Lot of space for optimizations (naive data structures)
  • 22. 22Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code miTLS (2)miTLS (2) Component F# (LOC) F7 (LOC) F7 (S) Base 945 581 11 TLS Record 826 511 77 Handshake/CCS 2 400 777 413 Alert Protocol 184 119 105 AppData Protocol 139 113 34 TLS API 640 426 309 Total 5 134 2 527 949 [1] Bhargavan K., Fournet C., Kohlweiss M., Pironti A., Strub P.-Y.: Implementing TLS with Verified Cryptographic Security, Technical Report, INRIA, Microsoft Research, IMDEA Software, 2013
  • 23. 23Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code F7F7 Refinement type checker Typed lambda-calculus All F# types and their refined subtypes E.g. positive integer, byte array of length 16, etc. Abstract types (function types with pre-conditions and post-conditions) Generates proof obligations of type assignments of F# functions and custom first-order logical formulas Uses the Z3 SMT solver “A program is safe if, in every run of the program, every formula logically follows from prior assumes. The main property of the type system is that well-typed expressions are always safe.” [1]
  • 24. 24Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code F# and F7F# and F7 // F# let f x = x + 1 // F7 type contract val f: x: int -> r: int { r > x } // F7 type contract that does not hold for f val f: x: int -> r: int { r = x }
  • 25. 25Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code F7 for miTLSF7 for miTLS // Predicate specifying the security of TLS connections predicate OpenState of epoch definition !e. OpenState(e) <=> (?r. (r = Client / r = Server) / ((IsFullEpoch(e) / SentCCS(r, EpochSI(e)) / (SafeVD(EpochSI(e)) => SentCCS(DualRole(r), EpochSI(e)))) / (IsAbbrEpoch(e) / SentCCSAbbr(r, EpochAI(e)) / (SafeVD(EpochSI(e)) => SentCCSAbbr(DualRole(r), EpochAI(e)))))) predicate Safe of epoch definition !e. Safe(e) <=> (SafeId(Id(e)) / OpenState(e)) val safe: (e : epoch) -> b: bool { b = true <=> Safe(e) } predicate Auth of epoch definition !e. Auth(e) <=> (AuthId(Id(e)) / OpenState(e)) val auth: (e : epoch) -> b: bool { b = true <=> Auth(e) } // Verify privacy and integrity properties ask !e. Safe(e) => Auth(e) ask !e. not(Auth(e)) => not(Safe(e)) ask !e. OpenState(e) => (AuthId(Id(e)) => Auth(e)) ask !e. OpenState(e) => (SafeId(Id(e)) => Safe(e)) ask !e. Auth(e) => OpenState(e)
  • 26. 26Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code F*F* Functional language aimed at formal verification Type system with polymorphism, dependent types, monadic efects, refinement types, weakest pre- condition calculus F* programs translated to OCaml, F# or C Essentially similar expressive power as F7 Uses Z3 SMT solver or manual proofs
  • 27. 27Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code F* for miTLSF* for miTLS // Predicate specifying the security of TLS connections type OpenState (e: epoch) = (exists (r: role). (((FullEpoch? e / sentCSS r (epochSI e) / safeVD (epochSI e)) ==> sentCCS (dualRole r) (epochSI e))) / (((AbbrEpoch? E / sentCCSAbbr r (epochAI e) / safeVD (epochSI e)) ==> sentCCSAbbr (dualRole r) (epochAI e)))) type Safe (e: epoch) = safeId (mk_id e) / OpenState e assume val safe: e: epoch -> b: bool { b = true <==> Safe e } type Auth (e: epoch) = authId (mk_id e) / OpenState e assume val auth: e: epoch -> b: bool { b = true <==> Auth e } // No properties to be verified yet
  • 28. 28Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code seL4seL4 Formally verified microkernel Originally NICTA and General Dynamics C4 Systems, now Data61/CSIRO Capability-based, reactive microkernel Thread scheduler Except during bootstrap, all resource management delegated to user space Supports ARMv6, ARMv7, x86 Executable specification in Haskell Properties verified using Isabelle/HOL interactive theorem prover Safe memory accesses, data integrity (no arithmetic overflows and exceptions, no undefined behavior), confidentiality, worst case execution time (upper bound on interrupt handling latency) Functional correctness of the C source code and compiled binary with the Haskell specification
  • 29. 29Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Where to Learn MoreWhere to Learn More Lectures at Faculty of Mathematics and Physics, Charles University System Behavior Models and Verification (NSWI101) Formal Foundations of Software Engineering (NTIN043) Program Analysis and Code Verification (NSWI132) Software Engineering for Dependable Systems (NSWI054) Software Requirements Specification (NSWI028)
  • 30. 30Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Q&A
  • 31. 31Martin Děcký, FSharping Meetup, April 25th 2017 Formal Verification of Functional Code Image ReferencesImage References Male dress code, AtomicRed, public domain Screwdriver, Clker, public domain Atom bomb, OpenClipart, public domain Therac-25 photo & schematics, Troy Gallagher, included under the fair use doctrine Ariane 5, Ignis, Creative Commons Gears, susannp4, public domain Photo of Kurt Gödel, Aldo Cavini Benedetti, Creative Commons Photo of Andrey Kolmogorov, Konrad Jacobs, Creative Commons Nuclear explosion, James Vaughan, Creative Commons