Skip to content

Commit caf7d87

Browse files
committed
net: ip: account for the size in the inet_ntop code path
The code was writing to the dst without a verification check on size which is not appropriate. The guard on the arguements should be enforced and so a stack manipulation followed by a strcpy is slight less efficient but at the benefit of being memory safe from the args being passed in. Signed-off-by: Charles Hardin <[email protected]>
1 parent 6379d7c commit caf7d87

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

subsys/net/ip/utils.c

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -168,11 +168,15 @@ char *z_impl_net_addr_ntop(sa_family_t family, const void *src,
168168
int pos = -1;
169169
char delim = ':';
170170
uint8_t zeros[8] = { 0 };
171-
char *ptr = dst;
172171
int len = -1;
173172
uint16_t value;
174173
bool needcolon = false;
175174
bool mapped = false;
175+
char *sptr, *ptr;
176+
union {
177+
char instr[INET_ADDRSTRLEN];
178+
char in6str[INET6_ADDRSTRLEN];
179+
} tmp;
176180

177181
if (family == AF_INET6) {
178182
net_ipv6_addr_copy_raw(addr6.s6_addr, src);
@@ -204,14 +208,17 @@ char *z_impl_net_addr_ntop(sa_family_t family, const void *src,
204208
pos = -1;
205209
}
206210

211+
sptr = &tmp.in6str[0];
207212
} else if (family == AF_INET) {
208213
net_ipv4_addr_copy_raw(addr.s4_addr, src);
209214
len = 4;
210215
delim = '.';
216+
sptr = &tmp.instr[0];
211217
} else {
212218
return NULL;
213219
}
214220

221+
ptr = sptr;
215222
print_mapped:
216223
for (i = 0; i < len; i++) {
217224
/* IPv4 address a.b.c.d */
@@ -281,16 +288,18 @@ char *z_impl_net_addr_ntop(sa_family_t family, const void *src,
281288
needcolon = true;
282289
}
283290

284-
if (!(ptr - dst)) {
285-
return NULL;
286-
}
287-
288291
if (family == AF_INET) {
292+
/* delim was written as last character - overwrite with nil */
289293
*(ptr - 1) = '\0';
290294
} else {
291-
*ptr = '\0';
295+
/* nil terminate and increment to compute the size */
296+
*ptr++ = '\0';
292297
}
293298

299+
if ((size_t)(ptr - sptr) > size) {
300+
return NULL;
301+
}
302+
strcpy(dst, sptr);
294303
return dst;
295304
}
296305

0 commit comments

Comments
 (0)