Skip to content
This repository has been archived by the owner on Sep 1, 2022. It is now read-only.

Commit

Permalink
Crypto: rewrite preexisting refactor. Fixes #164.
Browse files Browse the repository at this point in the history
* Redesign/refactor: the previous design was unnecessary in terms of
  organization and the logic was askew. Rewrite with maintainability in mind
* Within the realm of Signature and ElGamal, refactor out the unfinished
  cryptopp
* Finish the unfinished RNG-related refactor:
  - Swapout appropriate CryptoPP with Rand*-related calls
  - Creation of class DiffieHellman
  - Moving of CryptoConst into pimpl directory
* Cleanup related files that still call cryptopp
* C++11/style guideline refactor for touched files
* Add Crypto++ CMake build option + related pimpl src dir handling
* Various cleanups + add documentation
  • Loading branch information
anonimal committed Apr 14, 2016
1 parent aa3124f commit 5beae18
Show file tree
Hide file tree
Showing 33 changed files with 1,331 additions and 1,283 deletions.
10 changes: 7 additions & 3 deletions CMakeLists.txt
Expand Up @@ -6,6 +6,7 @@ option(KOVRI_DATA_PATH "The path to the kovri data folder")
option(WITH_AESNI "Use AES-NI instructions set" OFF)
option(WITH_BENCHMARKS "Build with benchmarks" OFF)
option(WITH_BINARY "Build binary" ON)
option(WITH_CRYPTOPP "Build with Crypto++" ON) # Default ON unless we switch libraries
option(WITH_DOXYGEN "Enable support for Doxygen" OFF)
option(WITH_HARDENING "Use hardening compiler flags" OFF)
option(WITH_LIBRARY "Build library" ON)
Expand Down Expand Up @@ -133,9 +134,11 @@ else()
add_definitions(-DBOOST_ALL_DYN_LINK)
endif()

find_package(CryptoPP REQUIRED)
if(NOT DEFINED CRYPTO++_INCLUDE_DIR)
message(SEND_ERROR "Could not find Crypto++. Please download and install it first!")
if(WITH_CRYPTOPP)
find_package(CryptoPP REQUIRED)
if(NOT DEFINED CRYPTO++_INCLUDE_DIR)
message(SEND_ERROR "Could not find Crypto++. Please download and install it first!")
endif()
endif()

if(APPLE)
Expand Down Expand Up @@ -190,6 +193,7 @@ message(STATUS "Options:")
message(STATUS " AESNI : ${WITH_AESNI}")
message(STATUS " BENCHMARKS : ${WITH_BENCHMARKS}")
message(STATUS " BINARY : ${WITH_BINARY}")
message(STATUS " CRYPTOPP : ${WITH_CRYPTOPP}")
message(STATUS " DOXYGEN : ${WITH_DOXYGEN}")
message(STATUS " HARDENING : ${WITH_HARDENING}")
message(STATUS " LIBRARY : ${WITH_LIBRARY}")
Expand Down
7 changes: 3 additions & 4 deletions src/client/AddressBook.cpp
Expand Up @@ -35,8 +35,6 @@
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>

#include <cryptopp/osrng.h>

#include <inttypes.h>
#include <string.h>
#include <string>
Expand All @@ -49,6 +47,7 @@
#include "Destination.h"
#include "Identity.h"
#include "NetworkDatabase.h"
#include "crypto/Rand.h"
#include "util/HTTP.h"
#include "util/Log.h"

Expand Down Expand Up @@ -446,8 +445,8 @@ void AddressBook::HandleSubscriptionsUpdateTimer(
if (m_IsLoaded && !m_IsDownloading &&
m_SharedLocalDestination->IsReady()) {
// pick random subscription
CryptoPP::AutoSeededRandomPool rnd;
auto ind = rnd.GenerateWord32(0, m_Subscriptions.size() - 1);
auto ind =
i2p::crypto::RandInRange<std::size_t>(0, m_Subscriptions.size() - 1);
m_IsDownloading = true;
m_Subscriptions[ind]->CheckSubscription();
} else {
Expand Down
8 changes: 3 additions & 5 deletions src/client/Destination.cpp
Expand Up @@ -669,11 +669,9 @@ bool ClientDestination::SendLeaseSetRequest(
request->excluded.insert(nextFloodfill->GetIdentHash());
request->requestTime = i2p::util::GetSecondsSinceEpoch();
request->requestTimeoutTimer.cancel();
CryptoPP::AutoSeededRandomPool rnd;
uint8_t replyKey[32],
replyTag[32];
rnd.GenerateBlock(replyKey, 32); // random session key
rnd.GenerateBlock(replyTag, 32); // random session tag
uint8_t replyKey[32], replyTag[32];
i2p::crypto::RandBytes(replyKey, 32); // random session key
i2p::crypto::RandBytes(replyTag, 32); // random session tag
AddSessionKey(replyKey, replyTag);
auto msg =
WrapMessage(
Expand Down
1 change: 0 additions & 1 deletion src/client/Destination.h
Expand Up @@ -49,7 +49,6 @@
#include "NetworkDatabase.h"
#include "Datagram.h"
#include "Streaming.h"
#include "crypto/CryptoConst.h"
#include "tunnel/TunnelPool.h"

namespace i2p {
Expand Down
9 changes: 4 additions & 5 deletions src/client/I2PControl/I2PControl.cpp
Expand Up @@ -36,16 +36,16 @@

#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/osrng.h>

#include <iomanip>
#include <sstream>
#include <string>

#include "core/RouterContext.h"
#include "core/NetworkDatabase.h"
#include "client/ClientContext.h"
#include "core/NetworkDatabase.h"
#include "core/RouterContext.h"
#include "core/Version.h"
#include "crypto/Rand.h"
#include "transport/Transports.h"
#include "tunnel/Tunnel.h"
#include "util/Log.h"
Expand Down Expand Up @@ -346,8 +346,7 @@ bool I2PControlSession::Authenticate(

std::string I2PControlSession::GenerateToken() const {
byte random_data[constants::TOKEN_SIZE] = {};
CryptoPP::AutoSeededRandomPool rng;
rng.GenerateBlock(random_data, constants::TOKEN_SIZE);
i2p::crypto::RandBytes(random_data, constants::TOKEN_SIZE);
std::string token;
CryptoPP::StringSource ss(
random_data,
Expand Down
19 changes: 12 additions & 7 deletions src/core/CMakeLists.txt
@@ -1,5 +1,4 @@
set(CORE_SRC
"tunnel/TunnelConfig.cpp"
"Garlic.cpp"
"I2NPProtocol.cpp"
"Identity.cpp"
Expand All @@ -11,11 +10,7 @@ set(CORE_SRC
"RouterContext.cpp"
"RouterInfo.cpp"
"crypto/AES.cpp"
"crypto/CryptoConst.cpp"
"crypto/EdDSA25519.cpp"
"crypto/ElGamal.cpp"
"crypto/Rand.cpp"
"crypto/Signature.cpp"
"crypto/Tunnel.cpp"
"transport/NTCP.cpp"
"transport/NTCPSession.cpp"
Expand All @@ -26,6 +21,7 @@ set(CORE_SRC
"transport/UPnP.cpp"
"tunnel/TransitTunnel.cpp"
"tunnel/Tunnel.cpp"
"tunnel/TunnelConfig.cpp"
"tunnel/TunnelEndpoint.cpp"
"tunnel/TunnelGateway.cpp"
"tunnel/TunnelPool.cpp"
Expand All @@ -36,9 +32,18 @@ set(CORE_SRC
"util/Filesystem.cpp"
"util/ZIP.cpp")

if(WITH_CRYPTOPP)
set(CRYPTO_PIMPL_DIR "crypto/pimpl/cryptopp")
endif()

set(CRYPTO_PIMPL_SRC
"crypto/pimpl/cryptopp/ZIP.cpp"
"crypto/pimpl/cryptopp/X509.cpp")
"${CRYPTO_PIMPL_DIR}/CryptoConst.cpp"
"${CRYPTO_PIMPL_DIR}/DiffieHellman.cpp"
"${CRYPTO_PIMPL_DIR}/ElGamal.cpp"
"${CRYPTO_PIMPL_DIR}/Rand.cpp"
"${CRYPTO_PIMPL_DIR}/Signature.cpp"
"${CRYPTO_PIMPL_DIR}/X509.cpp"
"${CRYPTO_PIMPL_DIR}/ZIP.cpp")

set(EDDSA_SRC
"crypto/ed25519/fe_0.cpp"
Expand Down
29 changes: 17 additions & 12 deletions src/core/Garlic.cpp
Expand Up @@ -39,11 +39,12 @@
#include "I2NPProtocol.h"
#include "RouterContext.h"
#include "client/Destination.h"
#include "crypto/Rand.h"
#include "tunnel/Tunnel.h"
#include "tunnel/TunnelPool.h"
#include "util/I2PEndian.h"
#include "util/Timestamp.h"
#include "util/Log.h"
#include "util/Timestamp.h"

namespace i2p {
namespace garlic {
Expand All @@ -59,7 +60,7 @@ GarlicRoutingSession::GarlicRoutingSession(
m_LeaseSetUpdateStatus(
attachLeaseSet ? eLeaseSetUpdated : eLeaseSetDoNotSend) {
// create new session tags and session key
m_Rnd.GenerateBlock(m_SessionKey, 32);
i2p::crypto::RandBytes(m_SessionKey, 32);
m_Encryption.SetKey(m_SessionKey);
}

Expand Down Expand Up @@ -87,7 +88,7 @@ GarlicRoutingSession::GenerateSessionTags() {
auto tags = new UnconfirmedTags(m_NumTags);
tags->tagsCreationTime = i2p::util::GetSecondsSinceEpoch();
for (int i = 0; i < m_NumTags; i++) {
m_Rnd.GenerateBlock(tags->sessionTags[i], 32);
i2p::crypto::RandBytes(tags->sessionTags[i], 32);
tags->sessionTags[i].creationTime = tags->tagsCreationTime;
}
return tags;
Expand Down Expand Up @@ -173,7 +174,7 @@ std::shared_ptr<I2NPMessage> GarlicRoutingSession::WrapSingleMessage(
// create ElGamal block
ElGamalBlock elGamal;
memcpy(elGamal.sessionKey, m_SessionKey, 32);
m_Rnd.GenerateBlock(elGamal.preIV, 32); // Pre-IV
i2p::crypto::RandBytes(elGamal.preIV, 32); // Pre-IV
uint8_t iv[32]; // IV is first 16 bytes
CryptoPP::SHA256().CalculateDigest(iv, elGamal.preIV, 32);
m_Destination->GetElGamalEncryption()->Encrypt(
Expand Down Expand Up @@ -236,9 +237,9 @@ size_t GarlicRoutingSession::CreateGarlicPayload(
std::shared_ptr<const I2NPMessage> msg,
UnconfirmedTags* newTags) {
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch() + 5000; // 5 sec
uint32_t msgID = m_Rnd.GenerateWord32();
uint32_t msgID = i2p::crypto::Rand<std::uint32_t>();
size_t size = 0;
uint8_t * numCloves = payload + size;
uint8_t* numCloves = payload + size;
*numCloves = 0;
size++;
if (m_Owner) {
Expand Down Expand Up @@ -307,7 +308,8 @@ size_t GarlicRoutingSession::CreateGarlicClove(
}
memcpy(buf + size, msg->GetBuffer(), msg->GetLength());
size += msg->GetLength();
htobe32buf(buf + size, m_Rnd.GenerateWord32()); // CloveID
// CloveID
htobe32buf(buf + size, i2p::crypto::Rand<std::uint32_t>());
size += 4;
htobe64buf(buf + size, ts); // Expiration of clove
size += 8;
Expand Down Expand Up @@ -336,8 +338,8 @@ size_t GarlicRoutingSession::CreateDeliveryStatusClove(
if (m_Owner) {
// encrypt
uint8_t key[32], tag[32];
m_Rnd.GenerateBlock(key, 32); // random session key
m_Rnd.GenerateBlock(tag, 32); // random session tag
i2p::crypto::RandBytes(key, 32); // random session key
i2p::crypto::RandBytes(tag, 32); // random session tag
m_Owner->SubmitSessionKey(key, tag);
GarlicRoutingSession garlic(key, tag);
msg = garlic.WrapSingleMessage(msg);
Expand All @@ -346,7 +348,8 @@ size_t GarlicRoutingSession::CreateDeliveryStatusClove(
size += msg->GetLength();
// fill clove
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch() + 5000; // 5 sec
htobe32buf(buf + size, m_Rnd.GenerateWord32()); // CloveID
// CloveID
htobe32buf(buf + size, i2p::crypto::Rand<std::uint32_t>());
size += 4;
htobe64buf(buf + size, ts); // Expiration of clove
size += 8;
Expand Down Expand Up @@ -411,8 +414,10 @@ void GarlicDestination::HandleGarlicMessage(
ElGamalBlock elGamal;
if (length >= 514 &&
i2p::crypto::ElGamalDecrypt(
GetEncryptionPrivateKey(), buf,
reinterpret_cast<uint8_t *>(&elGamal), true)) {
GetEncryptionPrivateKey(),
buf,
reinterpret_cast<std::uint8_t *>(&elGamal),
true)) {
auto decryption = std::make_shared<i2p::crypto::CBCDecryption>();
decryption->SetKey(elGamal.sessionKey);
uint8_t iv[32]; // IV is first 16 bytes
Expand Down
3 changes: 0 additions & 3 deletions src/core/Garlic.h
Expand Up @@ -33,8 +33,6 @@
#ifndef SRC_CORE_GARLIC_H_
#define SRC_CORE_GARLIC_H_

#include <cryptopp/osrng.h>

#include <inttypes.h>

#include <list>
Expand Down Expand Up @@ -168,7 +166,6 @@ class GarlicRoutingSession
uint64_t m_LeaseSetSubmissionTime; // in milliseconds

i2p::crypto::CBCEncryption m_Encryption;
CryptoPP::AutoSeededRandomPool m_Rnd;
};

class GarlicDestination : public i2p::data::LocalDestination {
Expand Down
10 changes: 1 addition & 9 deletions src/core/Identity.cpp
Expand Up @@ -30,22 +30,14 @@
* Parts of the project are originally copyright (c) 2013-2015 The PurpleI2P Project
*/

// TODO(unassigned): use crypto/DSA.h
#include <cryptopp/dsa.h>
// TODO(unassigned): use crypto/SHA.h
#include <cryptopp/sha.h>

#include <cryptopp/dh.h>

#include <stdio.h>
#include <time.h>

#include <string>

#include "Identity.h"
#include "RouterContext.h"
#include "crypto/CryptoConst.h"
#include "crypto/pimpl/cryptopp/Rand.h"
#include "crypto/EdDSA25519.h"
#include "crypto/ElGamal.h"
#include "crypto/Rand.h"
#include "crypto/Signature.h"
Expand Down
6 changes: 2 additions & 4 deletions src/core/LeaseSet.cpp
Expand Up @@ -33,14 +33,13 @@
#include "LeaseSet.h"

#include <cryptopp/dsa.h>
#include <cryptopp/osrng.h>

#include <string.h>

#include <vector>

#include "NetworkDatabase.h"
#include "crypto/CryptoConst.h"
#include "crypto/Rand.h"
#include "tunnel/TunnelPool.h"
#include "util/I2PEndian.h"
#include "util/Log.h"
Expand Down Expand Up @@ -88,7 +87,6 @@ LeaseSet::LeaseSet(
m_Buffer[m_BufferLen] = tunnels.size(); // num leases
m_BufferLen++;
// leases
CryptoPP::AutoSeededRandomPool rnd;
for (auto it : tunnels) {
memcpy(m_Buffer + m_BufferLen, it->GetNextIdentHash(), 32);
m_BufferLen += 32; // gateway id
Expand All @@ -99,7 +97,7 @@ LeaseSet::LeaseSet(
i2p::tunnel::TUNNEL_EXPIRATION_TIMEOUT -
i2p::tunnel::TUNNEL_EXPIRATION_THRESHOLD; // 1 minute before expiration
ts *= 1000; // in milliseconds
ts += rnd.GenerateWord32(0, 5); // + random milliseconds
ts += i2p::crypto::RandInRange<std::size_t>(0, 5); // + random milliseconds
htobe64buf(m_Buffer + m_BufferLen, ts);
m_BufferLen += 8; // end date
}
Expand Down
1 change: 0 additions & 1 deletion src/core/RouterContext.cpp
Expand Up @@ -43,7 +43,6 @@
#include "I2NPProtocol.h"
#include "NetworkDatabase.h"
#include "Version.h"
#include "crypto/CryptoConst.h"
#include "util/MTU.h"
#include "util/Timestamp.h"
#include "util/Filesystem.h"
Expand Down
1 change: 0 additions & 1 deletion src/core/RouterInfo.cpp
Expand Up @@ -45,7 +45,6 @@
#include <vector>

#include "RouterContext.h"
#include "crypto/CryptoConst.h"
#include "util/Base64.h"
#include "util/I2PEndian.h"
#include "util/Log.h"
Expand Down

0 comments on commit 5beae18

Please sign in to comment.