On Tue, Oct 16, 2018 at 9:49 PM Brandon Enochs <[email protected]> wrote:
> Here's the git format-patch:

See my version attached.


> +//config:config FEATURE_NTP_AUTH_MD5
> +//config:    bool "Make ntpd support MD5 authentication"
> +//config:    default n
> +//config:    depends on FEATURE_NTP_AUTH
> +//config:    help
> +//config:    Make ntpd support MD5 authentication"
> +//config:config FEATURE_NTP_AUTH_SHA1
> +//config:    bool "Make ntpd support SHA1 authentication"
> +//config:    default n
> +//config:    depends on FEATURE_NTP_AUTH
> +//config:    help
> +//config:    Make ntpd support SHA1 authentication"

If FEATURE_NTP_AUTH is selected, there is little benefit to have even more
granular choices (md5/sha1). Let's just support both.

>  //usage:     "\n    -p PEER    Obtain time from PEER (may be repeated)"
> +//usage:     "\n    -K    key number for preceding PEER (may be repeated)"
> +//usage:     "\n    -k    key file (see man 5 ntp.keys)"

The interplay between -p and -K is rather hard to code.

Since -p is busybox's invention anyway, there is no compatibility
to support, and we can, say, just include keys into -p ARG.
Then we don't need -K.

Brainstorming. How about -p [ALGO:KEYNO:]PEER ?

Also, code which parses of "server" lines in /etc/ntp.conf
probably needs to be extended to understand "key KEYNO" arg?

> +        key_file_parser = config_open(key_file_path);
> +        while ((token_count = config_read(key_file_parser, tokens, 4, 3, "# 
> \t", PARSE_NORMAL | PARSE_MIN_DIE)) == 3) {
> +            enum hash_type hash_type = HASH_NONE;
> +            size_t key_length;
> +            key_entry_t *key_entry = (key_entry_t *) 
> xzalloc(sizeof(key_entry_t));
> +
> +#if ENABLE_FEATURE_NTP_AUTH_MD5
> +            if (strcasecmp(tokens[1], "MD5") == 0) {

manpages and other documents seem to suggest "M" also should mean MD5?

> +            } else if ((key_length & 1) == 0 && key_length <= 64) {

manpage says "The key is a hex-encoded ASCII string of 40 characters,
which is truncated as necessary."
Why 64?
diff --git a/networking/ntpd.c b/networking/ntpd.c
index 1ebdc34c3..453345f99 100644
--- a/networking/ntpd.c
+++ b/networking/ntpd.c
@@ -62,6 +62,12 @@
 //config:	help
 //config:	Make ntpd look in /etc/ntp.conf for peers. Only "server address"
 //config:	is supported.
+//config:config FEATURE_NTP_AUTH
+//config:	bool "Make ntpd support authentication"
+//config:	default n
+//config:	depends on NTPD
+//config:	help
+//config:	Make ntpd support authentication"
 
 //applet:IF_NTPD(APPLET(ntpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
 
@@ -78,6 +84,10 @@
 //usage:     "\n	-w	Do not set time (only query peers), implies -n"
 //usage:     "\n	-S PROG	Run PROG after stepping time, stratum change, and every 11 mins"
 //usage:     "\n	-p PEER	Obtain time from PEER (may be repeated)"
+//usage:	IF_FEATURE_NTP_AUTH(
+//usage:     "\n	-K	key number for preceding PEER (may be repeated)"
+//usage:     "\n	-k	key file (ntp.keys compatible)"
+//usage:	)
 //usage:	IF_FEATURE_NTPD_CONF(
 //usage:     "\n		If -p is not given, 'server HOST' lines"
 //usage:     "\n		from /etc/ntp.conf are used"
@@ -228,14 +238,24 @@
 /* Parameter averaging constant */
 #define AVG             4
 
+#define MAX_KEY_NUMBER  65535
+#define KEYID_SIZE      sizeof(uint32_t)
 
 enum {
 	NTP_VERSION     = 4,
 	NTP_MAXSTRATUM  = 15,
 
+#if ENABLE_FEATURE_NTP_AUTH
+	NTP_MD5_DIGESTSIZE    = 16,
+	NTP_SHA1_DIGESTSIZE   = 20,
+	NTP_MSGSIZE_NOAUTH    = 48,
+	NTP_MSGSIZE_MD5_AUTH  = NTP_MSGSIZE_NOAUTH + NTP_MD5_DIGESTSIZE + KEYID_SIZE,
+	NTP_MSGSIZE_SHA1_AUTH = NTP_MSGSIZE_NOAUTH + NTP_SHA1_DIGESTSIZE + KEYID_SIZE,
+#else
 	NTP_DIGESTSIZE     = 16,
 	NTP_MSGSIZE_NOAUTH = 48,
-	NTP_MSGSIZE        = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
+	NTP_MSGSIZE        = (NTP_MSGSIZE_NOAUTH + KEYID_SIZE + NTP_DIGESTSIZE),
+#endif
 
 	/* Status Masks */
 	MODE_MASK       = (7 << 0),
@@ -288,7 +308,11 @@ typedef struct {
 	l_fixedpt_t m_rectime;
 	l_fixedpt_t m_xmttime;
 	uint32_t    m_keyid;
+#if ENABLE_FEATURE_NTP_AUTH
+	uint8_t     m_digest[NTP_SHA1_DIGESTSIZE];
+#else
 	uint8_t     m_digest[NTP_DIGESTSIZE];
+#endif
 } msg_t;
 
 typedef struct {
@@ -297,6 +321,20 @@ typedef struct {
 	double d_dispersion;
 } datapoint_t;
 
+#if ENABLE_FEATURE_NTP_AUTH
+enum {
+	HASH_MD5,
+	HASH_SHA1,
+};
+typedef struct {
+	unsigned id; //try uint16?
+	smalluint type;
+	smalluint msg_size;
+	smalluint key_length;
+	char key[0];
+} key_entry_t;
+#endif
+
 typedef struct {
 	len_and_sockaddr *p_lsa;
 	char             *p_dotted;
@@ -326,6 +364,9 @@ typedef struct {
 	/* last sent packet: */
 	msg_t            p_xmt_msg;
 	char             p_hostname[1];
+#if ENABLE_FEATURE_NTP_AUTH
+	key_entry_t      *key_entry;
+#endif
 } peer_t;
 
 
@@ -337,13 +378,25 @@ enum {
 	OPT_q = (1 << 1),
 	OPT_N = (1 << 2),
 	OPT_x = (1 << 3),
+#if ENABLE_FEATURE_NTP_AUTH
+	OPT_k = (1 << 4),
+	OPT_K = (1 << 5),
+#endif
 	/* Insert new options above this line. */
 	/* Non-compat options: */
+#if ENABLE_FEATURE_NTP_AUTH
+	OPT_w = (1 << 6),
+	OPT_p = (1 << 7),
+	OPT_S = (1 << 8),
+	OPT_l = (1 << 9) * ENABLE_FEATURE_NTPD_SERVER,
+	OPT_I = (1 << 10) * ENABLE_FEATURE_NTPD_SERVER,
+#else
 	OPT_w = (1 << 4),
 	OPT_p = (1 << 5),
 	OPT_S = (1 << 6),
 	OPT_l = (1 << 7) * ENABLE_FEATURE_NTPD_SERVER,
 	OPT_I = (1 << 8) * ENABLE_FEATURE_NTPD_SERVER,
+#endif
 	/* We hijack some bits for other purposes */
 	OPT_qq = (1 << 31),
 };
@@ -816,8 +869,12 @@ resolve_peer_hostname(peer_t *p)
 	return lsa;
 }
 
+#if !ENABLE_FEATURE_NTP_AUTH
+#define add_peers(s, key_entry) \
+	add_peers(s)
+#endif
 static void
-add_peers(const char *s)
+add_peers(const char *s, key_entry_t *key_entry)
 {
 	llist_t *item;
 	peer_t *p;
@@ -846,6 +903,9 @@ add_peers(const char *s)
 		}
 	}
 
+#if ENABLE_FEATURE_NTP_AUTH
+	p->key_entry = key_entry;
+#endif
 	llist_add_to(&G.ntp_peers, p);
 	G.peer_cnt++;
 }
@@ -870,6 +930,49 @@ do_sendto(int fd,
 	return 0;
 }
 
+#if ENABLE_FEATURE_NTP_AUTH
+static void
+hash(key_entry_t *key_entry, const msg_t *msg, uint8_t *output)
+{
+	union {
+		md5_ctx_t m;
+		sha1_ctx_t s;
+	} ctx;
+	unsigned hash_size = sizeof(*msg) - sizeof(msg->m_keyid) - sizeof(msg->m_digest);
+
+	switch (key_entry->type) {
+	case HASH_MD5:
+		md5_begin(&ctx.m);
+		md5_hash(&ctx.m, key_entry->key, key_entry->key_length);
+		md5_hash(&ctx.m, msg, hash_size);
+		md5_end(&ctx.m, output);
+		break;
+	default: /* it's HASH_SHA1 */
+		sha1_begin(&ctx.s);
+		sha1_hash(&ctx.s, key_entry->key, key_entry->key_length);
+		sha1_hash(&ctx.s, msg, hash_size);
+		sha1_end(&ctx.s, output);
+		break;
+	}
+}
+
+static void
+hash_peer(peer_t *p)
+{
+	p->p_xmt_msg.m_keyid = htonl(p->key_entry->id);
+	hash(p->key_entry, &p->p_xmt_msg, p->p_xmt_msg.m_digest);
+}
+
+static int
+hashes_differ(peer_t *p, const msg_t *msg)
+{
+	uint8_t digest[NTP_SHA1_DIGESTSIZE];
+
+	hash(p->key_entry, msg, digest);
+	return memcmp(digest, msg->m_digest, p->key_entry->msg_size - NTP_MSGSIZE_NOAUTH - KEYID_SIZE);
+}
+#endif
+
 static void
 send_query_to_peer(peer_t *p)
 {
@@ -946,9 +1049,18 @@ send_query_to_peer(peer_t *p)
 	 */
 	p->reachable_bits <<= 1;
 
+#if ENABLE_FEATURE_NTP_AUTH
+	if (p->key_entry)
+		hash_peer(p);
 	if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
-			&p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
-	) {
+		&p->p_xmt_msg, !p->key_entry ? NTP_MSGSIZE_NOAUTH : p->key_entry->msg_size) == -1
+	)
+#else
+	if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
+		&p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
+	)
+#endif
+	{
 		close(p->p_fd);
 		p->p_fd = -1;
 		/*
@@ -1924,10 +2036,21 @@ recv_and_process_peer_pkt(peer_t *p)
 		bb_perror_msg_and_die("recv(%s) error", p->p_dotted);
 	}
 
+#if ENABLE_FEATURE_NTP_AUTH
+	if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH) {
+		bb_error_msg("malformed packet received from %s", p->p_dotted);
+		return;
+	}
+	if (p->key_entry && hashes_differ(p, &msg)) {
+		bb_error_msg("invalid cryptographic hash received from %s", p->p_dotted);
+		return;
+	}
+#else
 	if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
 		bb_error_msg("malformed packet received from %s", p->p_dotted);
 		return;
 	}
+#endif
 
 	if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
 	 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
@@ -2135,7 +2258,12 @@ recv_and_process_client_pkt(void /*int fd*/)
 	from = xzalloc(to->len);
 
 	size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
-	if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
+#if ENABLE_FEATURE_NTP_AUTH
+	if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_SHA1_AUTH && size != NTP_MSGSIZE_MD5_AUTH)
+#else
+	if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE)
+#endif
+	{
 		char *addr;
 		if (size < 0) {
 			if (errno == EAGAIN)
@@ -2278,6 +2406,19 @@ recv_and_process_client_pkt(void /*int fd*/)
  *      with the -g and -q options. See the tinker command for other options.
  *      Note: The kernel time discipline is disabled with this option.
  */
+#if ENABLE_FEATURE_NTP_AUTH
+static key_entry_t *
+find_key_entry(llist_t *key_entries, unsigned id)
+{
+	while (key_entries) {
+		key_entry_t *cur = (key_entry_t*) key_entries->data;
+		if (cur->id == id)
+			return cur;
+		key_entries = key_entries->link;
+	}
+	return NULL;
+}
+#endif
 
 /* By doing init in a separate function we decrease stack usage
  * in main loop.
@@ -2286,6 +2427,11 @@ static NOINLINE void ntp_init(char **argv)
 {
 	unsigned opts;
 	llist_t *peers;
+#if ENABLE_FEATURE_NTP_AUTH
+	llist_t *key_ids;
+	llist_t *key_entries = NULL;
+	char *key_file_path = NULL;
+#endif
 
 	srand(getpid());
 
@@ -2304,6 +2450,7 @@ static NOINLINE void ntp_init(char **argv)
 	peers = NULL;
 	opts = getopt32(argv, "^"
 			"nqNx" /* compat */
+			IF_FEATURE_NTP_AUTH("K:*k:")
 			"wp:*S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
 			IF_FEATURE_NTPD_SERVER("I:") /* compat */
 			"d" /* compat */
@@ -2311,6 +2458,10 @@ static NOINLINE void ntp_init(char **argv)
 				"\0"
 				"dd:wn"  /* -d: counter; -p: list; -w implies -n */
 				IF_FEATURE_NTPD_SERVER(":Il") /* -I implies -l */
+				IF_FEATURE_NTP_AUTH(":K?k") /* -k is required if -K appears */
+#if ENABLE_FEATURE_NTP_AUTH
+			, &key_ids, &key_file_path
+#endif
 			, &peers, &G.script_name,
 #if ENABLE_FEATURE_NTPD_SERVER
 			&G.if_name,
@@ -2341,9 +2492,84 @@ static NOINLINE void ntp_init(char **argv)
 		logmode = LOGMODE_NONE;
 	}
 
+#if ENABLE_FEATURE_NTP_AUTH
+	if (opts & OPT_k) {
+		char *tokens[4];
+		parser_t *parser;
+
+		parser = config_open(key_file_path);
+		while (config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL | PARSE_MIN_DIE) == 3) {
+			key_entry_t *key_entry;
+			char buffer[64];
+			smalluint hash_type;
+			smalluint msg_size;
+			smalluint key_length;
+			char *key;
+
+			if ((tokens[1][0] | 0x20) == 'm')
+				/* supports 'M' and 'md5' formats */
+				hash_type = HASH_MD5;
+			else
+			if (strncasecmp(tokens[1], "sha", 3) == 0)
+				/* supports 'sha' and 'sha1' formats */
+				hash_type = HASH_SHA1;
+			else
+				bb_error_msg_and_die("only MD5 and SHA1 keys supported");
+
+/* man ntp.keys:
+ *  MD5    The key is 1 to 16 printable characters terminated by an EOL,
+ *         whitespace, or a # (which is the "start of comment" character).
+ *  SHA
+ *  SHA1
+ *  RMD160 The key is a hex-encoded ASCII string of 40 characters, which
+ *         is truncated as necessary.
+ */
+			key_length = strnlen(tokens[2], 41);
+			if (key_length >= 41) {
+ err:
+				bb_error_msg_and_die("malformed key at line %u", parser->lineno);
+			}
+
+			if (hash_type == HASH_MD5) {
+				key = tokens[2];
+				msg_size = NTP_MSGSIZE_MD5_AUTH;
+			} else /* it's hash_type == HASH_SHA1 */
+			if (!(key_length & 1)) {
+				key_length >>= 1;
+				if (!hex2bin(buffer, tokens[2], key_length))
+					goto err;
+				key = buffer;
+				msg_size = NTP_MSGSIZE_SHA1_AUTH;
+			} else {
+				goto err;
+			}
+			key_entry = xzalloc(sizeof(*key_entry) + key_length);
+			key_entry->type = hash_type;
+			key_entry->msg_size = msg_size;
+			key_entry->key_length = key_length;
+			memcpy(key_entry->key, key, key_length);
+			key_entry->id = xatou_range(tokens[0], 1, MAX_KEY_NUMBER);
+			llist_add_to(&key_entries, key_entry);
+		}
+		config_close(parser);
+	}
+#endif
 	if (peers) {
+#if ENABLE_FEATURE_NTP_AUTH
+		while (peers) {
+			key_entry_t *key_entry = NULL;
+
+			if (key_ids) {
+				int key_id = xatou_range(llist_pop(&key_ids), 1, MAX_KEY_NUMBER);
+				key_entry = find_key_entry(key_entries, key_id);
+//error if not found?
+			}
+			add_peers(llist_pop(&peers), key_entry);
+		}
+#else
 		while (peers)
 			add_peers(llist_pop(&peers));
+#endif
 	}
 #if ENABLE_FEATURE_NTPD_CONF
 	else {
@@ -2353,7 +2579,7 @@ static NOINLINE void ntp_init(char **argv)
 		parser = config_open("/etc/ntp.conf");
 		while (config_read(parser, token, 3, 1, "# \t", PARSE_NORMAL)) {
 			if (strcmp(token[0], "server") == 0 && token[1]) {
-				add_peers(token[1]);
+				add_peers(token[1], NULL);
 				continue;
 			}
 			bb_error_msg("skipping %s:%u: unimplemented command '%s'",
@@ -2394,6 +2620,7 @@ static NOINLINE void ntp_init(char **argv)
 		| (1 << SIGCHLD)
 		, SIG_IGN
 	);
+//TODO: free unused elements of key_entries?
 }
 
 int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
_______________________________________________
busybox mailing list
[email protected]
http://lists.busybox.net/mailman/listinfo/busybox

Reply via email to