Skip to content

Commit

Permalink
Replaced all calls to memcpy() with Bits_memcpy() and Bits_memcpyCons…
Browse files Browse the repository at this point in the history
…t(), the latter of which asserts __builtin_constant_p(length) at compile time.
  • Loading branch information
Caleb James DeLisle committed Apr 29, 2012
1 parent fe22709 commit bb32931
Show file tree
Hide file tree
Showing 37 changed files with 260 additions and 168 deletions.
10 changes: 9 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ if(HAS_CATCH_UNDEFINED)
add_definitions(-fcatch-undefined-behavior)
endif()

# __builtin_constant_p()
include(CheckCSourceCompiles)
check_c_source_compiles("int main() { return __builtin_constant_p(0);}" HAS_BUILTIN_CONSTANT_P)
if (HAS_BUILTIN_CONSTANT_P)
add_definitions("-D HAS_BUILTIN_CONSTANT_P")
endif()

# allow position independent executable to be turned off with NO_PIE cmake ..
if(NOT "$ENV{NO_PIE}" STREQUAL "")
set(NO_PIE TRUE)
Expand All @@ -83,6 +90,7 @@ else()
set(CMAKE_EXE_LINKER_FLAGS "${PIE}")
endif()

# logging
if(NOT $ENV{Log_LEVEL} STREQUAL "")
string(TOUPPER $ENV{Log_LEVEL} LEVEL)
message("Log_LEVEL = ${LEVEL}")
Expand All @@ -95,7 +103,7 @@ else()
endif()

# vrooooooom
add_definitions(-O3 -funroll-loops)
add_definitions(-O2 -funroll-loops)


if(NOT "$ENV{LTO}" STREQUAL "")
Expand Down
7 changes: 4 additions & 3 deletions admin/Admin.c
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include "io/Writer.h"
#include "memory/Allocator.h"
#include "memory/BufferAllocator.h"
#include "util/Bits.h"
#include "util/Hex.h"
#include "util/Log.h"
#include "util/Security.h"
Expand Down Expand Up @@ -502,8 +503,8 @@ void Admin_sendMessage(Dict* message, String* txid, struct Admin* admin)
StandardBencSerializer_get()->serializeDictionary(w, message);
size_t written = w->bytesWritten(w) + skip;
if (txid) {
memcpy(buff, "4567", 4);
memcpy(buff + 4, txid->bytes, 4);
Bits_memcpyConst(buff, "4567", 4);
Bits_memcpyConst(buff + 4, txid->bytes, 4);
}
write(admin->outFd, buff, written);
}
Expand Down Expand Up @@ -567,7 +568,7 @@ struct Admin* Admin_new(struct sockaddr_storage* addr,
admin->functionCount = 0;
admin->eventBase = eventBase;
admin->password = password;
memcpy(&admin->address, addr, sizeof(struct sockaddr_storage));
Bits_memcpyConst(&admin->address, addr, sizeof(struct sockaddr_storage));
admin->addressLength = addrLen;
admin->pipeEv = event_new(eventBase, inFd, EV_READ | EV_PERSIST, inFromChild, admin);
event_add(admin->pipeEv, NULL);
Expand Down
3 changes: 2 additions & 1 deletion benc/String.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/
#include "memory/Allocator.h"
#include "benc/String.h"
#include "util/Bits.h"

#include <string.h>
#include <stdio.h>
Expand All @@ -32,7 +33,7 @@ String* String_newBinary(const char* bytes, size_t length, const struct Allocato
// Make the string null terminated so it will print nicely.
copy[length] = '\0';
if (bytes != NULL) {
memcpy(copy, bytes, length);
Bits_memcpy(copy, bytes, length);
} else {
memset(copy, '\0', length);
}
Expand Down
15 changes: 8 additions & 7 deletions contrib/http/HttpServer.c
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
#include "memory/Allocator.h"
#include "memory/BufferAllocator.h"
#include "memory/MallocAllocator.h"
#include "util/Bits.h"

#define LIBSRVR_INDEX "text/html/index.html"
#define SECOND_SLASH_INDEX 9
Expand Down Expand Up @@ -157,9 +158,9 @@ static void fileHandler(struct evhttp_request* req, void* vcontext)
struct evkeyvalq* headers = evhttp_request_get_output_headers(req);

int offset = slash - uri;
memcpy(path, uri, offset);
char* charset = "; charset=UTF-8";
memcpy(path + offset, charset, strlen(charset) + 1);
Bits_memcpy(path, uri, offset);
#define CHARSET "; charset=UTF-8"
Bits_memcpyConst(path + offset, CHARSET, sizeof(CHARSET));
evhttp_add_header(headers, "Content-Type", path);

struct evbuffer* buff = NULL;
Expand Down Expand Up @@ -188,7 +189,7 @@ static void apiHandler(struct evhttp_request* req, void* vcontext)
return;
}

memcpy((char*)context->messageBuffer + 8, content, strlen(content));
Bits_memcpy((char*)context->messageBuffer + 8, content, strlen(content));

struct timeval now;
event_base_gettimeofday_cached(context->eventBase, &now);
Expand All @@ -213,8 +214,8 @@ static void apiHandler(struct evhttp_request* req, void* vcontext)
context->requests[i].request = req;
context->requests[i].time = now.tv_sec;
uint32_t txNum = context->txidBaseline + i;
memcpy(context->messageBuffer, "0123", 4);
memcpy(context->messageBuffer + 4, &txNum, 4);
Bits_memcpyConst(context->messageBuffer, "0123", 4);
Bits_memcpyConst(context->messageBuffer + 4, &txNum, 4);
write(context->apiSocket, context->messageBuffer, 8 + strlen(content));
fwrite(context->messageBuffer, 8 + strlen(content), 1, stdout);
printf("\n");
Expand Down Expand Up @@ -265,7 +266,7 @@ static void handleApiEvent(evutil_socket_t socket, short eventType, void* vconte
}

uint32_t txNum;
memcpy(&txNum, context->messageBuffer + 4, 4);
Bits_memcpyConst(&txNum, context->messageBuffer + 4, 4);

txNum -= context->txidBaseline;
if (txNum >= MAX_CONCURRENT_REQUESTS || !context->requests[txNum].request) {
Expand Down
4 changes: 2 additions & 2 deletions crypto/AddressCalc.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "crypto_hash_sha512.h"
#include "util/Bits.h"

#include <stdint.h>
#include <string.h>

void AddressCalc_addressForPublicKey(uint8_t addressOut[16], const uint8_t key[32])
{
uint8_t hash[crypto_hash_sha512_BYTES];
crypto_hash_sha512(hash, key, 32);
crypto_hash_sha512(hash, hash, crypto_hash_sha512_BYTES);
memcpy(addressOut, hash, 16);
Bits_memcpyConst(addressOut, hash, 16);
}
48 changes: 26 additions & 22 deletions crypto/CryptoAuth.c
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ static inline void printHexKey(uint8_t output[65], uint8_t key[32])
if (key) {
Hex_encode(output, 65, key, 32);
} else {
memcpy(output, "NULL", 5);
Bits_memcpyConst(output, "NULL", 5);
}
}

Expand Down Expand Up @@ -95,7 +95,7 @@ static inline void getSharedSecret(uint8_t outputSecret[32],
} buff;

crypto_scalarmult_curve25519(buff.components.key, myPrivateKey, herPublicKey);
memcpy(buff.components.passwd, passwordHash, 32);
Bits_memcpyConst(buff.components.passwd, passwordHash, 32);
crypto_hash_sha256(outputSecret, buff.bytes, 64);
}
#ifdef Log_KEYS
Expand All @@ -122,7 +122,7 @@ static inline void hashPassword_sha256(struct CryptoAuth_Auth* auth, const Strin
uint8_t tempBuff[32];
crypto_hash_sha256(auth->secret, (uint8_t*) password->bytes, password->len);
crypto_hash_sha256(tempBuff, auth->secret, 32);
memcpy(auth->challenge.bytes, tempBuff, Headers_AuthChallenge_SIZE);
Bits_memcpyConst(auth->challenge.bytes, tempBuff, Headers_AuthChallenge_SIZE);
Headers_setAuthChallengeDerivations(&auth->challenge, 0);
auth->challenge.challenge.type = 1;
}
Expand Down Expand Up @@ -167,7 +167,7 @@ static inline void getPasswordHash_typeOne(uint8_t output[32],
uint16_t derivations,
struct CryptoAuth_Auth* auth)
{
memcpy(output, auth->secret, 32);
Bits_memcpyConst(output, auth->secret, 32);
if (derivations) {
union {
uint8_t bytes[2];
Expand Down Expand Up @@ -218,15 +218,15 @@ static inline int decryptRndNonce(uint8_t nonce[24],
assert(msg->padding >= 16);
uint8_t* startAt = msg->bytes - 16;
uint8_t paddingSpace[16];
memcpy(paddingSpace, startAt, 16);
Bits_memcpyConst(paddingSpace, startAt, 16);
memset(startAt, 0, 16);
if (crypto_box_curve25519xsalsa20poly1305_open_afternm(
startAt, startAt, msg->length + 16, nonce, secret) != 0)
{
return -1;
}

memcpy(startAt, paddingSpace, 16);
Bits_memcpyConst(startAt, paddingSpace, 16);
Message_shift(msg, -16);
return 0;
}
Expand All @@ -247,12 +247,12 @@ static inline void encryptRndNonce(uint8_t nonce[24],
uint8_t* startAt = msg->bytes - 32;
// This function trashes 16 bytes of the padding so we will put it back
uint8_t paddingSpace[16];
memcpy(paddingSpace, startAt, 16);
Bits_memcpyConst(paddingSpace, startAt, 16);
memset(startAt, 0, 32);
crypto_box_curve25519xsalsa20poly1305_afternm(
startAt, startAt, msg->length + 32, nonce, secret);

memcpy(startAt, paddingSpace, 16);
Bits_memcpyConst(startAt, paddingSpace, 16);
Message_shift(msg, 16);
}

Expand Down Expand Up @@ -392,7 +392,7 @@ static uint8_t encryptHandshake(struct Message* message, struct CryptoAuth_Wrapp

// garbage the auth field to frustrate DPI and set the nonce (next 24 bytes after the auth)
randombytes((uint8_t*) &header->handshake.auth, sizeof(union Headers_AuthChallenge) + 24);
memcpy(&header->handshake.publicKey, wrapper->context->publicKey, 32);
Bits_memcpyConst(&header->handshake.publicKey, wrapper->context->publicKey, 32);

if (!knowHerKey(wrapper)) {
return genReverseHandshake(message, wrapper, header);
Expand All @@ -403,7 +403,9 @@ static uint8_t encryptHandshake(struct Message* message, struct CryptoAuth_Wrapp
struct CryptoAuth_Auth auth;
if (wrapper->password != NULL) {
passwordHash = hashPassword(&auth, wrapper->password, wrapper->authType);
memcpy(header->handshake.auth.bytes, &auth.challenge, sizeof(union Headers_AuthChallenge));
Bits_memcpyConst(header->handshake.auth.bytes,
&auth.challenge,
sizeof(union Headers_AuthChallenge));
}
header->handshake.auth.challenge.type = wrapper->authType;

Expand All @@ -428,7 +430,7 @@ static uint8_t encryptHandshake(struct Message* message, struct CryptoAuth_Wrapp
tempPrivateKeyHex, tempPubKeyHex);
#endif
if (wrapper->nextNonce == 0) {
memcpy(wrapper->tempKey, header->handshake.encryptedTempKey, 32);
Bits_memcpyConst(wrapper->tempKey, header->handshake.encryptedTempKey, 32);
}
#ifdef Log_DEBUG
assert(!Bits_isZero(header->handshake.encryptedTempKey, 32));
Expand All @@ -445,7 +447,7 @@ static uint8_t encryptHandshake(struct Message* message, struct CryptoAuth_Wrapp
// Dupe hello
// wrapper->nextNonce == 1
// Our public key is cached in wrapper->tempKey so lets copy it out.
memcpy(header->handshake.encryptedTempKey, wrapper->tempKey, 32);
Bits_memcpyConst(header->handshake.encryptedTempKey, wrapper->tempKey, 32);
}
#ifdef Log_KEYS
uint8_t tempKeyHex[65];
Expand Down Expand Up @@ -590,7 +592,7 @@ static uint8_t sendMessage(struct Message* message, struct Interface* interface)
wrapper->tempKey,
NULL,
wrapper->context->logger);
memcpy(wrapper->secret, secret, 32);
Bits_memcpyConst(wrapper->secret, secret, 32);
}
}

Expand Down Expand Up @@ -670,7 +672,7 @@ static uint8_t decryptHandshake(struct CryptoAuth_Wrapper* wrapper,
// have received a valid packet from them.
// We can't allow the upper layer to see this message because it's not authenticated.
if (!knowHerKey(wrapper)) {
memcpy(wrapper->herPerminentPubKey, header->handshake.publicKey, 32);
Bits_memcpyConst(wrapper->herPerminentPubKey, header->handshake.publicKey, 32);
}
Message_shift(message, -Headers_CryptoAuth_SIZE);
message->length = 0;
Expand Down Expand Up @@ -783,7 +785,7 @@ static uint8_t decryptHandshake(struct CryptoAuth_Wrapper* wrapper,
}

wrapper->user = user;
memcpy(wrapper->tempKey, header->handshake.encryptedTempKey, 32);
Bits_memcpyConst(wrapper->tempKey, header->handshake.encryptedTempKey, 32);

#ifdef Log_DEBUG
assert(!Bits_isZero(header->handshake.encryptedTempKey, 32));
Expand All @@ -803,7 +805,7 @@ static uint8_t decryptHandshake(struct CryptoAuth_Wrapper* wrapper,
wrapper->isInitiator = false;
}
if (herPermKey && herPermKey != wrapper->herPerminentPubKey) {
memcpy(wrapper->herPerminentPubKey, herPermKey, 32);
Bits_memcpyConst(wrapper->herPerminentPubKey, herPermKey, 32);
}

// If this is a handshake which was initiated in reverse because we
Expand Down Expand Up @@ -853,7 +855,7 @@ static uint8_t receiveMessage(struct Message* received, struct Interface* interf
if (decryptMessage(wrapper, nonce, received, secret)) {
Log_debug(wrapper->context->logger, "Final handshake step succeeded.\n");
wrapper->nextNonce += 3;
memcpy(wrapper->secret, secret, 32);
Bits_memcpyConst(wrapper->secret, secret, 32);
return Error_NONE;
}
CryptoAuth_reset(&wrapper->externalInterface);
Expand Down Expand Up @@ -893,7 +895,7 @@ struct CryptoAuth* CryptoAuth_new(Dict* config,
}

if (privateKey != NULL) {
memcpy(ca->privateKey, privateKey, 32);
Bits_memcpyConst(ca->privateKey, privateKey, 32);
crypto_scalarmult_curve25519_base(ca->publicKey, ca->privateKey);
} else {
crypto_box_curve25519xsalsa20poly1305_keypair(ca->publicKey, ca->privateKey);
Expand Down Expand Up @@ -933,7 +935,9 @@ int32_t CryptoAuth_addUser(String* password,
}
}
a.user = user;
memcpy(&context->passwords[context->passwordCount], &a, sizeof(struct CryptoAuth_Auth));
Bits_memcpyConst(&context->passwords[context->passwordCount],
&a,
sizeof(struct CryptoAuth_Auth));
context->passwordCount++;
return 0;
}
Expand Down Expand Up @@ -986,10 +990,10 @@ struct Interface* CryptoAuth_wrapInterface(struct Interface* toWrap,
.sendMessage = sendMessage,
.allocator = toWrap->allocator
};
memcpy(&wrapper->externalInterface, &iface, sizeof(struct Interface));
Bits_memcpyConst(&wrapper->externalInterface, &iface, sizeof(struct Interface));

if (herPublicKey != NULL) {
memcpy(wrapper->herPerminentPubKey, herPublicKey, 32);
Bits_memcpyConst(wrapper->herPerminentPubKey, herPublicKey, 32);
}

return &wrapper->externalInterface;
Expand All @@ -1008,7 +1012,7 @@ void CryptoAuth_setAuth(const String* password,

void CryptoAuth_getPublicKey(uint8_t output[32], struct CryptoAuth* context)
{
memcpy(output, context->publicKey, 32);
Bits_memcpyConst(output, context->publicKey, 32);
}

uint8_t* CryptoAuth_getHerPublicKey(struct Interface* interface)
Expand Down
9 changes: 5 additions & 4 deletions crypto/test/CryptoAuth_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "io/FileWriter.h"
#include "benc/Object.h"
#include "memory/MallocAllocator.h"
#include "util/Bits.h"
#include "util/Hex.h"
#include "util/Endian.h"
#include "wire/Error.h"
Expand Down Expand Up @@ -47,10 +48,10 @@ static struct Message msg;
static uint8_t* textBuff;
#define ALIGNED_LEN(x) (strlen(x) + 4 - (strlen(x) % 4))
#define MK_MSG(x) \
memset(textBuff, 0, BUFFER_SIZE); \
memcpy(&textBuff[BUFFER_SIZE - ALIGNED_LEN(x)], x, strlen(x)); \
msg.length = strlen(x); \
msg.bytes = textBuff + BUFFER_SIZE - ALIGNED_LEN(x); \
memset(textBuff, 0, BUFFER_SIZE); \
Bits_memcpy(&textBuff[BUFFER_SIZE - ALIGNED_LEN(x)], x, strlen(x)); \
msg.length = strlen(x); \
msg.bytes = textBuff + BUFFER_SIZE - ALIGNED_LEN(x); \
msg.padding = BUFFER_SIZE - ALIGNED_LEN(x)

static uint8_t* if1Msg;
Expand Down
Loading

0 comments on commit bb32931

Please sign in to comment.