git: 221c09cab60a - stable/15 - ngctl: Check hook name length

From: Dag-Erling Smørgrav <des_at_FreeBSD.org>
Date: Tue, 17 Feb 2026 23:57:59 UTC
The branch stable/15 has been updated by des:

URL: https://cgit.FreeBSD.org/src/commit/?id=221c09cab60a8257b41be9067f1712d77ba828d8

commit 221c09cab60a8257b41be9067f1712d77ba828d8
Author:     Dag-Erling Smørgrav <des@FreeBSD.org>
AuthorDate: 2026-02-13 15:57:46 +0000
Commit:     Dag-Erling Smørgrav <des@FreeBSD.org>
CommitDate: 2026-02-17 23:11:48 +0000

    ngctl: Check hook name length
    
    Check the length of the hook name when copying it into the sockaddr.
    
    MFC after:      1 week
    Reviewed by:    markj
    Differential Revision:  https://reviews.freebsd.org/D55258
    
    (cherry picked from commit 585190dff436eeea3be97300e36c82559028d3dd)
---
 usr.sbin/ngctl/write.c | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/usr.sbin/ngctl/write.c b/usr.sbin/ngctl/write.c
index 98bf213a2dad..b86533eca49c 100644
--- a/usr.sbin/ngctl/write.c
+++ b/usr.sbin/ngctl/write.c
@@ -34,10 +34,12 @@
 #include <sys/socket.h>
 
 #include <err.h>
+#include <stddef.h>
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>
 
+#include <netgraph/ng_message.h>
 #include <netgraph/ng_socket.h>
 
 #include "ngctl.h"
@@ -62,6 +64,7 @@ WriteCmd(int ac, char **av)
 	struct sockaddr_ng *sag = (struct sockaddr_ng *)sagbuf;
 	u_char buf[BUF_SIZE];
 	const char *hook;
+	size_t hooklen;
 	FILE *fp;
 	u_int len;
 	int byte;
@@ -71,6 +74,14 @@ WriteCmd(int ac, char **av)
 	if (ac < 3)
 		return (CMDRTN_USAGE);
 	hook = av[1];
+	_Static_assert(sizeof(sagbuf) >=
+	    offsetof(struct sockaddr_ng, sg_data) + NG_HOOKSIZ,
+	    "sagbuf is too small for NG_HOOKSIZ");
+	hooklen = strlcpy(sag->sg_data, hook, NG_HOOKSIZ);
+	if (hooklen >= NG_HOOKSIZ) {
+		warnx("hook name \"%s\" too long", hook);
+		return (CMDRTN_ERROR);
+	}
 
 	/* Get data */
 	if (strcmp(av[2], "-f") == 0) {
@@ -103,11 +114,10 @@ WriteCmd(int ac, char **av)
 	}
 
 	/* Send data */
-	sag->sg_len = 3 + strlen(hook);
+	sag->sg_len = 3 + hooklen;
 	sag->sg_family = AF_NETGRAPH;
-	strlcpy(sag->sg_data, hook, sizeof(sagbuf) - 2);
-	if (sendto(dsock, buf, len,
-	    0, (struct sockaddr *)sag, sag->sg_len) == -1) {
+	if (sendto(dsock, buf, len, 0, (struct sockaddr *)sag,
+	    sag->sg_len) < 0) {
 		warn("writing to hook \"%s\"", hook);
 		return (CMDRTN_ERROR);
 	}