From 3880f66bd053d1f56af74852ca57ba166d880920 Mon Sep 17 00:00:00 2001
From: Donald Sharp <sharpd@nvidia.com>
Date: Mon, 20 Nov 2023 12:03:29 +0000
Subject: [PATCH 2/6] bgpd: Fix use beyond end of stream of labeled unicast
 parsing

Fixes a couple crashes associated with attempting to read
beyond the end of the stream.

Reported-by: Iggy Frankovic <iggyfran@amazon.com>
Signed-off-by: Donald Sharp <sharpd@nvidia.com>

CVE: CVE-2023-38407

Upstream-Status: Backport [https://github.com/FRRouting/frr/commit/7404a914b0cafe046703c8381903a80d3def8f8b]

Signed-off-by: Narpat Mali <narpat.mali@windriver.com>
---
 bgpd/bgp_label.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/bgpd/bgp_label.c b/bgpd/bgp_label.c
index 4a20f2c09..b65c98e86 100644
--- a/bgpd/bgp_label.c
+++ b/bgpd/bgp_label.c
@@ -299,6 +299,9 @@ static int bgp_nlri_get_labels(struct peer *peer, uint8_t *pnt, uint8_t plen,
	uint8_t llen = 0;
	uint8_t label_depth = 0;

+	if (plen < BGP_LABEL_BYTES)
+		return 0;
+
	for (; data < lim; data += BGP_LABEL_BYTES) {
		memcpy(label, data, BGP_LABEL_BYTES);
		llen += BGP_LABEL_BYTES;
@@ -361,6 +364,9 @@ int bgp_nlri_parse_label(struct peer *peer, struct attr *attr,
			memcpy(&addpath_id, pnt, BGP_ADDPATH_ID_LEN);
			addpath_id = ntohl(addpath_id);
			pnt += BGP_ADDPATH_ID_LEN;
+
+			if (pnt >= lim)
+				return BGP_NLRI_PARSE_ERROR_PACKET_OVERFLOW;
		}

		/* Fetch prefix length. */
@@ -379,6 +385,15 @@ int bgp_nlri_parse_label(struct peer *peer, struct attr *attr,

		/* Fill in the labels */
		llen = bgp_nlri_get_labels(peer, pnt, psize, &label);
+		if (llen == 0) {
+			flog_err(
+				EC_BGP_UPDATE_RCV,
+				"%s [Error] Update packet error (wrong label length 0)",
+				peer->host);
+			bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR,
+					BGP_NOTIFY_UPDATE_INVAL_NETWORK);
+			return BGP_NLRI_PARSE_ERROR_LABEL_LENGTH;
+		}
		p.prefixlen = prefixlen - BSIZE(llen);

		/* There needs to be at least one label */
--
2.40.0
