Skip to contentSkip to conversation

last: Always terminate domain with '\0'

PATCH In review Tobias Stoeckmann 2 participants 2 messages Mar 12, 2017 – Mar 13, 2017 Util-Linux package

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 last: Always terminate domain with '\0'

Although in a practical sense, the stack will most likely be filled with zeros when the function is called, the C language requires an explicit '\0' termination which strncat() does not guarantee.

While at it, I replaced strncat with strncpy because that's what the program logic wants to do here.

---
 login-utils/last.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
login-utils/last.c +2 -2
index 340705757..ddbdd84a3 100644
@@ -507,8 +507,8 @@ static int list(const struct last_control *ctl, struct utmpx *p, time_t logout_t
 	if (r < 0) {
 		len = sizeof(p->ut_host);
 		if (len >= (int)sizeof(domain)) len = sizeof(domain) - 1;
-		domain[0] = 0;
-		strncat(domain, p->ut_host, len);
+		strncpy(domain, p->ut_host, len);
+		domain[len] = 0;
 	}
 
 
Signature · 1 line
2.12.0
maintainer
#1 lore raw
Quoted 8 lines · Tobias Stoeckmann
 login-utils/last.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
login-utils/last.c +0 -0
index 340705757..ddbdd84a3 100644

login-utils/last.c static int list(const struct last_control *ctl, struct utmpx *p, time_t logout_t · line 511

Quoted 7 lines
login-utils/last.c +2 -2
@@ -507,8 +507,8 @@ static int list(const struct last_control *ctl, struct utmpx *p, time_t logout_t
 	if (r < 0) {
 		len = sizeof(p->ut_host);
 		if (len >= (int)sizeof(domain)) len = sizeof(domain) - 1;
-		domain[0] = 0;
-		strncat(domain, p->ut_host, len);
+		strncpy(domain, p->ut_host, len);
+		domain[len] = 0;

I have applied a little bit different solution, we have xstrcpy() where is set \0 on len-1, so let's use it.

Karel

login-utils/last.c +6 -4
index 3407057..679ea6c 100644
@@ -505,10 +505,12 @@ static int list(const struct last_control *ctl, struct utmpx *p, time_t logout_t
        if (ctl->usedns || ctl->useip)
                r = dns_lookup(domain, sizeof(domain), ctl->useip, p->ut_addr_v6);
        if (r < 0) {
-               len = sizeof(p->ut_host);
-               if (len >= (int)sizeof(domain)) len = sizeof(domain) - 1;
-               domain[0] = 0;
-               strncat(domain, p->ut_host, len);
+               size_t sz = sizeof(p->ut_host);
+
+               if (sz > sizeof(domain))
+                       sz = sizeof(domain);
+
+               xstrncpy(domain, p->ut_host, sz);
        }