Reputation: 20035
What is the proper way or technique in framing with TCP?
I have created a simple framer in my node.js server that frames each message as they come-in where the 1st byte is the packet size.
One problem though: What if a user purposely sends an invalid packet.
Something like:
0A 00 03 04 05
We can tell that this is a broken packet, 0A
is the size but we can see that the actual size is only 05
.
How can we prevent such attacks?
Upvotes: 1
Views: 975
Reputation: 171206
Simply validate all input. If the client sends "N bytes coming" then read N bytes. If you read less (because the stream is depleted before you get N bytes) interpret that as a connection problem or a bug somewhere, log the event and abort the connection.
Upvotes: 0
Reputation: 101150
You can't since there is nothing in your protocol that allows you to validate that the specified size is correct.
You could append a control character to every message (for instance ascii 03):
<length><body><footer char>
But then an attacker could write:
03 32 32 32 03 32 32 32
Your validation would work, but the next message would be screwed.
The only way to prevent that is make sure that the actual body contains reasonable values and disconnect the client if it doesn't.
Upvotes: 0
Reputation: 3541
TCP is stream based and does not work on boundaries. So recv()
returning partial data can be genuine. Or there can be invalid peer who just wants to mess up the connection. TCP will not help. The onus is on application to take action.
If the data is not fully received (as many as the length bytes indicate) the application must have the logic to give up. May be a timer on whose expiry the application shall mark the connection as invalid and then do close()
.
Upvotes: 1
Reputation: 310980
If you receive rubbish, just close the socket. No point in persisting. The peer doesn't speak your language, or is deliberately trying to crash you or exploit vulnerabilities. Don't let him.
Upvotes: 1