diff --git a/ethermess.c b/ethermess.c index 473f4ec..38be5ad 100644 --- a/ethermess.c +++ b/ethermess.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -16,6 +17,7 @@ #include #include #include +#include #include #include @@ -33,6 +35,7 @@ bool running = true; int packet_socket; +int urandom; unsigned char own_mac[6]; unsigned char broadcast_mac[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; @@ -75,8 +78,11 @@ ssize_t msgid_cache_add(const unsigned char mac[6]) { // If we are adding into a new slot (instead of overwriting one), // expand the fill pointer - if (msgid_cache_fill < index) { - msgid_cache_fill++; + // + // + 1 because msgid_cache_fill of N means that cache slots [0, N-1] + // are in use + if (msgid_cache_fill < index + 1) { + msgid_cache_fill = index + 1; } memcpy(msgid_cache[index].other_mac, mac, sizeof(msgid_cache[index].other_mac)); @@ -86,6 +92,15 @@ ssize_t msgid_cache_add(const unsigned char mac[6]) { return index; } +unsigned char random_byte(void) { + unsigned char randomness; + errno = 0; + if (read(urandom, &randomness, 1) != 1) { + err(1, "read"); + } + return randomness; +} + char hexify(int nybble) { assert(0 <= nybble && nybble <= 16); return "0123456789abcdef"[nybble]; @@ -199,9 +214,8 @@ void send_msgid(const unsigned char destination[6]) { if (!msgid_cache[cache_index].know_receive) { // We don't have receive ID stored in the cache - // In that case, start from 0 - // TODO: Make it random instead - msgid_cache[cache_index].next_receive = 0; + // In that case, start from a random index + msgid_cache[cache_index].next_receive = (random_byte() << 8) | random_byte(); msgid_cache[cache_index].know_receive = true; } @@ -215,6 +229,7 @@ void send_msgid(const unsigned char destination[6]) { } void read_command(void) { + errno = 0; int cmd = getchar(); if (cmd == EOF) { err(1, "getchar"); @@ -356,7 +371,7 @@ void process_frame(void) { errno = 0; ssize_t res = recv(packet_socket, frame, sizeof(frame), 0); if (res == -1) { - errx(1, "recv"); + err(1, "recv"); } else if (res < 16) { // Frame too short to contain enough information return; @@ -480,6 +495,9 @@ int main(int argc, char **argv) { const char *interface_name = argv[1]; + // Open /dev/urandom for getting randomness + urandom = open("/dev/urandom", O_RDONLY); + // Create a packet socket errno = 0; packet_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); @@ -545,5 +563,11 @@ int main(int argc, char **argv) { err(1, "fflush"); } + // Close urandom + errno = 0; + if (close(urandom) == -1) { + err(1, "close"); + } + return 0; }