From 5ede437307cc3bbb20431f4b82f4a2ef79c9b746 Mon Sep 17 00:00:00 2001
From: Guus Sliepen <guus@tinc-vpn.org>
Date: Tue, 31 Jul 2012 20:36:35 +0200
Subject: [PATCH] Handle SPTPS datagrams in try_mac().

---
 src/net_packet.c |  3 +++
 src/sptps.c      | 14 ++++++++++++++
 src/sptps.h      |  1 +
 3 files changed, 18 insertions(+)

diff --git a/src/net_packet.c b/src/net_packet.c
index 4e651555..a744485f 100644
--- a/src/net_packet.c
+++ b/src/net_packet.c
@@ -252,6 +252,9 @@ static void receive_packet(node_t *n, vpn_packet_t *packet) {
 }
 
 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
+	if(experimental && OPTION_VERSION(n->options) >= 2)
+		return sptps_verify_datagram(&n->sptps, (char *)inpkt->data - 4, inpkt->len);
+
 	if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
 		return false;
 
diff --git a/src/sptps.c b/src/sptps.c
index 422940c9..12c6c7f0 100644
--- a/src/sptps.c
+++ b/src/sptps.c
@@ -376,6 +376,20 @@ static bool receive_handshake(sptps_t *s, const char *data, uint16_t len) {
 	}
 }
 
+// Check datagram for valid HMAC
+bool sptps_verify_datagram(sptps_t *s, const char *data, size_t len) {
+	if(!s->instate || len < 21)
+		return false;
+
+	char buffer[len + 23];
+	uint16_t netlen = htons(len - 21);
+
+	memcpy(buffer, &netlen, 2);
+	memcpy(buffer + 2, data, len);
+
+	return digest_verify(&s->indigest, buffer, len - 14, buffer + len - 14);
+}
+
 // Receive incoming data, datagram version.
 static bool sptps_receive_data_datagram(sptps_t *s, const char *data, size_t len) {
 	if(len < (s->instate ? 21 : 5))
diff --git a/src/sptps.h b/src/sptps.h
index d8ce3dae..0616ac7a 100644
--- a/src/sptps.h
+++ b/src/sptps.h
@@ -82,5 +82,6 @@ extern bool sptps_stop(sptps_t *s);
 extern bool sptps_send_record(sptps_t *s, uint8_t type, const char *data, uint16_t len);
 extern bool sptps_receive_data(sptps_t *s, const char *data, size_t len);
 extern bool sptps_force_kex(sptps_t *s);
+extern bool sptps_verify_datagram(sptps_t *s, const char *data, size_t len);
 
 #endif
-- 
2.39.5