[PATCH] Multiple call ngx_parse_url cause index out of bounds bug

Maxim Dounin mdounin at mdounin.ru
Tue Dec 29 17:26:42 UTC 2020


On Sun, Dec 27, 2020 at 09:26:44PM +0800, Attenuation wrote:

> Hello, I found an array index out of bounds bug in ngx_inet_add_addr()
> function.
> In my case, I want to use ngx_parse_url(cf->pool, u) twice to update my
> address.
> Consider this situation, my twice function call argument u:  u->url.data is
> string
> of ip address,  and then, call trace is
> ngx_inet_add_addr (src/core/ngx_inet.c#L1274)
> ngx_parse_inet_url (src/core/ngx_inet.c#L968)
> ngx_parse_url (src/core/ngx_inet.c#L700)
> In first ngx_parse_url() call, u->url.data ip address will successfully add
> to u->addrs array,
> and u->naddrs will  be increased to 1. And then  the second
> call ngx_parse_url(),
> u->url.data ip address add to u->addrs array, Because of in first call
> n->naddrs was
> increased to 1, so this time our update ip address will add to
> u->addrs[1],  but u->addrs
> array were allocated 1 * sizeof(ngx_addr_t).
> src/core/ngx_inet.c#L1275  u->addrs = ngx_palloc(pool, total * nports *
> sizeof(ngx_addr_t));
> So the second time I call this function will cause memory error, and it may
> even make the program crashes.
> In order to avoid this bug, We need to check index of u->addrs.
> Could you help me check where there is a problem? Thanks!

The ngx_parse_url() function expects the ngx_url_t structure to be 
zeroed out, and with some input fields set, such as u.url and 
u.default_port.  Calling ngx_parse_url() with the ngx_url_t 
structure not reinitialized after previous parsing is a bug.

That is, you should reconsider your code: if you want to reuse the 
same ngx_url_t structure for multiple calls of ngx_parse_url(), 
you have to reinitialize it before each call.

Maxim Dounin

More information about the nginx-devel mailing list