Attacking Real-World Security Protocols usingLegacy Crypto ......Attacking Real-World Security...

Post on 24-May-2020

21 views 0 download

Transcript of Attacking Real-World Security Protocols usingLegacy Crypto ......Attacking Real-World Security...

AttackingReal-WorldSecurityProtocolsusing LegacyCrypto[partI]

Karthikeyan Bhargavan

+many,manyothers.(INRIA,MicrosoftResearch,LORIA,IMDEA,Univ ofPennsylvania,Univ ofMichigan,JHU)

VerifyingCryptoProtocolImplementationsinF*[partII]

Method:Type-BasedCryptographic Verification

ModularType-BasedCryptographicVerificationsymmetricencryption(AES-CBC)

cryptographicalgorithms

symmetricencryption

(RC4)

SecureRPC

anotherattack

TLS1.2

activeadversaries

securityprotocols

cryptographicconstructions

encryptthen-MAC

fragment-MAC-encode-then-encrypt

typedinterfaces:cryptographicassumptions

typedinterfaces:attackermodels

someattack

someattack

someattack

MAC(SHA1)

typedinterfaces:securityguarantees

INT-CMA IND-CPA

authenticatedencryption

securechannel

BasisforVerification:Refinementtypes

BasisforVerification:Refinementtypes// Sample type and value declarations in F7type nat = n:int{ 0 <= n }val read: n:nat -> b:bytes{ Length(b) <= n }

// Sample cryptographic library interface in F7module AEStype keytype block = b:bytes{ Length(b)=16 }val encrypt: k:key -> p:block -> c:block {c=AES(k,p)} val decrypt: k:key -> c:block -> p:block {c=AES(k,p)}

ModularTyping&RuntimeSafety

Safetymeansthatalllogicalrefinementsholdatruntime.

F*:refinementtypechecking forF#• WeprogramandspecifyinF*• Weverifymodules

againstinterfaces:F*typechecks &callsZ3,anSMTsolver,oneachlogicalproofobligation

RPC.fsti

RPC.fst

RPC.fsi

Type(F*)

Prove(Z3)

Compile(F#)

Erasetypes

AE.fst

Lib.fst

somecryptographicimplementation

Samplemodularverification(protocol)

RPCprotocolusingAuthenticatedEncryption

Formatting

activeadversaries

securityprotocols

anytypedF#program

SecureRPC

Bytes

systemlibraries

AdversaryModel

applicationcode

anytypedF7program

authenticatedencryption messageformat

RPCAPI

Networking

Samplemodularverification(crypto)

RPCusingEncrypt-then-MAC

cryptographicschemes

Formatting

activeadversaries

securityprotocols

MACauthentication

anytypedF#program

SecureRPC

Bytes

systemlibraries

AdversaryModel

applicationcode

anytypedF7program

cryptographicconstructions

probabilisticcomputationalindistinguishability

Encrypt-then-MAC

AES-CBCencryption

authenticatedencryption messageformat

RPCAPI

≈IDEALIND-CPA

≈IDEALINT-CMA

Networking

Sample Typed Interface for Cryptography

MAC : integrity

Samplefunctionality:

MessageAuthenticationCodesmodule MACtype text = bytes val macsizetype key = bytestype mac = bytes

val GEN : unit -> keyval MAC : key -> text -> macval VERIFY: key -> text -> mac -> bool

basicF#interface

ThisinterfacesaysnothingonthesecurityofMACs.

module MACtype text = bytes val macsizetype keytype mac = bytes

val GEN : unit -> keyval MAC : key -> text -> macval VERIFY: key -> text -> mac -> bool

MACkeysareabstract

Samplefunctionality:

MessageAuthenticationCodes

module MACtype text = bytes val macsizetype keytype mac = b:bytes{Length(b)=macsize}

val GEN : unit -> keyval MAC : key -> text -> macval VERIFY: key -> text -> mac -> bool

MACsarefixedsized

MACkeysareabstract

Samplefunctionality:

MessageAuthenticationCodes

module MACtype text = bytes val macsizetype keytype mac = b:bytes{Length(b)=macsize}predicate Msg of key * textval GEN : unit -> keyval MAC : k:key -> t:text{Msg(k,t)} -> macval VERIFY: k:key -> t:text -> mac

-> b:bool{ b=true ) Msg(k,t)}

idealF7interface

“AllverifiedmessageshavebeenMACed”

MACkeysareabstract

MACsarefixedsized

Msg isspecifiedbyprotocolsusingMACs

Samplefunctionality:

MessageAuthenticationCodes

module MACopen System.Security.Cryptographylet macsize = 20let GEN() = randomBytes 16let MAC k t = (new HASHMACSHA1(k)).ComputeHash tlet VERIFY k t m = (MAC k t = m)

module MACtype text = bytes val macsizetype keytype mac = b:bytes{Length(b)=macsize}predicate Msg of key * textval GEN : unit -> keyval MAC : k:key -> t:text{Msg(k,t)} -> macval VERIFY: k:key -> t:text -> mac

-> b:bool{ b=true ) Msg(k,t)}

idealF7interface

MACkeysareabstract

MACsarefixedsized

Msg isspecifiedbyprotocolsusingMACs

concreteF#implementation(using.NET)

“AllverifiedmessageshavebeenMACed”

Thiscan’tbetrue!(collisions)

Samplefunctionality:

MessageAuthenticationCodes

Samplecomputationalassumption:

ResistancetoChosen-MessageExistentialForgeryAttacks(INT-CMA)

module INT_CMA_Gameopen MacLet private k = GEN()let private log = ref []let mac t =

log := t::!logMAC k t

let verify t m =let v = VERIFY k t m inif v && not (mem t !log) then FORGERYv

CMAgame(codedinF#)

ComputationalSafetyaprobabilisticpolytime programcallingmac andverify forgesaMAConlywithnegligibleprobability²

protocoladversarytypedagainstRPCinterface

ComputationalSafetyforMACsconcretesystem

RPCprotocol

Mac

sampleprotocoltypedagainstidealMACinterface

Idealfilter

errorcorrectionmakingVERIFYreturnsfalseonforgeriesIdealMAC

Mac

Anyp.p.t.adversary

RPCprotocol

Anyp.p.t.adversary

F#interfaceF#interface

idealsystem

secureRPC

concretealgorithmassumed INT-CMAcomputationally

safetoo,withprobability1– 1/𝛆

perfectlysafebytyping

INT-CM

Aadversary

Sampleidealfunctionality:

SupportingKeyCompromisemodule MACtype text = bytes val macsizetype keytype mac = b:bytes{Length(b)=macsize}predicate Msg of key * textval GEN : unit -> keyval MAC : k:key -> t:text{Msg(k,t)} -> macval VERIFY: k:key -> t:text -> mac

-> b:bool{ b=true ) Msg(k,t)}

val keysizetype keybytes = b:bytes{Length(b)=keysize}val LEAK: k:key{!t. Msg(k,t)} -> b:keybytesval COERCE: b:keybytes{…} -> k:key{…}

idealF7interface

“AllverifiedmessageshavebeenMACed”

MACkeysareabstract

MACsarefixedsized

Msg isspecifiedbyprotocolsusingMACs

MACkeyshaveconcreterepresentations

Itissafetoturnkeysintobyteswhenallmessagesareverifiable

Sample Typed Interface for Cryptography

encryption : secrecy

PerfectSecrecybyTyping

• Secrecyisexpressedusingobservationalequivalencesbetweensystemsthatdifferontheirsecrets

• Weprove(probabilistic,informationtheoretic)secrecy bytyping,relyingontypeabstraction

PlaintextModules

• Encryptionisparameterizedbyamodulethatabstractlydefineplaintexts,withinterfacemodule Plaintextval size: inttype plaintype repr = b:bytes{Length(b)=size}val coerce : repr -> plain // turning bytes into secretsval leak : plain -> repr // breaking secrecy!

val respond: plain -> plain // sample protocol code

Ifweremovetheleakfunction,wegetsecrecybytyping

Thesizeofplaintextisfixed(aswecannothideit)

Plainmayalsoimplementanyprotocolfunctionsthatoperatesonsecrets

Ifweremovethecoercefunction,wegetintegritybytyping

IdealInterfaceforAuthenticatedEncryption

• Relyingonbasiccryptographicassumptions(IND-CPA,INT-CTXT)itsidealimplementationneveraccessesplaintexts!Formally,idealAEistypedusinganabstractplain typeENC k p encryptsinsteadzerostoc&andlogs(k,c,p)DEC k c returnsSome(p) when(k,c,p) isinthelog,orNone

module AEopen Plaintexttype keytype cipher = b:bytes{Length(b)= size + 16}

val GEN: unit-> keyval ENC: key -> plain -> cipherval DEC: key -> cipher -> plain option

TowardsTLS:addingTypeIndexes

• WithinTLS,wekeeptrackofmanykeys,fordifferentalgorithms&sessions

• Weusefineridealfunctionalitiesthatprovideconditionalsecurity onlyfor“good”keys– generatedbyalgorithmsassumedcomputationallystrong;and– forsessionsbetweenhonest participants

(notthosewiththeadversary)

module AEopen Plaintype (algorithm, sessionID) key(…)val GEN: a:algorithm -> s:sessionID -> (a,s) keyval LEAK: a:algorithm -> s:sessionID

{Weak(a) or Corrupt(s)} -> (a,s) key -> bytesval COERCE: a:algorithm -> s:sessionID

{Weak(a) or Corrupt(s)} -> bytes -> (a,s) key

Thetypeofthekeygeneratedforthisalgorithmusedonlyforthissession

AnIdealInterfaceforCCA2-SecureEncryption

• Itsidealimplementationencryptszerosinsteadofplaintextssoitneveraccessesplaintextrepresentations,andcanbetypedparametrically

module PKENCopen Plainval pksize: inttype skeytype pkey = b:bytes{ PKey(b) Æ}

val ciphersize: inttype cipher = b:bytes{Length(b)=ciphersize}

val GEN: unit -> pkey * skeyval ENC: pkey -> plain -> cipherval DEC: skey -> cipher -> plain

TypedSecrecyfromCCA2-SecureEncryption

Variants:CPA&Authentication• WithCPA-secureencryption,wehaveaweaker idealinterface

thatdemandsciphertext integritybeforedecryption

• Withauthenticatedencryption,wehaveastronger idealinterfacethatensureplaintextintegrity(muchasMACs)

predicate Encrypted of key * cipher

val ENC: k:key -> plain -> c:cipher{Encrypted(k,c)}val DEC: k:key -> c:cipher{Encrypted(k,c)} -> plain

predicate Msg of key * plain // defined by protocol

val ENC: k:key -> p:plain{Msg(k,p)} -> cipherval DEC: k:key -> cipher -> p:plain{Msg(k,p)} option

Verifying a TLSimplementation

28

TLS protocol overviewClient Server

29

Common TLS configurationsClient Server

30

TLS negotiationClient Server

TransportLayerSecurity(Review)

• Interleavingoffourprotocolsontopoftherecordlayer

RecordLayer

Handshakeprotocol

Changeciphersuite

Alertprotocol

App.dataprotocol

authenticatedencryptionwithadditionaldata

stateful authenticatedencryption

fragment;compress

dispatch

CSKa Ke

CS’Ka’Ke’

TCP/IP

plainfragments

encryptedfragments

I/Obytestreams

Application

webpages

freshkeysforeachnewepoch

data

data

SessionsandConnections

• Sessions(S)areforkeyestablishment• Connectionsarefortransportingrecords(AE),

withinaseriesof“epochs”,possiblywithdifferentciphersuites andcertificates

newS finished rehandshake S’ close

resumeS data alert(fatal)

TCP TCP

TCP’

firstepoch(sameciphersuite &keys)

CCS CCS

nexthandshakeinterleavedwithdata

firsthandshake(unprotected)

abbreviatedhandshake

datadata

DHGroup

DH

CRE

PRF

RSA

Cert

Sig

SessionDB

StAE

LHAE

Enc

MAC

Record

Dispatch

TCP

Untyped Adversary

Encode

LHAEPlain

StPlain

TLSFragment

AlertDatastream

Handshake(andCCS)

TLSInfoTLSConstants

Handshake/CCS

TLSRecord

AppData

Base Bytes

Untyped APIAdversary

RPC

RPCPlainApplication

TLSAPI

AlertProtocol

AppDataProtocol

Nonce

TLS

CoreCrypto

RSAKey

Auth

AuthPlain

Extensions

1

2

3 4

5

67

Range

8

9Error

ModularArchitectureformiTLS

agilelength-hiding stateful

Authenticated Encryptionfor fragment streamswith additional data

DHGroup

DH

CRE

PRF

RSA

Cert

Sig

SessionDB

StAE

LHAE

Enc

MAC

Record

Dispatch

TCP

Untyped Adversary

Encode

LHAEPlain

StPlain

TLSFragment

AlertDatastream

Handshake(andCCS)

TLSInfoTLSConstants

Handshake/CCS

TLSRecord

AppData

Base Bytes

Untyped APIAdversary

RPC

RPCPlainApplication

TLSAPI

AlertProtocol

AppDataProtocol

Nonce

TLS

CoreCrypto

RSAKey

Auth

AuthPlain

Extensions

1

2

3 4

5

67

Range

8

9Error

ModularArchitectureformiTLS

MAC

Fragment;MAC;Encode;thenEncryptplaintextmessagesentbytheapplication

fragment tobesentlater

fragment

padMACfragment

sentearlier

fragmenting&paddingareunder-specified

IVencryptedrecord.header

sent/receivedonTCPconnection

• TLSdecodesthedecryptedtextbefore authentication;potentiallyleakingsecretinformation(via“paddingoracles”)

• Securityreliesonjointciphertext integrity(INT-CTXT)Theproofisadhoc(forCBC)anddependson|MAC|>|Block|(recentattack&proofbyPatersonetal.atASIACRYPT’11)

contenttype&sequencenumber

contenttype&sequencenumber

Fragment-then-Compress?

• Largemessagesareslicedintomanyfragments

• Whenencoded,eachfragmentisindependently compressed

• Aneavesdroppercanrecordthesequenceoffragmentciphertext lengths,andobtainprecisemessagefingerprints– leakingmuchmorethan

thetotalmessagelength

maxfragmentlength(16KB)

lengthsobservedonthenetwork

(16KB)

Fragment-then-Compress?

• Experimentaldata:downloadingsongsoverHTTPS:

Anotherrecentattackexploiting

compressionwithchosenplaintexts

Ourapproach:disablecompression,then

Hidesecretlengthswithinpublicranges• Theapplicationchoosesitsownplaintextrange,

e.g.anysecretURLofsize0..200bytes

•0

• Fragmentationandpaddingdependsonlyontherange&ciphersuite,notonthesecretmessagelength&content

Formally,weindexourtypeofplaintextfragmentsbytheirrange&sequencenumberinthestreamtoo.Bytyping,wecheckthat

AbstractPlaintextFragments

• Abstractplaintextfragmentsareindexedby– keyinfo includingnegotiatedalgorithmsandconnectioninfo– range forthe(secret)plaintextlength– additionaldata,encodinge.g.TLSversion&fragmentnumber

• Typeabstractionyieldsconditional securityforplaintextswithsafekeyinfo

module PlainAEADtype (;ki:KeyInfo) data = b:bytes{…}type (;ki:KeyInfo,rg:range,ad:data) fragment

val leak:ki:KeyInfo{not(Safe(ki))} -> rg:range -> ad:data -> (;ki,rg,ad) fragment -> b:bytes{Length(b) in rg}

val coerce:ki:KeyInfo{not(Safe(ki))} -> rg:range -> ad:data -> b:bytes{Length(b) in rg} ->(;ki,rg,ad) fragment

module PlainAEADtype (;ki:KeyInfo) data = b:bytes{…}type (;ki:KeyInfo,rg:range,ad:data) fragment

val LEAK:ki:KeyInfo{not(Safe(ki))} -> rg:range -> ad:data -> (;ki,rg,ad) fragment -> b:bytes{Length(b) in rg}

val COERCE:ki:KeyInfo{not(Safe(ki))} -> rg:range -> ad:data -> b:bytes{Length(b) in rg} ->(;ki,rg,ad) fragment

AuthenticatedEncryptioninTLS

• encryption&decryptionwithasafeindexdonotaccesstheplaintextbytes(IND-CPA)

• decryptionwithasafeindexsucceedsoncorrectly-encryptedciphertexts,returnsanerrorotherwise (INT-CTXT)

module AEADval encrypt:ki:KeyInfo -> (;ki)key -> ad:(;ki)data ->rg:range -> p:(;ki,rg,ad) fragment -> c:(;ki) cipher { CTXT(ki,ad,p,c) }

val decrypt:ki:KeyInfo -> (;ki)key -> ad:(;ki)data -> c:cipher{CipherLength(ki,c)} -> rg:range * r:(;ki,rg,ad) fragment option{ Safe(ki) => !p. r = Some(p) <=> CTXT(ki,ad,p,c) }

Handshakes

44

TLS_RSA_WITH_AES_128_CBC_SHA

Client Server

45

TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256

Client Server

46

Cryptographic core of TLS

47

Cryptography of TLS ‘as it is’

48

Cryptographic security goals

completes

Agreement: a cert ms, k tag

Authenticity:

Confidentiality:

49

KEM

DHGroup

DH

KEF

KDF/MAC

RSA

Cert

Sig

SessionDB StAE

LHAE

Enc

MAC

Record

Dispatch

TCP

Untyped Adversary

Encode

LHAEPlain

StPlain

TLSFragmentAlertDatastreamHandshake (and CCS)

TLSInfoTLSConstants

Handshake/CCS

TLSRecord

AppData

Base Bytes

Untyped APIAdversary

RPC

RPCPlainApplication

TLS API

AlertProtocol

AppDataProtocol

Nonce

TLS

CoreCrypto

RSAKey

Auth

AuthPlain

Extensions

1

2

3 4 5

6 7

Range

8

9Error

The concrete implementation

50

Security of master secret KEM

51

Security of master secret KEM

52

Sufficient assumptions on the pms-KEM

53

Sufficient assumptions on the pms-KEM

54

Sufficient assumptions on the pms-KEM

Main TLS API

TheTLSAPI&idealfunctionality

• OurAPIissimilarbutmoreinformativethanmainstreamAPIs– Werunonthecaller’sthread,

lettingtheapplicationdothescheduling&multiplexing– Wegivemorecontrol totheapplicationcode,

andreflectmoreinformationfromtheunderlyingTLSstate(lengths,fragmentation,authorizationqueries)

• Moreprecisesecuritytheorems• Moreflexibilityforexperiments&testing

• Wecanimplementsafe&simpleAPIsontopofit• SampleapplicationsusingourAPI

• SecureRPCs(withoneconnectionpercall)• Password-basedclientauthentication• BasicHTTPSclientsandservers(forinteroperabilitytesting)

ourmainTLSAPI(outline)

type cn // for each local instance of the protocol

// creating new client and server instancesval connect: TcpStream -> params -> (;Client) nullCn Resultval accept: TcpStream -> params -> (;Server) nullCn Result

// triggering new handshakes, and closing connectionsval rehandshake: c:cn{Role(c)=Client} -> cn Resultval request: c:cn{Role(c)=Server} -> cn Resultval shutdown: c:cn -> TcpStream Result

// writing data type (;c:cn,data:(;c) msg_o) ioresult_o =| WriteComplete of c':cn| WritePartial of c':cn * rest:(;c') msg_o| MustRead of c':cnval write: c:cn -> data:(;c) msg_o -> (;c,data) ioresult_o

// reading data type (;c:cn) ioresult_i =| Read of c':cn * data:(;c) msg_i| CertQuery of c':cn| Handshake of c':cn| Close of TcpStream| Warning of c':cn * a:alertDescription| Fatal of a:alertDescription val read : c:cn -> (;c) ioresult_i

Eachapplicationprovidesitsownplaintextmodulefordatastreams:• Typingensures

secrecyandauthenticityatsafeindexes

Eachapplicationcreatesandrunssession&connectionsinparallel• Parametersselect

ciphersuites andcertificates

• Resultsprovidedetailedinformationontheprotocolstate

ourverifiedmodularTLSimplementation

TLS.fs7

Bytes,Networklib.fs

CryptographicProvider

cryptographicassumptions

Mainresult:concreteTLSandidealTLSareindistinguishable

OurtypedidealAPIforTLSthusyieldsapplicationsecuritybytyping

ourverifiedmodularTLSimplementation

TLS.fs7

Bytes,Networklib.fs

anytypedF#program

Mainresult:concreteTLSandidealTLSareindistinguishable

OurtypedidealAPIforTLSthusyieldsapplicationsecuritybytyping

applicationdatastreams

TLSapplicationverifiedbytyping

CryptographicProvider

cryptographicassumptions

“Untyped”idealAPIforTLS

Ideal/Concretestream.fs

indistinguishabilityforallPPTadversaries

plaintypedinterface(attackermodel)

ourverifiedmodularTLSimplementation

TLS.fs7

anytypedF#program

TLSproxywithbytes-onlyAPI

Bytes,Networklib.fs

anytypedF#program

TLS_Adv.fs7

CryptographicProvider

cryptographicassumptions

SecurityforRPC

overTLS

RPCPayloadplain.fs

activeadversaries

ourverifiedmodularTLSimplementation

TLS.fs7

anytypedF#program

RPCrpc.fs

Bytes,Networklib.fs

RpcAdv.fs

applicationcode

anytypedF#program

anytypedF#program

CryptographicProvider

cryptographicassumptions

Interoperability&Performance

WerunclientsagainstanOpenSSL 1.0.1eserverforvariousciphersuites• Howmanyhandshakespersecond?• Howmuchdatatransferredpersecond?

miTLS verifiedcodebaseandpapers

https://github.com/mitls/mitls-fstarhttps://mitls.org/