Subject: kern/23625: malloc usage error can result in referencing undefined memory
To: None <gnats-bugs@gnats.netbsd.org>
From: None <gdt@ir.bbn.com>
List: netbsd-bugs
Date: 12/02/2003 12:43:03
>Number:         23625
>Category:       kern
>Synopsis:       malloc usage error can result in referencing undefined memory
>Confidential:   no
>Severity:       serious
>Priority:       medium
>Responsible:    kern-bug-people
>State:          open
>Class:          sw-bug
>Submitter-Id:   net
>Arrival-Date:   Tue Dec 02 17:44:00 UTC 2003
>Closed-Date:
>Last-Modified:
>Originator:     Greg Troxel
>Release:        NetBSD 1.6.1_STABLE
>Organization:
        Greg Troxel <gdt@ir.bbn.com>
>Environment:
	
	
System: NetBSD fnord.ir.bbn.com 1.6.1_STABLE NetBSD 1.6.1_STABLE (FNORD) #7: Mon Oct 6 15:46:22 EDT 2003 root@fnord.ir.bbn.com:/home/gdt/QUIST-current/netbsd/src/sys/arch/i386/compile/FNORD i386
Architecture: i386
Machine: i386
>Description:

In src/lib/libipsec/policy_parse.y, malloc is called with 0 (from
tlen), but then the resulting pointer is used as if it were of size
struct sadb_x_policy.

>How-To-Repeat:

Inspect code.  Note that there is an invariant that pbuf points to a
malloced area of memory of size tlen, or else pbuf is NULL and tlen is
zero.  Note that init_x_policy calls malloc with tlen, which will
generally be zero.

>Fix:

This may need defuzzing; I have other local changes as well resulting
in differing line numbers.

Basically the idea is to assign tlen to the desired length before
mallocing, and also be careful to zero tlen if the malloc fails, so
that the invariant is preserved.

Note that while the patch changes whitespace; this isn't entirely
gratuitous - the point is to group all the lines within which the
invariant might not be satisfied as a unit.  (Arguably the assignment
of pbuf to p doesn't belong in the group, though.)

Index: policy_parse.y
===================================================================
RCS file: /QUIST-CVS/netbsd/src/lib/libipsec/policy_parse.y,v
retrieving revision 1.1.1.5
retrieving revision 1.12
diff -u -u -r1.1.1.5 -r1.12
--- policy_parse.y	10 Oct 2003 13:04:20 -0000	1.1.1.5
+++ policy_parse.y	2 Dec 2003 17:27:58 -0000	1.12
@@ -295,14 +351,15 @@
 {
 	struct sadb_x_policy *p;
 
+	tlen = sizeof(struct sadb_x_policy);
 	pbuf = malloc(tlen);
 	if (pbuf == NULL) {
+		tlen = 0;	/* preserve tlen/pbuf invariant */
 		__ipsec_errcode = EIPSEC_NO_BUFS;
 		return -1;
 	}
-	tlen = sizeof(struct sadb_x_policy);
-
 	p = (struct sadb_x_policy *)pbuf;
+
 	p->sadb_x_policy_len = 0;	/* must update later */
 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
 	p->sadb_x_policy_type = p_type;
>Release-Note:
>Audit-Trail:
>Unformatted:
  >Synopsis:      libipsec malloc error results in referencing undefined memory