23
Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of Madrid Cristina Arribas Francisco Fernando de la Cruz Su´ arez Connor William Sydney Gascoigne Yaiza Jim´ enez Briongos Marcello Savarese Coordinator: Miguel Ambrona Co-organizer: Itsaka Rakotonirina IMDEA Software Institute

Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

Side-Channel Attacks in

Cryptography

XII Modelling Week - Master in Mathematical EngineeringComplutense University of Madrid

Cristina Arribas Francisco

Fernando de la Cruz Suarez

Connor William Sydney Gascoigne

Yaiza Jimenez Briongos

Marcello Savarese

Coordinator: Miguel Ambrona

Co-organizer: Itsaka Rakotonirina

IMDEA Software Institute

Page 2: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

Contents

1 Introduction 1

2 Task 1: Breaking a password 3

3 Task 2: Binary attack 5

4 The RSA algorithm 6

5 Task 3: Timing attack to RSA 8

5.1 Attacking the multiply . . . . . . . . . . . . . . . . . . . . . . . . . . 9

5.2 Attacking the square . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

6 Conclusions and future work 12

A Source code of our attacks 13

References 20

2

Page 3: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

We would like to acknowledge the coordinator of this problem, Miguel, for hishelp and support during and after the Modelling Week.

3

Page 4: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

1 Introduction

Cryptography is a very important area of knowledge nowadays, and that isbecause it consists of the practice and study of secure communication. In the realworld we are immersed, there is a huge amount of information being transferredbetween people and a wide variety of organizations. The growth of these exchanges,as well as the storage of this information, has promoted the development of cryp-tography in order to guarantee security for all this data. But, specifically, whatdo we understand by security? Let us suppose that our data is protected using acipher. Data will be secure if the cipher cannot be broken with current technologyin a reasonable time frame.

A very big area in cryptography is encryption, that allows us to encode messagesor information so that a third party can not access them. A public-key encryptionscheme consists of three different algorithms:

1. Setup, it takes as input the security parameter (then length of the generatedkeys) and produces a pair of keys (pk, sk).

2. Encryption, it takes as input the public key pk and a message m and producesa ciphertext.

3. Decryption, it takes as input the secret key sk and a ciphertext ct and producesa message.

The method for encrypting a message m consists of the following steps, wherewe use the previous algorithms:

1. Create a pair of keys (the secret key, sk, and the public key, pk) using thesetup algorithm.

2. Encrypt the message: Enc(pk,m)→ ct, where ct is the ciphertext.

3. Send the ciphertext to the receiver.

4. The receiver has to perform the decryption of the ciphertext: Dec(sk, ct)→ m.

The security of an encryption scheme is defined by a game between a challengerand an attacker (called the security experiment). First of all, the challenger will setup two keys: the secret key, sk, and the public key, pk. The last one will be sharedwith the attacker, who will now pick two different messages, m0 and m1, and sendthem to the challenger. The challenger will choose one of them (in other words, thechallenger will set b ∈ {0, 1}) and encrypt it, getting ciphertext (ct = Enc(pk,mb)).After that, the ciphertext will be sent back to the attacker, who will try to break itguessing b′. The attacker wins if b = b′.

1

Page 5: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

Graphically we have the following scheme:

Formally, the former scheme is secure if for all probabilistic polynomial timeadversaries A,

Pr[A wins] ≤ 1

2+ f(λ),

where f is a negligible1 function of λ, which is the length of the key. Intuitively,this means that the attacker has only an insignificant advantage (measured by f)in deciding which of the messages it chose was encrypted. A cipher that is securein under this definitions provides pretty strong guarantees, because roughly, cipher-texts do not leak anything, not even a single bit of information.

Nowadays, there are many candidates of encryption schemes, many of themproven secure under standard assumptions like the hardness of factoring or solvingthe discrete logarithm over a finite group of large prime order. However, even theseschemes that are theoretically sound (there exists no known way of attacking them inpractice) suffer from the problems that appear when putting them into practice. Inparticular, one of the most common vulnerabilities that appear when implementinga cryptographic primitive are the so-called side-channel attacks.

Side-Channel attacks

Side-channel attacks are a powerful kind of attacks that take advantage of phys-ical information that the cryptographic algorithm generates while running. Thisinformation belongs to a wide range of properties: the time that the algorithmneeds to give a response, power-consumption while the algorithm is running, elec-tromagnetic leaks, traffic volume, etc.

1A function is said to be negligible if it is asymptotically smaller than the inverse of any

polynomial.

2

Page 6: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

During the resolution of this problem we have implemented the so-called timingattacks . The idea behind them, as we have just anticipated, is to take benefit fromthe non-constant time that the algorithms or implementations needs to give the usera response, after entering some information. As we can see in the following schema,we can enter a question into the implementation of the algorithm, which will performsome tasks involving that question. We will measure the time difference between thestart of the attack and the moment in which we get a response from the algorithm:

Analyzing the timing variations that occur when we enter different questions, wewill be able to infer the secret information. So this attack is very useful when theencryption is impractical to break by brute force. However, we are taking advantageof the fact that many systems perform the required computations in non-constanttime, mostly because they are more efficient if they need less time to give the user aresponse. If this was not the case, then we wouldn’t be able to perform the timingattacks we are going to describe next. These attacks are the main tasks we per-formed during the Modelling Week.

Our goal in this work is to perform a timing attack against an RSA implemen-tation. However, we first analyze two simpler examples (Task 1 and Task 2) towarm-up and present the ideas of a timing attack.

2 Task 1: Breaking a password

In this section we are focused in breaking a password. The password can containcharacters a-z, A-Z and also numbers from 0 to 9. We call this the alphabet of ourpassword.

We are provided with an oracle that checks if certain entered password is corrector not: it returns “true” or “false” respectively. For the sake of our example, thepassword checker is not perfect and is implemented in a naive way. It checks eachcharacter of the given password until it finds one that it’s not correct. Then, itstops and returns an error message. So we can expect that, if the given password is

3

Page 7: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

correct, or almost correct, it will take more time than if it’s not.

In other words, imagine that the first character of the given password is incor-rect. Then, as soon as the oracle checks the first character, it will return an errormessage. Now imagine that the password is completely correct. In this case, theoracle will check all the characters, verifying that they’re right. In the second casethe oracle will take more time in giving us a response than in the previous case, andthis will be precisely the basis of our timing attack.

To implement this attack we used Python. We created a code that performsthe main idea described above. First, it starts guessing the first character of thepassword. To do that, we measure the times of response of the oracle when weintroduced each of the letters of the alphabet. Our guess for the first character wasthe letter of the alphabet that made the oracle to give the longest response. Nowthat we now the first letter, we will continue trying to guess the second one. Wefix the first one and we do the same process, that is, introducing in the oracle thestring formed of the first (fixed) letter + the different possible characters available inthe alphabet. Again, the correct second character will be the one with the longestresponse time of the oracle. Doing this, we guess the second letter and we fix itfor the next iteration of the algorithm. The algorithm iterates this process for eachcharacter of the password.

When does this algorithm stop? As we stated before, the oracle returns “true”or “false” after each attempt we try. When we already have the correct password,the oracle will return “true” and this is when the algorithm will stop.

To see if this attack is feasible, we should check the average time that the attackneeds to recover the complete password. Lets consider:

• s, number of characters of the alphabet, that is, the number of different char-acters that can appear in the password.

• n, the length, or an upper bound on it, of the password we are trying to break.

• t, the time for comparing two letters.

If the password had one letter, then the average time we need to guess thatcharacter is s× t.

If it has two characters, then we need the following average time:

s× t︸︷︷︸For the first one

+ (s× t+ s× t).︸ ︷︷ ︸For the second one, with two characters

4

Page 8: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

Generalizing this for a password with n characters we get:

s× t+ (s× t+ s× t) + . . .(n) + (s× t+ . . .(n) + s× t) =

= (s× t)× (1 + 2 + · · ·+ n) = (s× t)× n(n+ 1)

2.

So the average time the attack needs to break a password with n characters is

(s× t)× n(n+ 1)

2. As we can see, it’s quadratic in the length of the password. The

gain achieved by using this strategy instead of trying all the possible combinationsof characters in the alphabet is clear: in that case, the time needed for the attackwould be up to t× sn, where sn is the number of comparisons that we have to do.

All these steps have been implemented in the code of the Appendix A. Afterperforming this attack, we could recover the correct password, which resulted tohave 17 bits.

3 Task 2: Binary attack

Our second example is based on an abstract function that is given by the followingOcaml code.

let oracle (k:key) (m:msg) : int =

let rec step s k m =

let _ = if s = 1 then wait gap in

if k = Z.zero && m = Z.zero then s

else

let ki = let open Z in Z.to_int (k land Z.one) in

let mi = let open Z in Z.to_int (m land Z.one) in

step (s lxor ki lxor mi) (k >> 1) (m >> 1) in

step 0 k m

We have been given a binary file that implements the above code for certain keyk. On input a message m, this binary computes the function oracle on the unknownkey k and message m. Our goal is to recover this key k by interacting with thisoracle (and measuring the time it requires for every response).

First of all, we analyzed the given code an realized that it is computing thefollowing function:

n−1⊕i=0

ki ⊕n−1⊕i=0

mi

5

Page 9: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

Note that the information that can be gained about the key, from the output ofthis binary file, is at most the parity of its hamming weight. However, we will tryto recover the whole key by performing a side-channel attack.

First, a more detailed analysis allows us to detect that the execution time of thisfunction is dependent on the input values. In particular, The total execution timet(k,m) for inputs k and m is given by the following formula:

t(k,m) =n−1∑i=0

(i⊕

j=0

kj ⊕mj

)(1)

where kj is the jth element in the key, mj is the jth element in the message andn is the length of the key (which is assumed to be known).

We are going to attack the program using side-channels, so to compare differenttimes, we are going to prove different messages and save the time that takes them.In this way, it is easy to compare times.

Note that the following relation holds:

t(k, 0) > t(k, 2i + 2i+1)⇐⇒i⊕

j=0

kj = 1 (2)

Having realized that the execution time satisfies the above formula, we can per-form an attack by recovering all bits of the key iteratively. We refer to Appendix Afor the code in Python implementing our attack.

We succesfully recover the whole key of 512-bits. We note that in this case(unlike in Task 1 or Task 3), there is no way of checking that the guessed key iscorrect. To do so, we compared the recovered key with the one that was used toproduce the binary executable.

4 The RSA algorithm

RSA (Rivest-Shamir-Adleman) is one of the first public-key cryptosystems and iswidely used for secure data transmission. In this cryptosystem, the encryption key(e) is public and the decryption key (d) is private.

RSA is the first privacy protocol based on the difficulty of factoring integers.

A user of RSA creates and then publishes a public key based on two large primenumbers, along with an auxiliary value. The prime numbers must be kept secret.Anyone can use the public key to encrypt a message, but with currently publishedmethods, and if the public key is large enough, only someone with knowledge of the

6

Page 10: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

prime numbers can decode the message feasibly.

The RSA algorithm involves four steps: key generation, key distribution, encryp-tion and decryption.

Key generation

• Start choosing two distinct prime numbers p and q. Then, compute n = pq.

• Compute ϕ(n) = (p− 1)(q − 1), where ϕ is the Euler function.

• Choose a positive integer e ∈ {1, ..., ϕ(n)− 1}, such that it is co-prime withϕ(n), i.e., such that gcd(e, ϕ(n)) = 1

• Determine d as d ≡ e−1 mod ϕ(n), i.e., d is the modular multiplicative inverseof e modulo ϕ(n).

We have d · e ≡ 1 mod ϕ(n). e is released as the public key exponent and d iskept as the private key exponent. There is, then, a public key {n, e} and a privatekey {p, q, d}.

Some criteria to take into account to guarantee the safety of the RSA have todo with the choice of p and q.

• Choose p, q so that lcm(p− 1, q − 1) ≈ (p− 1)(q − 1).

• Avoid p near to q, due to Fermat Algorithm allows factoring n if n = pq withp and q close to

√n.

• Avoid Mersenne primes, which are prime numbers of the form 2k − 1 withk ∈ N .

• Avoid the Pollar’s rho attack, i.e., if n is the product of primes such that p−1have small prime factors only, then is easy to factor.

Key distribution

Suppose that Bob wants to send a message M to Alice. Bob needs Alice’spublic key {n, e} in order to encrypt the message he wants to send. Alice will useher private key {d} to decrypt the message. To enable Bob to send his encryptedmessages, Alice transmits her public key to Bob via a reliable, but not necessarilysecret, route.

7

Page 11: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

Encryption

Now Bob knows Alice’s public key. He wants to send the message m to Alice. Afterturning this message M into an integer m by using a protocol known as paddingscheme, he computes:

c ≡ me (mod n)

that can be done reasonably quickly by using modular exponentiation. ThenBob sends c to Alice.

Decryption

Alice obtains c. Now she recovers m by using her private key d and computing

cd ≡ (me)d ≡ m (mod n)

Once she has recovered m, she can get the original message M by reversing thepadding scheme.

5 Task 3: Timing attack to RSA

We are going to apply a side-channel attack to the RSA. The attack is finishedwhen the private key d = d1d2d3... is recovered.

We assume we have oracle access to a machine that decrypts2 ciphertexts of ourchoice. Note that there are scenarios where having such oracle access makes sense(when a smartcard implementing this functionality is stolen, for example). By mea-suring the time that this oracle takes to answer to our queries, our goal is to guessthe secret that is key hard-wired in the oracle.

By assumption, d1 = 1. To perform the attack, as we have just stated, we havebeen given a binary file that performs the RSA algorithm. The heart of this attackis that this binary file uses the most common modular exponentiation (3), wherethe multiply and the square are done by using the Montgomery algorithm. In thisalgorithm, the operations are performed modulo n. In general, this algorithm hasthe same time of execution for any message m, but sometimes an extra operationis needed. This happens when, during the procedure, a number is greater than themodulus. Because the operations are done by the Montgomery algorithm, we willknow when an extra operation is needed or not.

2In RSA this can also be seen as an oracle that signs messages

8

Page 12: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

The algorithm we have implemented is the following:

x = m

for i = 2 to |d|x = x2

if (di == 1) then

x = x ∗mreturn x

(3)

5.1 Attacking the multiply

Suppose that we know the first k − 1 bits of the key (d1d2...dk−1) and we wantto guess the kth bit, dk.

We start generating many aleatory messages mi. Using the binary file, we savethe time that RSA takes to compute each mi, so at the end we have a set of ti. Alsowe compute the modular exponentiation algorithm, (3), for each mi, and we savethe output xi for each one. Now, the Montgomery algorithm that is used in thismodular exponentiation will tell us if a reduction was needed or not. If we call thisoutput ri, then we have two possibilities: ri = red if a reduction was needed andri = nored if not.

At the end we have a list of messages mi, with associated RSA computationtimes ti and values ri

(mi, ti, ri)

Consider now two sets defined as follows:

RED = {ti : ri = red}

NORED = {ti : ri = nored}

Now we have to determine if the means are statistically equal or not. To do so,for example we can perform the T-Student test for the comparison of two meansand decide according to the obtained p-value.

The hypothesis we should test are:

H0 : µ(RED) = µ(NORED) (a)

H1 : µ(RED) 6= µ(NORED) (b)

This should reveal the value of the next bit dk.

9

Page 13: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

The figure 1 shows the comparison between two possible cases. In (a) we acceptH0 and so dk = 0 while in (b) the null hypothesis is rejected and dk = 1.

Figure 1: Comparison between two possible cases.

Once this value is known, we can simulate the computation up to the multipli-cation due to bit dk+1, attack it in the same way as described above, and so on forthe next bits.

5.2 Attacking the square

The second way in which we decided to attack the algorithms of RSA is attackingthe square. In the same way that we performed before, we start generating manyaleatory messages and saving the time that RSA takes to compute them.

Suppose we know the first k− 1 bits of the key and we want to guess the kth bit.The first operation that is going to be executed independently of the value of dk ism2.

First, we can suppose that dk is 1. In this case we know that there are twooperations that must be doing with the Montgomery algorithm:

• The multiplication between m and the new value that we have (m2).

• The square of the result.

Secondly, we are going to execute the first operation, that has a time. To con-tinue, we execute the square and we are capable to know if the operation needs todo a reduction or not. If the reduction is necessary, the time will be bigger.

10

Page 14: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

Repeat these steps for all the messages that we have created. Now, we definetwo different sets:

RED-1 = {ti : ri = red, dk = 1}NORED-1 = {ti : ri = nored, dk = 1}

Continuing with the attack, we suppose that dk is 0. In this case, we know thatthe multiplication never takes place, and the operation will be the square.

Now, we need to consider a new pair of sets, depending if the operation needsreduction or not:

RED-0 = {ti : ri = red, dk = 0}NORED-0 = {ti : ri = nored, dk = 0}

At this point, we have four sets of messages:

• The bit dk is a 1 and the message needs a reduction.

• The bit dk is a 1 and the message does not need a reduction.

• The bit dk is a 0 and the message needs a reduction.

• The bit dk is a 0 and the message does not need a reduction.

For all of these messages, we have the time that RSA takes to execute them. Allwe have to do is to compare times between these four sets. Compute the mean ofall of them:

• µ1 = µ(RED-1)

• µ2 = µ(NORED-1)

• µ3 = µ(RED-0)

• µ4 = µ(NORED-0)

Finally, if the difference between µ1 and µ2 is greater than the difference betweenµ3 and µ4 we can assume that dk = 1. If not, dk = 0.

At the end, repeating this procedure for each bit in the key d, we get all bits ofthe key except for the last one. We cannot determine the last bit this way due tohow the attack is performed: assuming that the key has length n, in each step weare working by giving the value 0 or 1 to the next bit to the one we want to get,but, if we want to get dn, the last bit, dn+1, does not exist. Actually, this situationis not going to be a big problem. If we already know all bits except the last one it’senough to set the last bit to 0 and 1 and check which one is correct.

11

Page 15: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

The code implemented is in the appendix A. The implemented algorithm cor-rectly recovered a 128-bits key in about 40 hours with 80.000 time measurements.The problem of deciding how many time measurements are needed in order to per-form a successful attack for certain key length is very interesting and a potentialfuture work.

This should be considered as a proof of concept, in the sense that the attack isvery heavy, but it follows a completely indirect method rather than factoring and itwill scale linearly for longer keys (unlike factoring). This algorithm can probably besimplified and achieve a better performance by reusing certain calculations in everyiteration or using a faster compiled language like C, Ocaml, etc.

6 Conclusions and future work

Cryptography is very important, as well as encryption in particular. There is anincreasing amount of fields in the real world that are in need of these disciplines.Fortunately, many theoretically sound encryption schemes exist that rely on well-studied hardness assumptions. However, theoretic security seems to be not enough,because when putting things into practice, there are, indeed, other factors to con-sider. One of them is side channels.

In this report we present a proof of concept which shows that extra care needsto be taken into consideration when dealing with cryptogrphy, because unexpectedattacks and vulnerabilities might appear. In particular, we study and put intropractice several side-channel attacks, based on timing attacks, for different crypto-graphic primitives.

The short time that we had during the Modelling Week allowed us to performseveral attacks. However, as this is a wide area, there was much work to do and notso much time, so this left the door open to a few questions that would be interestingfor future work. For example, some of these questions could be how to improvethe efficiency of the attacks, and also to try to understand the limits of them. Inparticular, how precise need to be the time measurements for the attacks to be fea-sible, studying how many time measurements (in expectation) are needed. Anotheraspect to study is to check if there are any specific scenarios where we really needto dispose of even more time measurements.

For everything we have stated before, we conclude that for the sake of secu-rity and to prevent such unexpected attacks, cryptography needs to be constantlyrevisited and updated.

12

Page 16: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

A Source code of our attacks

Here below, a Python version of the codes that we have implemented:

• Task 1

import socket

import sys

from time import *

def primera():

host = "172.16.16.193"

port = 1234

buf = 1024

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientsocket.connect((host, port))

alphabet = [chr(i) for i in range(48, 123)]

tiempos = []

for i in range(0,len(alphabet)):

t1 = time()

clientsocket.send(alphabet[i])

clientsocket.recv(buf)

t2 = time()

tiempos.append((t2 - t1, i))

(m,ind1) = max(tiempos)

caract1 = alphabet[ind1]

return caract1

def siguiente (caract):

host = "172.16.16.193"

port = 1234

buf = 1024

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientsocket.connect((host, port))

alphabet = [chr(i) for i in range(48, 123)]

13

Page 17: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

tiempos = []

for i in range(0,len(alphabet)):

t1 = time()

clientsocket.send(caract + alphabet[i])

clientsocket.recv(buf)

t2 = time()

tiempos.append((t2 - t1, i))

(m,ind1) = max(tiempos)

caract2 = caract + alphabet[ind1]

return caract2

def main():

t0 = time()

host = "172.16.16.193"

port = 1234

buf = 1024

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientsocket.connect((host, port))

caract1 = primera()

clientsocket.send(caract1)

ans = clientsocket.recv(buf)

estado = 0

while estado == 0:

caract1 = siguiente(caract1)

clientsocket.send(caract1)

ans = clientsocket.recv(buf)

print ans

print caract1

if ans.strip() == "true":

estado = 1

password = caract1

t1 = time()

tiempo = t1-t0

print tiempo

return password

14

Page 18: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

• Task 2

from time import *

import subprocess

import operator

alphabet = [0, 1]

tiempos = []

k = []

t1_0 = time()

subprocess.call(["/home/alumno/h.native", "0"])

t2_0 = time()

basetime0 = t2_0 - t1_0

t1_3 = time()

subprocess.call(["/home/alumno/h.native", "3"])

t2_3 = time()

basetime3 = t2_3 - t1_3

if basetime0 - basetime3 > 0:

k.append(1)

else:

k.append(0)

sumk = k[0]

def first(sumk):

i = 0

while len(k) < 512:

i += 1

t1 = time()

exponent = (2**i) + (2**(i+1))

subprocess.call(["/home/alumno/h.native", str(exponent)])

t2 = time()

time_difference = t2 - t1

comparison = basetime0 - time_difference

print(i, comparison)

if comparison > 0:

n = sumk-1

15

Page 19: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

k.insert(0, operator.mod(n, 2))

print(k)

sumk = sumk + k[0]

else:

n = sumk

k.insert(0, operator.mod(n, 2))

sumk = sumk + k[0]

print(k)

first(sumk)

s = ""

for a in k:

s += str(a)

print(eval("0b"+s))

• Task 3

To create the file that contains all the random messages and time measure-ments, we used the following code:

from time import *

from subprocess import *

from random import randrange

f = open("lista.txt", ’w’)

for i in range(20):

msg=randrange(1,2**128)

t0 = time()

y=call(["/home/alumno/Escritorio/rsa.native", str(msg)],

stdin=PIPE, stdout=PIPE, stderr=PIPE)

t1 = time()

t = t1-t0

f.write(str(msg) +’\n’)

f.write(str(t) +’\n’)

f.close()

16

Page 20: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

To perform the attack, the following code was implemented:

from time import *

from subprocess import *

import matplotlib.pyplot as plt

from scipy.stats import *

import scipy

import numpy as np

import sys

t0 = time()

def modexp(m, d, N):

x = int(m)

for j in range(1,len(d)):

x=x**2%N

if d[j] == ’1’:

x=x*int(m)%N

return x

f = open("file.txt", "r")

data = f.read()

datavec = data.split (’\n’)

def clave(d,N,f):

r0=[]

nr0=[]

r1=[]

nr1=[]

d0 = d + ’0’

d1 = d + ’1’

for i in range(0,160000,2):

m = datavec[i]

t = datavec[i+1]

x0 = modexp(m, d0, N)

x1 = modexp(m, d1, N)

z0 = check_output(["/home/alumno/Escritorio/mtg.native",

str(x0), str(x0)], stdin=PIPE, stderr=PIPE)

red0 = str(z0).split(’\\n’)[1]

if red0 == ’nored’:

nr0.append(t)

17

Page 21: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

else:

r0.append(t)

z1 = check_output(["/home/alumno/Escritorio/mtg.native",

str(x1), str(x1)], stdin=PIPE, stderr=PIPE)

red1 = str(z1).split(’\\n’)[1]

if red1 == ’nored’:

nr1.append(t)

else:

r1.append(t)

#To test equal means:

r0 = [eval(a) for a in r0]

nr0 = [eval(a) for a in nr0]

r1 = [eval(a) for a in r1]

nr1 = [eval(a) for a in nr1]

media_r0 = sum(r0)/len(r0)

media_nr0 = sum(nr0)/len(nr0)

media_r1 = sum(r1)/len(r1)

media_nr1 = sum(nr1)/len(nr1)

resta0 = abs(media_r0-media_nr0)

resta1 = abs(media_r1-media_nr1)

if resta0>resta1:

d = d0

else:

d = d1

return d

def main():

d = ’1’

N = 140964673677570804086640340988681628281

for k in range(127):

d = clave(d,N,f)

print(d)

sys.stdout.flush()

18

Page 22: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

return d

d = main()

print(d)

t1 = time()

tfinal = t1-t0

print(tfinal)

19

Page 23: Side-Channel Attacks in Cryptography - UCM · 2018. 7. 4. · Side-Channel Attacks in Cryptography XII Modelling Week - Master in Mathematical Engineering Complutense University of

References

[1] J.-F. Dhem, F. Koeune, P.-A. Leroux, P. Mestre, J.-J. Quisquater y J.-L.Willems, A practical implementation of the timing attack. In Jean-JacquesQuisquater and Bruce Schneier, editors, Smart Card Research and Applications,pages 167–182, Berlin, Heidelberg, 2000. Springer Berlin Heidelberg.

[2] David Brumley y Dan Boneh, Remote timing attacks are practical. In Proceed-ings of the 12th Conference on USENIX Security Symposium, Volume 12,SSYM’03, pages 1–1, Berkeley, CA, USA, 2003. USENIX Association.

[3] Andrew Bortz and Dan Boneh. Exposing private information by timing webapplications. In Proceedings of the 16th International Conference on World WideWeb, WWW ’07, pages 621–628, New York, NY, USA, 2007. ACM.

[4] Romain Bardou, Riccardo Focardi, Yusuke Kawamoto, Lorenzo Simionato, Gra-ham Steel y Joe-Kai Tsay. Efficient padding oracle attacks on cryptographichardware. Cryptology ePrint Archive, Report 2012/417, 2012.

[5] Billy Bob Brumley and Nicola Tuveri. Remote timing attacks are still practical.In Vijay Atluri and Claudia Diaz, editors, Computer Security – ESORICS 2011,pages 355–371, Berlin, Heidelberg, 2011. Springer Berlin Heidelberg.

[6] Goran Doychev. Tools for the evaluation and choice of countermeasures againstside-channel attacks. Thesis (doctoral). In E.T.S. de Ingenieros Informticos(UPM)2, 2016.

[7] Paul C. Kocher. Timing attacks on implementations of Diffie-Hellman, RSA,DSS, and other systems. pages 104–113, 1996

[8] Kenneth G. Paterson y Arnold Yau. Padding oracle attacks on the iso cbc modeencryption standard. In Tatsuaki Okamoto, editor, Topics in Cryptology – CT-RSA 2004, pages 305–323, Berlin, Heidelberg, 2004. Springer Berlin Heidelberg.

20