Skip to content

Commit 13648ec

Browse files
authored
Adding Validity-Checks for incoming packets (#2)
* Add Declaration for isValid() * Added isValid() and modified implementation of forceUpdate()
1 parent 957af4d commit 13648ec

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

NTPClient.cpp

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,30 @@ void NTPClient::begin(int port) {
6060
this->_udpSetup = true;
6161
}
6262

63+
bool NTPClient::isValid(byte * ntpPacket)
64+
{
65+
//Perform a few validity checks on the packet
66+
if((ntpPacket[0] & 0b11000000) == 0b11000000) //Check for LI=UNSYNC
67+
return false;
68+
69+
if((ntpPacket[0] & 0b00111000) >> 3 < 0b100) //Check for Version >= 4
70+
return false;
71+
72+
if((ntpPacket[0] & 0b00000111) != 0b100) //Check for Mode == Server
73+
return false;
74+
75+
if((ntpPacket[1] < 1) || (ntpPacket[1] > 15)) //Check for valid Stratum
76+
return false;
77+
78+
if( ntpPacket[16] == 0 && ntpPacket[17] == 0 &&
79+
ntpPacket[18] == 0 && ntpPacket[19] == 0 &&
80+
ntpPacket[20] == 0 && ntpPacket[21] == 0 &&
81+
ntpPacket[22] == 0 && ntpPacket[22] == 0) //Check for ReferenceTimestamp != 0
82+
return false;
83+
84+
return true;
85+
}
86+
6387
bool NTPClient::forceUpdate() {
6488
#ifdef DEBUG_NTPClient
6589
Serial.println("Update from NTP Server");
@@ -73,14 +97,20 @@ bool NTPClient::forceUpdate() {
7397
do {
7498
delay ( 10 );
7599
cb = this->_udp->parsePacket();
100+
101+
if(cb > 0)
102+
{
103+
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
104+
if(!this->isValid(this->_packetBuffer))
105+
cb = 0;
106+
}
107+
76108
if (timeout > 100) return false; // timeout after 1000 ms
77109
timeout++;
78110
} while (cb == 0);
79111

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

82-
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
83-
84114
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
85115
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
86116
// combine the four bytes (two words) into a long integer

NTPClient.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class NTPClient {
2525
byte _packetBuffer[NTP_PACKET_SIZE];
2626

2727
void sendNTPPacket();
28+
bool isValid(byte * ntpPacket);
2829

2930
public:
3031
NTPClient(UDP& udp);

0 commit comments

Comments
 (0)