• Authenticated Encryption

    There’s been some buzz lately about authenticated encryption. The buzz comes from some interesting issues in OpenGPG, and more recently the folks at Microsoft put out an advisory stating that unauthenticated encryption is simply not advisable anymore.

    I thought it would be fun to write about cryptography, despite rarely doing it, even though I find it part of what defines me as an engineer and developer.

    When we think of “encryption”, we usually think of an entity that has sensitive information they want to protect with a “key” of some kind.

    ciphertext = encrypt(plaintext, key)

    Something like that. “Decryption” is usually visualized as the process in reverse. The entity has encrypted data that they want to decrypt into its plaintext form because they know the key.

    The truth is, well designed systems that rely on cryptography aren’t this simple for a variety of reasons. Further on top of that, software developers struggle to encrypt and decrypt information correctly because many frameworks or libraries that developers depend on offer primitives.

    A primitive is a cryptographic function that does very little, but it does its job and it does its job well. That doesn’t mean though that the primitive is enough to fully complete the task. “AES” is a widely known primitive encryption function.

    Its most common mode of operation is Cipher Block Chaining, or CBC, which is not authenticated. To put another way, it is malleable. Let’s demonstrate with some ruby code.

    require 'openssl'
    encrypt_me = "what a fine day for coding" # Data to encrypt
    aes_key = (1..16).to_a.pack("C*") # Dummy bad key
    aes_iv = (17..32).to_a.pack("C*") # Dummy bad initialization vector
    cipher = OpenSSL::Cipher::AES.new(128, :CBC)
    cipher.encrypt # Put it in "encrypt" mode, doesn't actually encrypt
    cipher.key = aes_key
    cipher.iv = aes_iv
    ciphertext = cipher.update(encrypt_me) + cipher.final
    puts ciphertext.bytes.inspect

    Which produces

    [15, 90, 144, 183, 105, 160, 17, 219, 160, 166, 20, 201, 53, 30, 2, 29,
    217, 115, 3, 249, 2, 170, 203, 32, 37, 234, 147, 188, 167, 254, 254, 192]

    There are some bad things in the code example above - it uses a hard-coded, easy to guess key and initialization vector. If you borrow this code, please be wary that it is to demonstrate.

    Decryption is a similar process.

    aes_key = (1..16).to_a.pack("C*") # Dummy bad key
    aes_iv = (17..32).to_a.pack("C*") # Dummy bad initialization vector
    cipher = OpenSSL::Cipher::AES.new(128, :CBC)
    cipher.decrypt # Put it in "decrypt" mode, doesn't actually decrypt
    cipher.key = aes_key
    cipher.iv = aes_iv
    plaintext = cipher.update(ciphertext) + cipher.final
    puts plaintext

    Which produces the original string, “what a fine day for coding”.

    What if we just… changed the first byte of the cipher text though?

    ciphertext[0] = "\1"
    # same decryption code as above

    That decrypts to “,=m1aH-q8hor coding”. The decryption process didn’t fail in any clear way, it just produced some garbage. We’ve broken the entire “block” of data that we changed a byte in, plus the Nth byte of the next block which was changed. Since we changed the first (0th) byte, the first byte in the second block is “h”, not “f”.

    If we slice the data:

    plaintext[0..15]  # produces ,=m1aH-q8
    plaintext[16..-1] # produces hor coding

    If we change the second value of the cipher text:

    ciphertext[1] = "\1"
    # Decrypt...
    plaintext[0..15]  # produces non-ASCII characters
    plaintext[16..-1] # produces f4r coding

    We see that the “f” is correct for the first byte, but wrong for the second byte.

    This is malleable encryption. It allows an attacker to change bits or whole bytes. However the decryption process doesn’t “know” that it is producing invalid data. It’s obvious when you are processing something like text, but it can be less obvious if the data being encrypted is binary data, like a JPEG image.

    More interestingly, let’s try changing the last byte of the cipher text:

    ciphertext[-1] = "\1"
    # Decrypt...

    Boom! We get an error, in 'final': bad decrypt (OpenSSL::Cipher::CipherError). Why is that? What we just changed was a padding byte. You might have noticed that when we encrypted our string, the resulting cipher text was bigger than then plain text.

    That’s because AES-CBC is a block cipher. It has to operate on chunks of data that are 16 bytes in size. Many implementations will pad the data for you. So when we encrypted “what a fine day for coding”, what actually got encrypted was “what a fine day for coding\6\6\6\6\6\6”.

    Where did those \6 bytes come from? That how many bytes it took to reach a multiple of 16. During decryption, it looks at the last byte to determine how much padding to remove.

    We can demonstrate this by telling the AES cipher during decryption that there is no padding.

    cipher.padding = 0
    # Continue decryption...
    puts plaintext.bytes.inspect

    Which produces:

    [119, 104, 97, 116, 32, 97, 32, 102, 105, 110, 101, 32, 100, 97, 121,
    32, 102, 111, 114, 32, 99, 111, 100, 105, 110, 103, 6, 6, 6, 6, 6, 6]

    So we can see the padding is left there. Six bytes of padding.

    Most implementations of AES will automatically apply and remove padding for you.

    A poor implementation of AES padding removal will look at the last byte and blindly remove that many bytes:

    # Bad padding removal
    last_octet = plaintext[-1].ord
    unpadded = plaintext[0...-last_octet]

    A better implementation of AES padding removal will check that all of the padding bytes are equal to the amount of padding removed.

    # Better
    last_octet = plaintext[-1].ord
    padding = plaintext[-last_octet..-1]
    is_padding_valid = padding.bytes.all? { |b| b == last_octet }
    # Handle "false" for is_padding_valid
    unpadded = plaintext[0...-last_octet]

    An even better implementation of AES padding removal would validate the padding in constant time, which is out of my hands with ruby.

    It turns out that “false” case for is_padding_valid has caused a lot of problems with AES-CBC, resulting in a padding oracle.

    For fun, let’s change the last byte of the first block, and look at the decrypted result and leave the padding on. Remember as we saw previously, changing the Nth byte of the previous block affects the Nth byte of the current block. That’s true for padding as well, it get encrypted like any other data.

    ciphertext[15] = "\1"
    cipher.padding = 0

    We get:

    [... 110, 103, 6, 6, 6, 6, 6, 26]

    Clearly this padding is invalid, because the padding bytes are not all equal to 26. In our home-grown padding removal, is_padding_valid would be false and an error would be returned.

    There is one other value that is valid padding, which is 1. If we can change the last byte of the first block so that the last padding byte is one, the padding will appear valid and no error is raised. Let’s use our bad padding removal code and throw an exception if the padding is bad.

    def decrypt(data)
        aes_key = (1..16).to_a.pack("C*") # Dummy bad key
        aes_iv = (17..32).to_a.pack("C*") # Dummy bad initialization vector
        cipher = OpenSSL::Cipher::AES.new(128, :CBC)
        cipher.padding = 0
        cipher.decrypt # Put it in "decrypt" mode, doesn't actually decrypt
        cipher.key = aes_key
        cipher.iv = aes_iv
        plaintext = cipher.update(data)
        last_octet = plaintext[-1].ord
        padding = plaintext[-last_octet..-1]
        is_padding_valid = padding.bytes.all? { |b| b == last_octet }
        raise "BAD PADDING" unless is_padding_valid
        return plaintext[0...-last_octet]

    Our test string is made up of two blocks. We happen to know the padding length is 6, but let’s pretend we don’t. Here is the cipher text. Let’s try and break the last block.

    Block 1: [15, 90, 144, 183, 105, 160, 17, 219, 160, 166, 20, 201, 53, 30, 2, 29]
    Block 2: [217, 115, 3, 249, 2, 170, 203, 32, 37, 234, 147, 188, 167, 254, 254, 192]

    Let’s assume we have a server that we can submit a cipher text to and we have some encrypted data we want to decrypt. The server can accept encrypted data, but it never actually reveals what the plaintext is. The server will either give a padding error back, or say “OK, I was able to decrypt and process the data”.

    Remember earlier we said:

    We’ve broken the entire “block” of data that we changed a byte in, plus the Nth byte of the next block which was changed.

    It goes to reason then, that if we change the last value of the first block, it will affect the last byte of the second block. We are assuming that this encrypted data has padding, but we don’t know how much. Perhaps we can fiddle with the last byte of the penultimate block.

    Fortunately, our decryption process makes a nice big fat error when the padding is wrong. The byte of the padding has one or two possible values. The value it is supposed to be (remember, it’s six because we are cheating for now) and one. If it’s one, the padding remover will just remove the last byte. If we just try all combinations for the last byte of the first block, perhaps we can figure out what value makes a padding value of one.

                                                                       Change this
    Block 1: [15, 90, 144, 183, 105, 160, 17, 219, 160, 166, 20, 201, 53, 30, 2, 29]
    Block 2: [217, 115, 3, 249, 2, 170, 203, 32, 37, 234, 147, 188, 167, 254, 254, 192]
                                                                      To affect this

    Let’s loop over it.

    (0..255).each do |b|
        # Set last byte of first block
        ciphertext[15] = b.chr
            puts b
            # The decryption process an error. Skip it and move on.

    We get two values back. We get 29 and 26. We already know that the value 29 is valid because that’s the actual value from the ciphertext. So 26 forces the padding to one.

    Let’s cheat for a moment and verify our findings so that we are comfortable. Given:

    ciphertext[15] = 26.chr

    and if we peek inside the decrypted result with the padding left on, we get:

    [95, 9, 61, 149, 138, 173, 150, 56, 255, 200, 46, 73, 45, 145, 185,
    77, 102, 111, 114, 32, 99, 111, 100, 105, 110, 103, 6, 6, 6, 6, 6, 1]

    The first block is garbage, but crucially we see that we indeed coerce the padding byte to 1.

    OK, no more pretending. We know that if we tweak the cipher text’s 15th byte to 26, we end up with a padding of one. What can we learn from that? Let’s take the original ciphertext value, 29, and xor it with our guessed value 26, and then with 1 which is the plaintext value we know it happens to be because the padding was removed successfully.

    29 ^ 26 ^ 1 => 6

    We were able to figure out the plaintext last byte of the second block. This isn’t “sensitive”, yet, this is the only a padding value. However, we did successfully decrypt a byte without explicit knowledge of the key or the decryption process telling it was 6.

    Let’s see if we can figure out how to get the padding to (2, 2).

    We can control the last byte of the plaintext now. We can force it to 2 using

    ciphertext_value xor known_plaintext_value xor 2
    original_ct = ciphertext.dup
    ciphertext[15] = (original_ct[15].ord ^ 6 ^ 2).chr
    (0..255).each do |b|
        ciphertext[14] = b.chr
            puts b

    The result we get back is 6 for this one. If we follow the same formula of

    ciphertext_byte xor guess xor result

    We get 2 ^ 6 ^ 2, which is 6. So we we have decrypted another byte. Let’s use that to force our padding to three.

    ciphertext[15] = (original_ct[15].ord ^ 6 ^ 3).chr
    ciphertext[14] = (original_ct[14].ord ^ 6 ^ 3).chr
    (0..255).each do |b|
        ciphertext[13] = b.chr
            puts b

    The result is 27. 30 ^ 27 ^ 3 is yet again, 6. Which is what we expect since we expect 6 padding bytes with a value of 6.

    For the sake of brevity, let’s skip ahead a bit. Let’s see what happens if we trick it in to thinking there are 7 padding bytes.

    ciphertext[15] = (original_ct[15].ord ^ 6 ^ 7).chr
    ciphertext[14] = (original_ct[14].ord ^ 6 ^ 7).chr
    ciphertext[13] = (original_ct[13].ord ^ 6 ^ 7).chr
    ciphertext[12] = (original_ct[12].ord ^ 6 ^ 7).chr
    ciphertext[11] = (original_ct[11].ord ^ 6 ^ 7).chr
    ciphertext[10] = (original_ct[10].ord ^ 6 ^ 7).chr
    (0..255).each do |b|
        ciphertext[9] = b.chr
            puts b

    The result is 198. 166 ^ 198 ^ 7 is 103. 103 on the ASCII table is “g”. Our plaintext string ends in a “g”. Let’s keep advancing.

    ciphertext[10] = (original_ct[10].ord ^ 6 ^ 8).chr
    ciphertext[9] = (original_ct[9].ord ^ 103 ^ 8).chr
    # etc...

    We get 198, and 160 ^ 198 ^ 8 is “n”. If we repeat this pattern, we can fully decrypt the block. Let’s automate this a bit now.

    decrypt_data = ciphertext.dup
    recovered = {}
    (1..16).each do |i|
        position = 16-i
        (0..255).each do |guess|
            decrypt_data[position] = guess.chr
                next # Bad padding.
            recovered[position] = ciphertext[position].ord ^ guess ^ i
            (1..i).each do |j|
                z = 16 - j
                decrypt_data[z] = (ciphertext[z].ord ^ recovered[z] ^ (i+1)).chr
    pp recovered.sort.map { |k, v| v }.pack("c*")

    The final output is:

    for coding\x06\x06\x06\x06\x06\x06

    The everything put together example of attacking padding is available on GitHub. You can run that in most online ruby REPLs, like repl.it.

    The crucial thing about this is that the “decrypt” process never returns the decrypted data, it either raises an exception or returns “Data processed”. Yet we were still able to determine the contents.

    A common example of this is encrypted data over insecure transports and home-grown transport protocols. Such an example might be two servers that need to communicate with each other securely. The owners of the servers are able to pre-share an AES key for data transmission, say with a configuration file of sorts, so they assume they don’t need to use HTTPS because they can use AES-CBC to communicate data with their preshared keys. If that encrypted data is intercepted, and the intercepter is able to re-submit that data to one of the servers with padding changed, they are now able to decrypt this data.

    Aside: You really should just use TLS with a modern configuration of protocol and cipher suites.

    The solution for this is to authenticate our cipher text, which is to say, make it tamper-proof. This is easier said than done.

    Let’s clean up symmetric encryption a bit to make it less of an example.

    def process_data(iv, data)
        cipher = OpenSSL::Cipher::AES.new(128, :CBC)
        cipher.padding = 0
        cipher.key = @aes_key
        cipher.iv = iv
        plaintext = cipher.update(data)
        last_octet = plaintext[-1].ord
        raise PaddingError if plaintext.length - last_octet < 0
        padding = plaintext[-last_octet..-1]
        is_padding_valid = padding.bytes.inject(0) { |a, b|
            a | (b ^ last_octet)
        raise PaddingError unless is_padding_valid
        # Process data
        return true

    There. We have a function that takes an independent initialization vector and the data, and does a little bit more error handling. It still has flaws mind you, regarding padding removal. There are also some short comings of our attack, such has handling the case where the amount of padding on the ciphertext really is one or decrypting multiple blocks. Both of those are currently left as an exercise.

    The usual means of authenticating AES-CBC is with an HMAC using Encrypt-then-MAC (EtM) to ensure the integrity of the ciphertext. Let’s cleanup our code a bit and reduce the amount of assumptions we make. No more hard coded keys and IVs. We’ll go with in-memory values, for now.

    The final cleaned up version of this is also available on GitHub. For brevity, here are the function definitions:

    def encrypt_data(plaintext); # return is [ciphertext, random_iv]
    def process_data(iv, data); #return is "true", or an exception is raised

    HMAC is a symmetric signature, or a “keyed hash”. If we sign the contents of the cipher text, then validate the HMAC before attempting to decrypt the data, then we have reasonable assurance that the cipher text has not been changed.

    Let’s update the encrypt_data function to include a MAC.

    HASH_ALGORITHM = 'sha256'.freeze
    def encrypt_data(plaintext)
        new_iv = OpenSSL::Random.random_bytes(16)
        cipher = OpenSSL::Cipher::AES.new(128, :CBC)
        cipher.key = @aes_key
        cipher.iv = new_iv
        ciphertext = cipher.update(plaintext) + cipher.final
        digest = OpenSSL::Digest.new(HASH_ALGORITHM)
        mac = OpenSSL::HMAC.digest(digest, @hmac_key, ciphertext)
        [mac.freeze, ciphertext.freeze, new_iv.freeze]

    Our encrypt function now returns the MAC as well. Many uses of EtM simply prepend the MAC to the front of the cipher text. The MAC’s size will be consistent with the underlying algorithm. For example, HMAC-SHA256 will always produce a 256-bit length digest, or 32-bytes. When it comes time to decrypt the data, the HMAC is split off from the cipher text since the length is known.

    The process_data can be updated like this:

    HASH_ALGORITHM = 'sha256'.freeze
    def process_data(iv, mac, data)
        raise MacError if mac.length != 32
        digest = OpenSSL::Digest.new(HASH_ALGORITHM)
        recomputed_mac = OpenSSL::HMAC.digest(digest, @hmac_key, data)
        is_mac_valid = 0
        (0...32).each do |index|
            is_mac_valid |= recomputed_mac[index].ord ^ mac[index].ord
        raise MacError if is_mac_valid != 0
        # Continue normal decryption

    Our attack on the padding no longer works. When we attempt to tweak the first block, the HMAC no longer matches the supplied value. As an attacker, we can’t feasibly re-compute the HMAC without the HMAC key, and trying to guess one that works is also not doable.

    We have some simple authenticated data applied to AES-CBC now, and defeated our padding oracle attack.

    Authenticated encryption is a bare minimum for properly encrypting data, it isn’t “bonus” security. This attack is not new, is have been known at least since Vaudenay described it in 2002. Yet application developers continue to use unauthenticated encryption. Part of that is because people have stated that this oracle attack can be mitigated by not revealing that there was a padding error during decryption and instead being generic about the failure. This was likely incorrect advice - the correct solution is to authenticate the data which mitigates the padding oracle attack quite well.

    We’re not quite done yet. In a later post, we’ll look at some of the problems with authenticating data using HMAC or using a mode of AES that is already authenticated like AES-GCM.

  • Disabling old TLS

    I last wrote about the incoming change of disabling old versions of TLS. A detail I left off there was deciding when, and how, to do this.

    At minimum, your site should at least support the latest version of TLS. As of writing, that’s currently 1.2, with 1.3 hot on its heels.

    Who’s Impacted?

    When people or organizations start evaluating this, usually the first question that arises is understanding the impact to the users of your site. Disabling old versions of TLS has the unfortunate issue of a poor user experience. There is no way to tell the user “Your version of TLS is not supported, please update” for reason I previously discussed.

    Not everyone has the same set of users, either. Certain websites might have a disproportionate amount of traffic that target tech-savvy people, which tend to have more up-to-date operating systems and browsers. Other sites may have most of their traffic coming from users that are less inclined to update their software.

    As such, the only way to get a clear picture of an impact to a site is to measure how the site is currently performing. Most web servers or places of terminating TLS (such as a load balancer) can log various aspects of the TLS handshake. The two that are important are the negotiated TLS version, and the negotiated cipher suite. It’s also very beneficial to collect the User-Agent header and IP address as well.

    TLS tries to negotiate the highest version that both the client and the server support. If a client negotiates TLSv1.0, then it is very unlikely that it supports TLSv1.2. If 1% of all negotiated handshakes are TLSv1.0, then disabling TLSv1.0 will result in 1% of handshakes failing.

    That doesn’t necessarily mean 1% of users would be impacted. Almost all sites (even this one) get crawled. Either legitimately by search indexers, or others simply looking for common website exploits. Eliminating handshake statistics that aren’t from users will give a much clearer picture of the actual impact on users. That doesn’t mean you shouldn’t care about crawlers! Having healthy SEO is important to many web properties, and it’s quite possible crawlers you are targeting don’t support modern versions of TLS. However, the traffic from them can be disproportionate. Most reputable crawlers do support TLSv1.2 however.

    Using the IP address and User-Agent header can aide in identifying the source of the handshake. Good crawlers identify themselves with a User-Agent. Less kind crawlers may choose to use an agent string that mimics a browser. For those, you may be able to compare the IP addresses against a list of known spam or bot IP addresses.

    If your website performs any kind of user identification, such as signing in, you may be able to even further know that those handshakes and TLS sessions are from a more reputable source that should factor in statistics.

    Collecting Statistics

    Various different web servers and load balancers support logging common elements of an HTTP request.

    Most web servers and load balancers have a common log format called “combined” logging. Which looks like this: - - [01/Jan/2018:23:59:59 -0400] "GET / HTTP/2.0" 200 9000 "-" "<User Agent String>"

    This breaks down to:

    <client ip> - <basic auth user> [<date time>] "<request>" <response code> <response size> "<referer>" "<user agent>"

    The combined logging format doesn’t include the TLS information, if any. Fortunately, web servers are flexible about what they log and how they log it. You will need something like a flat file parser to be able to query these logs. Alternatively, logging to a central location with syslog or by other means in to a data store that allows querying is very helpful. That way the log file on the server itself can easily be rotated to keep disk usage to a minimum.


    Caddy’s logging directive is simple and can easily be extended.

    log / /var/log/caddy/requests.log "{combined} {tls_protocol} {tls_cipher}"

    Caddy has many different placeholders of what you can include in your logs.

    Note that as of writing, Caddy’s documentation for the TLS version placeholder is incorrect. That documentation indicates the placeholder is {tls_version} when it is actually {tls_protocol}.


    Nginx has a similar story. Define a log format in the http block using the $ssl_protocol and $ssl_cipher variables for the TLS version and cipher suite, respectively.

    log_format combined_tls '$remote_addr - $remote_user [$time_local] '
                            '"$request" $status $body_bytes_sent '
                            '"$http_referer" "$http_user_agent" $ssl_protocol $ssl_cipher';

    Then use the log format in a server block.

    access_log /var/log/nginx/nginx-access.log combined_tls;


    Declare a log format:

    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" %{version}c %{cipher}c" combined_tls

    Then add CustomLog directive to a Server or virtual host block:

    CustomLog /var/log/apache/apache-access.log combined_tls

    With all that said and done, you’ll have a Combined Log extended with your TLS connection information.

    You can also use custom log formats to log in a different format entirely, such as JSON. Using a JSON log format and ingesting it elsewhere such as NoSQL DB or any other query engine that is friendly to JSON.


    A good idea that some sites that have already disabled old TLS have done is a “brown-out”. GitHub disabled TLSv1.0 and 1.1 for just one hour. This helped people identify their own browsers or software that was incompatible while only temporarily breaking them. Presumably the idea was to break people temporarily so they would know something is wrong and find documentation about TLS errors they started getting. Things would get working again while those people or teams worked to deploy new versions of software that supported TLSv1.2.

    CloudFlare is doing the same thing for their APIs, except the duration is for a whole day.

    I like this idea, and would encourage people to do this for their web applications. Keep support teams and social media aware of what is going on so they can give the best response, and have plenty of documentation.

    Unfortunately for the case of GitHub, I would say their one hour window was probably a little too small to capture global traffic. A whole day might be too long for others as well. Consider both of these options, or others such as multiple one hour periods spaced out over a 24 or 48 hour period. Geography tends to play an important role in what versions of browsers and software are deployed. In China, for example, Qihoo 360 browser is very popular. You wouldn’t get representative sample of Qihoo’s traffic during the day in the United States.

    Since we mentioned logging, be sure to log failed handshakes because a protocol or cipher suite couldn’t be agreed upon during the brown out period.

    Beyond the Protocol

    Many are focused on TLSv1.2, but making 1.2 the minimum supported TLS version gives us other opportunities to improve.

    You could consider using an ECDSA certificate. Most browsers that support TLS 1.2 also support ECDSA certificates. The only broad exception I can think of is Chrome on Windows XP. Chrome on XP supports TLSv1.2, but uses the operating system to validate and build a certificate path. Windows XP does not support ECDSA certificates.

    Other browsers, like Internet Explorer, won’t work on Windows XP anyway because they don’t support TLSv1.2 in the first place. Firefox uses NSS for everything, so ECDSA works on Windows XP as well.

    ECDSA has a few advantages. The first is smaller certificates. Combined with a if ECDSA is used through the certificate chain as much as possible, this saves hundreds of precious bytes in the TLS handshake. It’s also for the most part more secure than RSA. RSA still widely uses PKCS#1.5 padding for use in TLS. ECDSA avoids this problem entirely.

    Lastly, as mentioned previously, consider the cipher suites, both the key agreement as well as the symmetric algorithm. FF-DHE shouldn’t be used, and is widely disabled in clients for now. Key generation is slow, and the parameter configuration is sometimes wrong. Best to avoid DHE entirely and stick with ECDHE. Also consider if static key exchange is needed at all. There are few browsers out there that support TLSv1.2 but not ECDHE. That might not be true of non-browser software. This again goes back to measuring with your traffic.

    Remove every symmetric algorithm except AES-GCM, ChaCha, and AES-CBC. At minimum, TLSv1.2 requires TLS_RSA_WITH_AES_128_CBC_SHA. That doesn’t include ECDHE, but it does mean that 3DES, RC4, CAMILLA, etc. shouldn’t be bothered with anymore. The order is generally important. AEAD suites should be placed first, while AES-CBC should be placed last.


    Having done these experiments with a few small and medium sized sites, I’m optimistic of disabling old versions of TLS. Particularly, I see little need to support TLSv1.1. Almost everything that supports TLSv1.1 also supports 1.2 as well, and leaving 1.1 enabled doesn’t accomplish too much.

    Since we are removing support from a lot of legacy browsers by supporting TLSv1.2 as a minimum, we can also consider other areas of improvement such as ECDSA for smaller, more secure, certificates, and cleaning up the list of supported cipher suites.

  • Time to disable old TLS

    There has been discussion for a few years about the eventual deprecation of TLS 1.0. The deprecation of TLS 1.0 is interesting, and perhaps a little exciting to me, and will be quite different from when SSL 3 was widely disabled.

    TLS 1.0 is old. 1999 old - it’s been almost twenty years. That’s rather impressive for a security protocol. There have been additions to it over the years, such as adding more modern cipher suites to it, such as AES.

    TLS 1.0 has not been without problems though. There have been various breakages of it over the past few years. While POODLE was widely known as an attack against SSL 3, it did affect certain implementations of TLS 1.0. BEAST is another such breakage. BEAST has been worked around by clients by using 1/n-1 record splitting, however it is unfixable at the protocol without breaking compatibility. A naive client will continue to be vulnerable to such an issue. TLS 1.0 also makes use of older algorithms that cannot be changed, such as using MD5 and SHA1 in the PRF when computing the master secret.

    As a result, there has been a call to deprecate TLS 1.0. That time is finally here, not just for those that like being on the bleeding edge of security. This has been a long time coming, and it won’t be without difficulty for some users and site owners.

    TLS 1.2 is newer, and unfortunately had slow uptake. While TLS 1.2 was specified in 2008, it didn’t see wide deployment for a few years later. Android is an example, which gained support in version 4.0 in late 2011. Only the latest version of Internet Explorer, version 11, has it enabled by default. MacOS 10.9 was the first MacOS version to support TLS 1.2, released in October 2013 (curiously, iOS 5 for the iPhone got TLS 1.2 in 2011, much sooner than MacOS). You can see a full list of common clients and their TLS 1.2 support from SSL Labs’ Site.

    Due to POODLE, SSL 3 was widely disabled, both from clients and servers starting around 2014. TLS 1.0 had 14 years to work its way in to software and in to consumer products. TLS 1.2 on the other hand, has had less time. The other thing that’s rather recent is the explosion of internet connected consumer devices. Unlike desktop computers, these devices tend to have a much more problematic software update schedule, if one exists at all.

    Putting all of this together, turning TLS 1.0 off is likely to cause a much more noticable impact on connectivity. However, this leads to better user safety. Many big players have already announced their plans to disable TLS 1.0. The most notable upcoming one is all organizations that need to be PCI compliant. PCI 3.2 stipulates the eventual shut off of “early TLS”, which is TLS 1.0 and SSL in this case. The looming date is June 30th, 2018. This will impact every website that takes a credit or debit card.

    After June 30, 2018, all entities must have stopped use of SSL/early TLS as a security control, and use only secure versions of the protocol (an allowance for certain POS POI terminals is described in the last bullet below)

    PCI originally wanted this done in June 2016, however it became quickly apparent that many organizations would not be able to meet this goal when PCI 3.1 was announced. Thus, 3.2 extended it by two years, however required companies to put together a risk mitigation and migration plan up until June 2018.

    Many are wondering what they should do about TLS 1.1. Some organizations are simply turning off TLS 1.0, and leaving 1.1 and 1.2 enabled. Other are turning off both 1.0 and 1.1, leaving 1.2 as the only option. In my experience, almost all clients that support TLS 1.1 also support 1.2. There are few browsers that will benefit from having TLS 1.1 enabled since they also support 1.2 in their default configuration. However, the only way to know for certain is to measure based on your needs. TLS 1.1 also shares several character flaws with TLS 1.0.

    A final note would be to tighten down the available cipher suites. TLS 1.2 makes TLS_RSA_WITH_AES_128_CBC_SHA a mandatory cipher suite - there is little reason to have 3DES enabled if your site is going to be TLS 1.2 only. Also ensure that AEAD suites are prioritized first, such as AES-GCM or CHACHA. My preferred suite order might be something like this:


    You can of course move things around to better suit your needs or customers. Some prefer putting AES-256 in front of AES-128 for better security over performance. The exact ones I use on this site are my Caddyfile.

  • Generating .lib with Rust build scripts

    Something I’ve been working on in my spare time is porting Azure SignTool to Rust. I’ve yet to make up mind if Rust is the one-true way forward with that, but that’s a thought for another day.

    I wanted to check out the feasibility of it. I’m happy to say that I think all of the concepts necessary are there, they just need to be glued together.

    One roadblock with Azure SignTool is that it needs to use an API, SignerSignEx3, which isn’t included in the Windows SDK. In fact, just about nothing in mssign32 is in the Windows SDK. Not being in the Windows SDK means no headers, and no .lib to link against.

    For .NET developers, no .lib for linking hasn’t really mattered when consuming Win32 APIs. It simply needs the ordinal or name of the export and the CLR takes care of the rest with platform invoke. For languages like C that use a linker, you need a .lib to link against. Rust is no different.

    For most cases, the winapi crate has all of the Win32 functions you need. It’s only in the case of APIs that are not in the Windows SDK (or like SignerSignEx3, entirely undocumented) that an API will not be in the crate.

    We need to call SignerSignEx3 without something to link against. We have a few different options.

    1. Use LoadLibrary(Ex) and GetProcAddress.
    2. Make our own .lib.

    The latter seemed appealing because then the Rust code can continue to look clean.

    #[link(name = "mssign32")]
    extern {
        fn SignerSignEx3(...)

    Making a .lib that contains exports only is not too difficult. We can define our own .def file like so:

    LIBRARY mssign32

    and use lib.exe to convert it to a linkable lib file:

    lib.exe /MACHINE:X64 /DEF:mssign32.def /OUT:mssign32.lib

    If we put this file somewhere that the Rust linker can find it, our code will compile successfully and we’ll have successfully linked.

    Dependency Walker with azure_sign_tool_rs

    I wasn’t thrilled about the idea of checking in an opaque binary in to source for building, so I sought an option to make it during the rust build process.

    Fortunately, cargo makes that easy with build scripts. A build script is a rust file itself named build.rs in the same directory as your Cargo.toml file. It’s usage is simple:

    fn main() {
        // Build script

    Crucially, if you write to stdout using println!, the build process will recognize certain output as commands to modify the build process. For example:

    println!("cargo:rustc-link-search={}", "C:\\foo\\bar");

    Will add a path for the linker to search. We can begin to devise a plan to make this part of a build. We can in our build call out to lib.exe to generate a .lib to link against, shove it somewhere, and add the directory to to linker’s search path.

    The next trick in our build script will be to find where lib.exe is. Fortunately, the Rust toolchain already solves this since it relies on link.exe from Visual Studio anyway, so it knows how to find SDK tooling (which move all over the place between Visual Studio versions). The cc crate makes this easy for us.

    let target = env::var("TARGET").unwrap();
    let lib_tool = cc::windows_registry::find_tool(&target, "lib.exe")
                .expect("Could not find \"lib.exe\". Please ensure a supported version of Visual Studio is installed.");

    The TARGET environment variable is set by cargo and contains the architecture the build is for, since Rust can cross-compile. Conveniently, we can use this to support cross-compiled builds of azure_sign_tool_rs so that we can make 32-bit builds on x64 Windows and x64 builds on 32-bit Windows. This allows us to modify the /MACHINE argument for lib.exe.

    I wrapped that up in to a helper in case I need to add additional libraries.

    enum Platform {
    impl std::fmt::Display for Platform {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            match *self {
                Platform::X64 => write!(f, "X64"),
                Platform::X86 => write!(f, "X86"),
                Platform::ARM => write!(f, "ARM"),
                Platform::ARM64 => write!(f, "ARM64"),
    struct LibBuilder {
        pub platform : Platform,
        pub lib_tool : cc::Tool,
        pub out_dir : String
    impl LibBuilder {
        fn new() -> LibBuilder {
            let target = env::var("TARGET").unwrap();
            let out_dir = env::var("OUT_DIR").unwrap();
            let platform =
                if target.contains("x86_64") { Platform::X64 }
                else if target.contains("ARM64") { Platform::ARM64 }
                else if target.contains("ARM") { Platform::ARM }
                else { Platform::X86 };
            let lib_tool = cc::windows_registry::find_tool(&target, "lib.exe")
                .expect("Could not find \"lib.exe\". Please ensure a supported version of Visual Studio is installed.");
            LibBuilder {
                platform : platform,
                lib_tool : lib_tool,
                out_dir : out_dir
        fn build_lib(&self, name : &str) -> () {
            let mut lib_cmd = self.lib_tool.to_command();
                .arg(format!("/MACHINE:{}", self.platform))
                .arg(format!("/DEF:build\\{}.def", name))
                .arg(format!("/OUT:{}\\{}.lib", self.out_dir, name));
            lib_cmd.output().expect("Failed to run lib.exe.");

    Then our build script’s main can contain this:

    fn main() {
        let builder = LibBuilder::new();
        println!("cargo:rustc-link-search={}", builder.out_dir);

    After this, I was able to link against mssign32.

    Note that, since this entire project is Windows’s specific and has zero chance of running anywhere, I did not bother to decorate anything with #[cfg(target_os = "windows")]. If you are attempting to make a cross-platform project, you’ll want to account for all of this in the Windows-specific parts.

    With this, I now only need to check in a .def text file and Cargo will take care of the rest.

  • Caddy

    This is my first post with my blog running Caddy. In short, it’s a web server with a focus on making HTTPS simple. It accomplishes this by supporting ACME out of the box. ACME is the protocol that Let’s Encrypt uses. Technically, Caddy supports any Certificate Authority that supports ACME. Practically, few besides Let’s Encrypt do, though I am aware of other CAs making an effort to support issuance with ACME.

    Though I’ve seen lots of praise for Caddy and its HTTPS ALL THE THINGS mantra for a while now, I never really dug in to it until recently. I was actually grabbed by several of its other features that I really liked.

    Configuration is simple. That isn’t always a good thing. Simple usually means advanced configuration or features is lost in the trade off. Fortunately, this does not seem to be the case with Caddy, for me. I am sure it may be for others. When evaluating Caddy, there were a number of things nginx was taking care of besides serving static content.

    1. Rewrite to WebP if the user agent accepts WebP.
    2. Serve pre-compressed gzip files if the user agent accepts it.
    3. Serve pre-compressed brotli files if the user agent accepts it.
    4. Take care of some simple redirects.
    5. Flexible TLS configuration around cipher suites, protocols, and key exchanges.

    Caddy does all of those. It also does them better. Points two and three Caddy just does. It’ll serve gzip or brotli if the user agent is willing to accept them if a pre-compressed version of the file is on disk.

    Rewriting to WebP was easy:

    header /images {
        Vary Accept
    rewrite /images {
        ext .png .jpeg .jpg
        if {>Accept} has image/webp
        to {path}.webp {path}

    The configuration does two things. First, it adds the Vary: Accept header to all responses under /images. This is important if a proxy or CDN is caching assets. The second part says, if the Accept header contains “image/webp”, rewrite the response to “{path}.webp”, so it will look for “foo.png.webp” if a browser requests “foo.png”. The second {path} means use the original if there is no webp version of the file. Nginx on the other hand, was a bit more complicated.

    HTTPS / TLS configuration is simple and well documented. As the documentation points out, most people don’t need to do anything other than enable it. It has sensible defaults, and will use Let’s Encrypt to get a certificate.

    I’m optimistic about Caddy. I think it’s a very nice web server / reverse proxy. I spent about an hour moving my 400 lines of nginx configuration to 51 lines of Caddy configuration.

    I’d recommend giving it a shot.