Refactor extract_prefix() to first do the length checks and only then
authorclaudio <claudio@openbsd.org>
Thu, 30 Mar 2023 14:47:25 +0000 (14:47 +0000)
committerclaudio <claudio@openbsd.org>
Thu, 30 Mar 2023 14:47:25 +0000 (14:47 +0000)
copy the data out.
OK tb@

usr.sbin/bgpd/util.c

index 2163fb1..85f15a6 100644 (file)
@@ -1,4 +1,4 @@
-/*     $OpenBSD: util.c,v 1.74 2023/01/04 14:33:30 claudio Exp $ */
+/*     $OpenBSD: util.c,v 1.75 2023/03/30 14:47:25 claudio Exp $ */
 
 /*
  * Copyright (c) 2006 Claudio Jeker <claudio@openbsd.org>
@@ -495,25 +495,23 @@ aspath_inflate(void *data, uint16_t len, uint16_t *newlen)
 
 /* NLRI functions to extract prefixes from the NLRI blobs */
 static int
-extract_prefix(u_char *p, uint16_t len, void *va,
-    uint8_t pfxlen, uint8_t max)
+extract_prefix(u_char *p, uint16_t len, void *va, uint8_t pfxlen, uint8_t max)
 {
        static u_char    addrmask[] = {
            0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
        u_char          *a = va;
-       int              i;
-       uint16_t         plen = 0;
+       int              plen;
 
-       for (i = 0; pfxlen && i < max; i++) {
-               if (len <= plen)
-                       return (-1);
+       plen = PREFIX_SIZE(pfxlen) - 1;
+       if (len < plen || max < plen)
+               return -1;
+
+       while (pfxlen > 0) {
                if (pfxlen < 8) {
-                       a[i] = *p++ & addrmask[pfxlen];
-                       plen++;
+                       *a++ = *p++ & addrmask[pfxlen];
                        break;
                } else {
-                       a[i] = *p++;
-                       plen++;
+                       *a++ = *p++;
                        pfxlen -= 8;
                }
        }