Skip to content

Commit 7d0c800

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 7d0c800

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

subsys/net/ip/utils.c

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -168,11 +168,16 @@ 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+
/* POSIX used strlen but this is the size - includes nil */
178+
char instr[INET_ADDRSTRLEN];
179+
char in6str[INET6_ADDRSTRLEN];
180+
} tmp;
176181

177182
if (family == AF_INET6) {
178183
net_ipv6_addr_copy_raw(addr6.s6_addr, src);
@@ -204,14 +209,17 @@ char *z_impl_net_addr_ntop(sa_family_t family, const void *src,
204209
pos = -1;
205210
}
206211

212+
sptr = &tmp.in6str[0];
207213
} else if (family == AF_INET) {
208214
net_ipv4_addr_copy_raw(addr.s4_addr, src);
209215
len = 4;
210216
delim = '.';
217+
sptr = &tmp.instr[0];
211218
} else {
212219
return NULL;
213220
}
214221

222+
ptr = sptr;
215223
print_mapped:
216224
for (i = 0; i < len; i++) {
217225
/* IPv4 address a.b.c.d */
@@ -281,16 +289,18 @@ char *z_impl_net_addr_ntop(sa_family_t family, const void *src,
281289
needcolon = true;
282290
}
283291

284-
if (!(ptr - dst)) {
285-
return NULL;
286-
}
287-
288292
if (family == AF_INET) {
293+
/* delim was written as last character - overwrite with nil */
289294
*(ptr - 1) = '\0';
290295
} else {
291-
*ptr = '\0';
296+
/* nil terminate and increment to compute the size */
297+
*ptr++ = '\0';
292298
}
293299

300+
if ((size_t)(ptr - sptr) > size) {
301+
return NULL;
302+
}
303+
strcpy(dst, sptr);
294304
return dst;
295305
}
296306

0 commit comments

Comments
 (0)