From 9eef9e78c151640db9a6849adb431554f8259249 Mon Sep 17 00:00:00 2001
From: Cy Schubert <cy@FreeBSD.org>
Date: Thu, 12 Dec 2024 12:03:09 -0800
Subject: [PATCH] ntpd: Correctly setuid to the ntpd user

Using the rc plumbing to setuid(2) to the ntpd user using su(1) results
in ntpd not being able to sync with NTP servers on IPv6-only hosts. To
solve this we instead use the ntpd -u option to setuid() to the ntpd
user.

PR:			283116
MFC after:		1 week
Differential Revision:	<https://reviews.freebsd.org/D###>
---
 libexec/rc/rc.d/ntpd | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/libexec/rc/rc.d/ntpd b/libexec/rc/rc.d/ntpd
index e7e42da8acc7..4a5b104845bd 100755
--- a/libexec/rc/rc.d/ntpd
+++ b/libexec/rc/rc.d/ntpd
@@ -23,6 +23,7 @@ _ntp_tmp_leapfile="/var/run/ntpd.leap-seconds.list"
 _ntp_default_dir="/var/db/ntp"
 _ntp_default_driftfile="${_ntp_default_dir}/ntpd.drift"
 _ntp_old_driftfile="/var/db/ntpd.drift"
+_ntpd_user_arg="-u ntpd:ntpd"
 
 pidfile="${_ntp_default_dir}/${name}.pid"
 
@@ -101,9 +102,12 @@ ntpd_precmd()
 	# by the admin, we don't add the option.  If the file exists in the old
 	# default location we use that, else we use the new default location.
 	if can_run_nonroot; then
-		_user="ntpd"
 		driftopt="-f ${_ntp_default_driftfile}"
-	elif grep -q "^[ \t]*driftfile" "${ntpd_config}" ||
+	elif [ -n "${ntpd_user}" ]; then
+		_ntpd_user_arg="-u ${ntpd_user}"
+		unset ntpd_user
+	fi
+	if grep -q "^[ \t]*driftfile" "${ntpd_config}" ||
 	     [ -n "${rc_flags}" ] &&
 	     ( [ -z "${rc_flags##*-f*}" ] ||
 	       [ -z "${rc_flags##*--driftfile*}" ] ); then
@@ -115,7 +119,7 @@ ntpd_precmd()
 	fi
 
 	# Set command_args based on the various config vars.
-	command_args="-p ${pidfile} -c ${ntpd_config} ${driftopt}"
+	command_args="-p ${pidfile} -c ${ntpd_config} ${driftopt} ${_ntpd_user_arg}"
 	if checkyesno ntpd_sync_on_start; then
 		command_args="${command_args} -g"
 	fi
-- 
2.47.1