Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Validity-Checks for incoming packets #28

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions NTPClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,30 @@ void NTPClient::begin(int port) {
this->_udpSetup = true;
}

bool NTPClient::isValid(byte * ntpPacket)
{
//Perform a few validity checks on the packet
if((ntpPacket[0] & 0b11000000) == 0b11000000) //Check for LI=UNSYNC
return false;

if((ntpPacket[0] & 0b00111000) >> 3 < 0b100) //Check for Version >= 4
return false;

if((ntpPacket[0] & 0b00000111) != 0b100) //Check for Mode == Server
return false;

if((ntpPacket[1] < 1) || (ntpPacket[1] > 15)) //Check for valid Stratum
return false;

if( ntpPacket[16] == 0 && ntpPacket[17] == 0 &&
ntpPacket[18] == 0 && ntpPacket[19] == 0 &&
ntpPacket[20] == 0 && ntpPacket[21] == 0 &&
ntpPacket[22] == 0 && ntpPacket[22] == 0) //Check for ReferenceTimestamp != 0
return false;

return true;
}

bool NTPClient::forceUpdate() {
#ifdef DEBUG_NTPClient
Serial.println("Update from NTP Server");
Expand All @@ -73,14 +97,20 @@ bool NTPClient::forceUpdate() {
do {
delay ( 10 );
cb = this->_udp->parsePacket();

if(cb > 0)
{
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
if(!this->isValid(this->_packetBuffer))
cb = 0;
}

if (timeout > 100) return false; // timeout after 1000 ms
timeout++;
} while (cb == 0);

this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time

this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);

unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
Expand Down
1 change: 1 addition & 0 deletions NTPClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class NTPClient {
byte _packetBuffer[NTP_PACKET_SIZE];

void sendNTPPacket();
bool isValid(byte * ntpPacket);

public:
NTPClient(UDP& udp);
Expand Down