1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 13:27:35 +00:00

LibCrypto: Implement GCM mode

This commit is contained in:
AnotherTest 2020-11-11 13:17:23 +03:30 committed by Andreas Kling
parent 2cc867bcba
commit d3c52cef86
6 changed files with 657 additions and 0 deletions

View file

@ -0,0 +1,148 @@
/*
* Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <AK/MemoryStream.h>
#include <AK/Types.h>
#include <AK/Vector.h>
#include <LibCrypto/Authentication/GHash.h>
#include <LibCrypto/BigInt/UnsignedBigInteger.h>
namespace {
static u32 to_u32(const u8* b)
{
return AK::convert_between_host_and_big_endian(*(const u32*)b);
}
static void to_u8s(u8* b, const u32* w)
{
for (auto i = 0; i < 4; ++i) {
auto& e = *((u32*)(b + i * 4));
e = AK::convert_between_host_and_big_endian(w[i]);
}
}
}
namespace Crypto {
namespace Authentication {
GHash::TagType GHash::process(ReadonlyBytes aad, ReadonlyBytes cipher)
{
u32 tag[4] { 0, 0, 0, 0 };
auto transform_one = [&](auto& buf) {
size_t i = 0;
for (; i < buf.size(); i += 16) {
if (i + 16 <= buf.size()) {
for (auto j = 0; j < 4; ++j) {
tag[j] ^= to_u32(buf.offset(i + j * 4));
}
galois_multiply(tag, m_key, tag);
}
}
if (i > buf.size()) {
static u8 buffer[16];
Bytes buffer_bytes { buffer, 16 };
OutputMemoryStream stream { buffer_bytes };
stream.write(buf.slice(i - 16));
stream.fill_to_end(0);
for (auto j = 0; j < 4; ++j) {
tag[j] ^= to_u32(buffer_bytes.offset(j * 4));
}
galois_multiply(tag, m_key, tag);
}
};
transform_one(aad);
transform_one(cipher);
auto aad_bits = 8 * (u64)aad.size();
auto cipher_bits = 8 * (u64)cipher.size();
auto high = [](u64 value) -> u32 { return value >> 32; };
auto low = [](u64 value) -> u32 { return value & 0xffffffff; };
#ifdef GHASH_PROCESS_DEBUG
dbg() << "AAD bits: " << high(aad_bits) << " : " << low(aad_bits);
dbg() << "Cipher bits: " << high(cipher_bits) << " : " << low(cipher_bits);
dbg() << "Tag bits: " << tag[0] << " : " << tag[1] << " : " << tag[2] << " : " << tag[3];
#endif
tag[0] ^= high(aad_bits);
tag[1] ^= low(aad_bits);
tag[2] ^= high(cipher_bits);
tag[3] ^= low(cipher_bits);
#ifdef GHASH_PROCESS_DEBUG
dbg() << "Tag bits: " << tag[0] << " : " << tag[1] << " : " << tag[2] << " : " << tag[3];
#endif
galois_multiply(tag, m_key, tag);
TagType digest;
to_u8s(digest.data, tag);
return digest;
}
/// Galois Field multiplication using <x^127 + x^7 + x^2 + x + 1>.
/// Note that x, y, and z are strictly BE.
void galois_multiply(u32 (&z)[4], const u32 (&_x)[4], const u32 (&_y)[4])
{
u32 x[4] { _x[0], _x[1], _x[2], _x[3] };
u32 y[4] { _y[0], _y[1], _y[2], _y[3] };
__builtin_memset(z, 0, sizeof(z));
for (ssize_t i = 127; i > -1; --i) {
if ((y[3 - (i / 32)] >> (i % 32)) & 1) {
z[0] ^= x[0];
z[1] ^= x[1];
z[2] ^= x[2];
z[3] ^= x[3];
}
auto a0 = x[0] & 1;
x[0] >>= 1;
auto a1 = x[1] & 1;
x[1] >>= 1;
x[1] |= a0 << 31;
auto a2 = x[2] & 1;
x[2] >>= 1;
x[2] |= a1 << 31;
auto a3 = x[3] & 1;
x[3] >>= 1;
x[3] |= a2 << 31;
if (a3)
x[0] ^= 0xe1000000;
}
}
}
}

View file

@ -0,0 +1,76 @@
/*
* Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <AK/String.h>
#include <AK/Types.h>
#include <LibCrypto/Hash/HashFunction.h>
namespace Crypto {
namespace Authentication {
void galois_multiply(u32 (&z)[4], const u32 (&x)[4], const u32 (&y)[4]);
struct GHashDigest {
constexpr static size_t Size = 16;
u8 data[Size];
const u8* immutable_data() const { return data; }
size_t data_length() { return Size; }
};
class GHash final {
public:
using TagType = GHashDigest;
template<size_t N>
explicit GHash(const char (&key)[N])
: GHash({ key, N })
{
}
explicit GHash(const ReadonlyBytes& key)
{
for (size_t i = 0; i < 16; i += 4)
m_key[i / 4] = AK::convert_between_host_and_big_endian(*(const u32*)(key.offset(i)));
}
constexpr static size_t digest_size() { return TagType::Size; }
String class_name() const { return "GHash"; }
TagType process(ReadonlyBytes aad, ReadonlyBytes cipher);
private:
inline void transform(ReadonlyBytes, ReadonlyBytes);
u32 m_key[4];
};
}
}

View file

@ -1,4 +1,5 @@
set(SOURCES
Authentication/GHash.cpp
BigInt/SignedBigInteger.cpp
BigInt/UnsignedBigInteger.cpp
Checksum/Adler32.cpp

View file

@ -31,6 +31,7 @@
#include <LibCrypto/Cipher/Cipher.h>
#include <LibCrypto/Cipher/Mode/CBC.h>
#include <LibCrypto/Cipher/Mode/CTR.h>
#include <LibCrypto/Cipher/Mode/GCM.h>
namespace Crypto {
namespace Cipher {
@ -53,6 +54,7 @@ public:
virtual ByteBuffer get() const override { return m_data; };
virtual const ByteBuffer& data() const override { return m_data; };
ReadonlyBytes bytes() const { return m_data; }
virtual void overwrite(ReadonlyBytes) override;
virtual void overwrite(const ByteBuffer& buffer) override { overwrite(buffer.bytes()); }
@ -113,6 +115,7 @@ class AESCipher final : public Cipher<AESCipherKey, AESCipherBlock> {
public:
using CBCMode = CBC<AESCipher>;
using CTRMode = CTR<AESCipher>;
using GCMMode = GCM<AESCipher>;
constexpr static size_t BlockSizeInBits = BlockType::BlockSizeInBits;

View file

@ -0,0 +1,154 @@
/*
* Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <AK/OwnPtr.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <AK/StringView.h>
#include <LibCrypto/Authentication/GHash.h>
#include <LibCrypto/Cipher/Mode/CTR.h>
#include <LibCrypto/Verification.h>
namespace Crypto {
namespace Cipher {
using IncrementFunction = IncrementInplace;
template<typename T>
class GCM : public CTR<T, IncrementFunction> {
public:
constexpr static size_t IVSizeInBits = 128;
virtual ~GCM() { }
template<typename... Args>
explicit constexpr GCM<T>(Args... args)
: CTR<T>(args...)
{
static_assert(T::BlockSizeInBits == 128u, "GCM Mode is only available for 128-bit Ciphers");
__builtin_memset(m_auth_key_storage, 0, block_size);
typename T::BlockType key_block(m_auth_key_storage, block_size);
this->cipher().encrypt_block(key_block, key_block);
key_block.bytes().copy_to(m_auth_key);
m_ghash = make<Authentication::GHash>(m_auth_key);
}
virtual String class_name() const override
{
StringBuilder builder;
builder.append(this->cipher().class_name());
builder.append("_GCM");
return builder.build();
}
virtual size_t IV_length() const override { return IVSizeInBits / 8; }
// FIXME: This overload throws away the auth stuff, think up a better way to return more than a single bytebuffer.
virtual void encrypt(const ReadonlyBytes& in, Bytes& out, const Bytes& ivec = {}, Bytes* = nullptr) override
{
ASSERT(!ivec.is_empty());
static ByteBuffer dummy;
encrypt(in, out, ivec, dummy, dummy);
}
virtual void decrypt(const ReadonlyBytes& in, Bytes& out, const Bytes& ivec = {}) override
{
encrypt(in, out, ivec);
}
void encrypt(const ReadonlyBytes& in, Bytes out, const ReadonlyBytes& iv_in, const ReadonlyBytes& aad, Bytes tag)
{
auto iv_buf = ByteBuffer::copy(iv_in.data(), iv_in.size());
auto iv = iv_buf.bytes();
// Increment the IV for block 0
CTR<T>::increment(iv);
typename T::BlockType block0;
block0.overwrite(iv);
this->cipher().encrypt_block(block0, block0);
// Skip past block 0
CTR<T>::increment(iv);
if (in.is_empty())
CTR<T>::key_stream(out, iv);
else
CTR<T>::encrypt(in, out, iv);
auto auth_tag = m_ghash->process(aad, out);
block0.apply_initialization_vector(auth_tag.data);
block0.get().bytes().copy_to(tag);
}
VerificationConsistency decrypt(const ReadonlyBytes& in, Bytes out, const ReadonlyBytes& iv_in, const ReadonlyBytes& aad, const ReadonlyBytes& tag)
{
auto iv_buf = ByteBuffer::copy(iv_in.data(), iv_in.size());
auto iv = iv_buf.bytes();
// Increment the IV for block 0
CTR<T>::increment(iv);
typename T::BlockType block0;
block0.overwrite(iv);
this->cipher().encrypt_block(block0, block0);
// Skip past block 0
CTR<T>::increment(iv);
auto auth_tag = m_ghash->process(aad, in);
block0.apply_initialization_vector(auth_tag.data);
auto test_consistency = [&] {
if (block0.block_size() != tag.size() || __builtin_memcmp(block0.bytes().data(), tag.data(), tag.size()) != 0)
return VerificationConsistency::Inconsistent;
return VerificationConsistency::Consistent;
};
// FIXME: This block needs constant-time comparisons.
if (in.is_empty()) {
out = {};
return test_consistency();
}
CTR<T>::encrypt(in, out, iv);
return test_consistency();
}
private:
static constexpr auto block_size = T::BlockType::BlockSizeInBits / 8;
u8 m_auth_key_storage[block_size];
Bytes m_auth_key { m_auth_key_storage, block_size };
OwnPtr<Authentication::GHash> m_ghash;
};
}
}