Repository navigation
ngx_mruby v2.7.2
ngx_mruby 2.7.2 is a maintenance release of the 2.x line. It changes some
behavior that an existing configuration, Ruby script or build can observe;
read "Behavior changes: read before upgrading" in the notes before you
upgrade. No directive was added, renamed or removed: rebuild the module the
way you built 2.7.1 and replace the binary or the dynamic module.
Security
This release fixes three issues reachable through an operator's own
configuration by the clients whose input or requests reach it. Each has its
own advisory:
- High —
Nginx::Upstream#server=andNginx::Stream::Connection#upstream_server=
pointed the shared, worker-lifetime upstream peer at memory freed when the
setting request or connection ended, so a later request or connection that
used the same upstream read freed memory (use-after-free, CWE-416): a crash,
a misdirected upstream connection, or disclosure of freed memory in a log.
(GHSA-22jc-w698-vfqw) - Medium — A value that contains a NUL byte, stored into an nginx variable
withNginx::Var, was copied only up to the NUL while the variable kept the
full length, so reading the variable back returned uninitialized worker
memory, which a configuration could then send to the client (CWE-200,
CWE-908). (GHSA-gxqc-3p4h-5p36) - Medium — A HEAD request to an mruby content handler that writes output
received a response body, which desynchronizes response framing on a
kept-alive connection and, behind a connection-reusing proxy, can pair a
response with the wrong request (CWE-444). (GHSA-8mxf-gvvp-38fq)
All three are fixed in 2.7.2. See entries 6, 7 and 8 of the notes for what
each changes and what to do (nothing, for a configuration that upgrades).
Behavior changes: read before upgrading
1. Nginx::Var raises for a method name that names no variable and for a setter without its value (#589)
- Before:
Nginx::Vartreats a call of a method that it does not define as
access to the nginx variable of that name (v.http_hostreads
$http_host), and a method name that ends with=as a setter of the
variable named before the=(v.http_host = "a"). Code that builds the
name at run time passes it tosend. For three kinds of names the accessor
read memory outside the name or outside the arguments, so the result
depended on that memory:- an empty name (
v.send("")) read the byte before the name, and usually
returnednil; - a name made only of
=(v.send("=", "x")) read past the end of the
name, and returnednilor ended the worker process; - a setter called without its value (
v.send("http_host=")) read a value
from outside its arguments. It could end the worker process, or set the
variable to a value that the code did not pass.
- an empty name (
- Now: an empty name and a name made only of
=raiseNoMethodError
(undefined method '' for Nginx::Var,undefined method '=' for Nginx::Var). A setter called without its value raisesArgumentError
(wrong number of arguments (given 0, expected 1) for Nginx::Var#http_host=) and leaves the variable as it was. The accessor
checks the name and the arguments before it reads them. - Why it changed:
- The defect: the accessor read the byte before an empty name, ran
strtok
past the end of its copy of a name made only of=, and read the first
element of an empty argument list for a setter without its value, as
"Before" says (#589). - Why the old behavior could not be kept: the results of these calls came
from memory outside the name and the arguments, so the same call could
returnnilonce and end the worker process another time. Such a name
names no variable, and a setter has no value to set without its
argument, so there is no result to keep. The calls raise what Ruby raises
for a method that the receiver does not have (NoMethodError) and for a
call with fewer arguments than the method takes (ArgumentError). - What the documentation promised: the 2.7.1 documentation says that the
accessor is called forNginx::Var#VARNAMEandNginx::Var#VARNAME=and
sets "the 2nd arg" to the variable when the name ends with=
(Nginx::Var#method_missing of 2.7.1).
It says nothing about a name without a variable name in it, or about a
setter without its value.
- The defect: the accessor read the byte before an empty name, ran
- Affected: code that calls
Nginx::Varwith a name that it builds at run
time (send,public_send,method_missing) when the name can be empty
or made only of=, and code that calls a setter without a value. - What to do: check the name before the call, or rescue
NoMethodError
where the name can be empty. Pass a value to each setter. - Not changed by this release: the accessor reads and sets the same
variables as before, also for names with uppercase letters, which name the
variable in lowercase. A setter called with more than one value still uses
the first one, and a name like=foo=still sets$foo. - Tests: port 18153 (
test/t/cases/var_input.rb).
2. Nginx::Var#set leaves the String or Symbol of the name unchanged (#589)
- Before:
Nginx::Var#set(name, value)looked the variable up by the
lowercased name, and lowercased the bytes ofnamein place to get it.
After the call, the String passed asnamewas in lowercase, also when it
was frozen, and so was a String that shared its bytes, such as a copy that
dupmade of a long String. For a Symbol with a long name,set
lowercased the name that the worker keeps for the Symbol, soto_sof that
Symbol returned the name in lowercase in every later request of the
worker. Long means more than 27 bytes on a 64-bit build: mruby keeps a
shorter String inside the String object, and a copy does not share it. - Now:
setlooks the variable up by a lowercased copy of the name. The
String or Symbol passed asnamestays as it was.setsets the same
variable and returns the same value as before. - Why it changed:
- The defect:
setwrote into the String passed asname, and through it
into frozen Strings, into the Strings that shared its bytes and into the
names of Symbols, as "Before" says (#589). - Why the old behavior could not be kept: a frozen String must not change,
a String that shares its bytes is another object of the code, and the
name of a Symbol belongs to every request of the worker. The lookup needs
the name in lowercase, so it takes a copy. - What the documentation promised: the 2.7.1 documentation says that
set
sets the value to the nginx variable
(Nginx::Var#set of 2.7.1).
It does not say thatsetchanges its arguments.
- The defect:
- Affected: code that uses the String or Symbol that it passed to
set
after the call, and expects it in lowercase. - What to do: nothing, unless the code relied on
setlowercasing the name.
Such code callsdowncaseon the name itself. - Tests: port 18153 (
test/t/cases/var_input.rb).
3. Redis is in the default build again, and mruby-redis builds hiredis v1.5.0 on every platform without stopping on hiredis warnings (#604, matsumotory/mruby-redis#108)
- Before: the default
build_config.rbof 2.7.1 leaves
matsumotory/mruby-redisout (entry 1 of the
2.7.1 notes), so
a binary built with it has noRedisclass, and code that refers to
RedisraisesNameError(uninitialized constant Redis). A build that
enables the gem, by uncommenting
conf.gem github: 'matsumotory/mruby-redis'or with its own
build_config.rb, gets hiredis from the build script of the gem. When the
build directory of the gem had nohiredisdirectory yet, the script
cloned hiredis from the head of its default branch, and on macOS checked
out v0.13.3. The script compiled hiredis with the C flags of the mruby
build, and the Makefile of hiredis 1.2.0 and later adds-Werror, so a
new warning in hiredis stopped the build. With hiredis 1.4.0 and later and
the gcc toolchain of mruby, the build stopped at
ffc.h:330:5: error: "FFC_DEBUG" is not defined, evaluates to 0 [-Werror=undef]. - Now: the default
build_config.rbincludesmatsumotory/mruby-redis
again (#604), as
the defaultbuild_config.rbof 2.7.0 and earlier did. A binary built
with it has theRedisclass, and its build clones the gem and hiredis
from GitHub. The build script of the gem clones the hiredis tagv1.5.0into
hiredis-v1.5.0on every platform, macOS included. It stops, with a
message that names both commits, when the clone is not at commit
5bb7f030f6631b243438cf0fdd3be84352b905bb, the commit of that tag. It
builds hiredis withUSE_WERROR=0, so the build prints the warnings of
hiredis and goes on. It builds hiredis withmake installonly, so
hiredis-testis no longer built, and musl systems such as Alpine no
longer needlinux-headers. Ahiredisdirectory left by an earlier
build is not reused. The change of hiredis is in the gem: ngx_mruby 2.x commits no
gem lock, so the build clones the gem at the head of itsmasterbranch.
Every build that clones the gem after the merge of
matsumotory/mruby-redis#108
gets the change, a build of 2.7.1 included. mruby does not update a gem
that it cloned before, and it checks a gem out at the commit that
build_config.rb.lockrecords, a file that mruby writes at the end of
each build and that git ignores on 2.x: a source tree that built
mruby-redis before the merge keeps that commit of the gem, and its
hiredis, until both its mruby build directorymruby/buildand
build_config.rb.lockare removed. - Why it changed:
- The defect: the unpinned clone let every new hiredis commit reach every
new build that enables the gem, and hiredis 1.4.0 stopped such builds
with theFFC_DEBUGerror above
(#528,
matsumotory/mruby-redis#108).
2.7.1 left the gem out of the default build because of this defect
(entry 1 of the 2.7.1 notes). - Why the old behavior could not be kept: a build that follows the default
branch of hiredis can break with any hiredis commit, which is why 2.7.1
left the gem out of the default build. A pinned release with a checked
commit gives every build the same hiredis.-Werrorhad to go as well:
with ngx_mruby's sanitizer flags
(-fsanitize=address,undefined -fno-omit-frame-pointer), gcc 13 to 15
stop the build of hiredis v1.5.0 atsds.c:525with
null format string [-Werror=format-truncation=], so a newer compiler
would break the pinned build too.USE_WERROR=0is the switch that
hiredis 1.3.0 and later provide for builds that do not want-Werror
(redis/hiredis#1210).
v1.5.0 builds and passes the tests of the gem on Linux and macOS, so
macOS no longer needs v0.13.3. With hiredis pinned, the reason for
leaving the gem out of the default build no longer holds: entry 1 of
the 2.7.1 notes kept the gem out of the default list "until
mruby-redis pins hiredis". Leaving it out longer would keepRedis
from the scripts that used it with the default build of 2.7.0 and
earlier, the examples in the README and indocs/use_caseand the
client of the bundledauto-sslmrbgem among them. - What the documentation promised: entry 1 of the 2.7.1 notes says that
the build of the gem "can fail while hiredis has the problem that #528
describes". The 2.7.1 documentation says to uncomment the line of the
gem inbuild_config.rb
(built-in mrbgems of 2.7.1).
It says that the build of the gem "clones the hiredis library from an
unpinned branch, which broke the build of ngx_mruby"
(docs/install of 2.7.1),
and does not name a version of hiredis. It also says that theRedis
class "is not in the default build since 2.7.1". The 2.7.0
documentation listed mruby-redis among "the default mrbgems"
(docs/install of 2.7.0)
andRedisamong the classes that can be used "with default build
configuration"
(built-in mrbgems of 2.7.0).
- The defect: the unpinned clone let every new hiredis commit reach every
- Affected: the default builds of 2.7.2. Their binaries have the
Redis
class again, so code that refers toRedisno longer raises
NameError. Their build clones three more repositories from GitHub:
matsumotory/mruby-redis, and matsumotory/mruby-pointer, which
mruby-redis depends on and which adds no class, at the heads of their
masterbranches, and the hiredis tagv1.5.0. It links hiredis
statically into nginx or into
the dynamic module, which grows by about 190 KB: a stripped static
nginx built with the release options of the performance comparison of
next(test/build_release.shthere), on Linux aarch64 with gcc 11.4,
grows from 3.88 MB to 4.08 MB. Only a script that calls
Redisneeds a Redis server. The change of hiredis affects the default
builds of 2.7.2, builds of 2.7.1 that enable mruby-redis, and the
default builds of 2.7.0 and earlier, whose defaultbuild_config.rb
includes the gem. When they clone the gem after the merge, they get
hiredis v1.5.0 instead of the head of the default branch of hiredis, and
on macOS instead of v0.13.3. mruby-redis#108 tested the gem with mruby
3.3.0, which 2.6.0 to 2.7.2 bundle, and with mruby 4.0.0; 2.5.0 and
earlier bundle older mruby releases. The gem links hiredis statically, so a binary built before
keeps its hiredis until it is built again aftermruby/buildand
build_config.rb.lockare removed. A build of 2.7.1 with the defaultbuild_config.rbis not
affected, because it does not include the gem. - What to do: nothing for the default build of 2.7.2, unless this source
tree built mruby-redis before, in a build that enabled it or in the
default build of 2.7.0 or earlier: then removemruby/buildand
build_config.rb.lockfirst. Removingmruby/buildalone is not
enough: the next build clones the gem again, but checks it out at the
commit that the lock recorded, with the unpinned hiredis clone.
Then build as before: the warning of entry 1 of the 2.7.1 notes ("The
build of that gem can fail ...") no longer applies. To build without the
gem, as the default build of 2.7.1 did, comment out
conf.gem github: 'matsumotory/mruby-redis'inbuild_config.rb. To
build with another hiredis release, set the environment variable
MRUBY_REDIS_HIREDIS_VERSIONto its tag when you build, or set
ENV['MRUBY_REDIS_HIREDIS_VERSION']inbuild_config.rb(see the
README of mruby-redis).
The build does not check the commit of another tag. mruby-redis#108 also
built and testedv1.4.1, on its earlier head 2cc63c1 with gcc and mruby
3.3.0. - Not changed by this release: as in 2.7.0 and in builds of 2.7.1 that
enable the gem, each call ofRediswaits in the worker until the Redis
server answers, because the gem uses the blocking API of hiredis, so the
worker serves no other request meanwhile.Redis#ttl, whose declaration
mruby-redis#108 changed for mruby 4.0.0, behaves as before with the
bundled mruby 3.3.0. - Tests: the test suite of ngx_mruby has no test that calls Redis, and it
starts no Redis server. Its default build builds the gem since #604,
so every CI cell builds the gem and links hiredis, the cell with the
sanitizers included, and the test nginx has theRedisclass. #604
quotes the suite onmasterwith the static and the dynamic module and
with the sanitizers, the symbols of the gem and of hiredis in the nginx
binary, and a request that calls Redis without and with a running Redis
server. mruby-redis#108 quotes the suite of
ngx_mrubymaster(03aad70) andnext(75bfa6f), each built with the
gem enabled at the head of that pull request, and both pass. The CI of
the gem runs its tests on Ubuntu 22.04 and on Ubuntu 24.04, the latter
with the sanitizer settings of ngx_mruby's CI.
4. Redis.connect_set_udptr and Redis.new without arguments keep the connection in the mrb_state, not in mrb->ud, and Redis.new with one argument raises ArgumentError (matsumotory/mruby-redis#109)
- Before: in a build that includes mruby-redis,
Redis.connect_set_udptr host, port[, timeout](also named
Redis.connect_set_raw) connected to the server and stored the
connection through matsumotory/mruby-pointer, which keeps its own struct
inmrb->ud, the user-data pointer of themrb_state.Redis.new
without arguments read the connection from there. ngx_mruby keeps its
own data inmrb->ud: the stream module its context, in all the code of
astream {}block, and the HTTP module its server configuration while
mruby_server_context_handler_code,mruby_ssl_handshake_handlerand
mruby_ssl_handshake_handler_coderun. In that code the two methods
wrote the connection into ngx_mruby's data and read it from there. In
the other code of anhttp {}block,mrb->udis NULL:
Redis.connect_set_udptrraisedRuntimeError("can not set, mrb ud
pointer was not initialized") after it had connected, and left that
connection open, andRedis.newwithout arguments raisedRuntimeError
("can not get. mrb ud pointer was not initialized"). Where a connection
was stored, everyRedis.newwithout arguments returned an object with
that same connection, and each of these objects closed it when it was
collected.Redis.newwith one argument used a value that the call had
not set: for a new object, a NULL pointer, which ended the worker. - Now: the gem keeps the connection in the
mrb_state, in an instance
variable of theRedisclass that Ruby code cannot reach, and no
longer reads or writesmrb->ud. The two methods work the same way in
all the code of anhttp {}or astream {}block.
Redis.connect_set_udptrkeeps the connection. When it connects, it
closes a connection that it kept before and that noRedis.newhas
taken. A failedRedis.connect_set_udptrraises
Redis::ConnectionError, as before; it now also closes the connection
that failed, and a connection kept before stays kept.Redis.new
without arguments takes the kept connection, so that one object owns
it: a secondRedis.newwithout arguments raises an error until
Redis.connect_set_udptris called again, and so does a call when no
connection is kept. The error isRedis::ConnectionError, a subclass
ofRuntimeError, with the message "no connection kept: call
Redis.connect_set_udptr first".Redis.newwith one argument raises
ArgumentErrorwith the message "wrong number of arguments (given 1,
expected 0, 2 or 3)". The change is in the gem: ngx_mruby 2.x commits no gem
lock, so every build that clones the gem after the merge of
matsumotory/mruby-redis#109
gets it, a build of 2.7.1 included. A source tree that built the gem
before keeps its checkout of the gem untilmruby/buildand
build_config.rb.lockare removed (see entry 3). - Why it changed:
- The defect: mruby leaves
mrb->udto the application that embeds it,
and ngx_mruby uses it. The two methods used ngx_mruby's data as the
struct of mruby-pointer in the code named above, and raised in the
rest of anhttp {}block.Redis.newwith one argument used a value
that the call had not set
(matsumotory/mruby-redis#109). - Why the old behavior could not be kept:
mrb->udhas no place for
the data of a gem. While the gem kept its connection there, the two
methods either raised, where ngx_mruby leavesmrb->udNULL, or used
ngx_mruby's data, where it does not. Handing one connection to several
objects made each of them close it, so the connection was closed more
than once; with one owner, it is closed once. A call with one
argument has no host and port to connect to, and its old result came
from a pointer that the call had not set, so there is no result to
keep. It raises what Ruby raises for a wrong number of arguments
(ArgumentError). - What the documentation promised: before this change, neither the
README of mruby-redis nor the documentation of ngx_mruby described the
two methods. The README of
mruby-pointer
shows them in a C program that callsmrb_udptr_initand
mrb_udptr_copyto share a connection between twomrb_states;
ngx_mruby calls neither.
- The defect: mruby leaves
- Affected: scripts that call
Redis.connect_set_udptr,
Redis.connect_set_raw, orRedis.newwithout arguments or with one
argument, in the default build of 2.7.2, which includes mruby-redis
again (entry 3), and in every other build that includes the gem: builds
of 2.7.1 that enable it, and the default builds of 2.7.0 and earlier.
Scripts that create everyRedisobject with
Redis.new host, port[, timeout]are not affected. - What to do: call
Redis.connect_set_udptragain before each further
Redis.newwithout arguments, or keep the object thatRedis.new
returned and use it again, or callRedis.new host, portinstead.
Redis::ConnectionErroris a subclass ofRuntimeError, so code that
rescuesRuntimeErroraroundRedis.newwithout arguments still
catches the new error. Change only code that compares the class of the
error withRuntimeErrorexactly, or its message. Call
Redis.connect_set_udptrin code that runs in the worker
(mruby_init_worker_code,mruby_stream_init_worker_codeor a
handler): a connection kept bymruby_init_code,
mruby_server_context_handler_code,mruby_stream_init_codeor
mruby_stream_server_context_codeis copied into every worker. If this
source tree built mruby-redis before, removemruby/buildand
build_config.rb.lockfirst. - Not changed by this release:
Redis.new host, port[, timeout]and the
other methods ofRedisbehave as before. The build of mruby-redis
still clones matsumotory/mruby-pointer, which the gem no longer calls. - Tests: the test suite of ngx_mruby has no test that uses Redis.
mruby-redis#109 adds tests ofRedis.connect_set_udptr,
Redis.connect_set_raw,Redis.newwithout arguments andRedis.new
with one argument to the gem, among them tests withmrb->udset the
way a host application sets it. It quotes the suite of ngx_mruby
masterandnext, each built with the gem enabled at the head of
that pull request, and both pass.
5. A content handler that writes output and then sets a status below 300 answers with that status (#594)
- Before: an
mruby_content_handler*on the main request that wrote output
withNginx.rputsorNginx.echoand then calledNginx.return,
Nginx.send_headerorNginx.status_code=with a status below 300 other
than 200, 201 and 204, for exampleNginx::HTTP_ACCEPTED, or with 0, sent
no response. nginx closed an HTTP/1.0 connection without sending a byte
and kept an HTTP/1.1 keep-alive connection open without a response until
keepalive_timeout(75 s by default), so the client waited for its own
timeout. 2.7.1 lists this under "Known limitations". - Now: the request gets the output with the status that the handler set,
withContent-Lengthof the output, like nginx's ownreturn 202 "text";
without itsContent-Type(ngx_mruby sends none, as for 200 after
output). This holds also when the handler ends so after
Nginx::Async::HTTP.sub_requestresumed it.Nginx.rputs "queued"followed by
Nginx.return Nginx::HTTP_ACCEPTEDanswers202 Acceptedwith the body
queued. A status below 200 goes out the same way, as the number without
a reason phrase (HTTP/1.1 100), as nginx sends it for its own
return 100 "text";, although HTTP does not allow a final response with
such a status.Nginx.return 0sets no status, and the output gets 200,
as output without a status does. A keep-alive connection stays open for
the next request, as after a 200 with output. - Why it changed:
- The defect:
Nginx.returnafter the output marked the end of the
output, and ngx_mruby then handed the status to nginx without sending
the output. nginx sends a response of its own for 201, 204 and the
statuses from 300 up, but for any other status below 300 it ends the
request without sending anything, so the request had no response.
#566 fixed this for
handlers without output and left this case open, as its
review records; this release fixes it
(#594). - Why the old behavior could not be kept: keeping it would leave these
requests without a response. A content handler that writes output and
then sets 200 already answers with its output; the fix answers the other
statuses that nginx does not answer by itself in the same way, with the
status the handler set. No request that got a response in 2.7.1 gets a
different one. - What the documentation promised: the 2.7.1 documentation says that
Nginx.rputs"Puts response text" and thatNginx.return"Returns nginx
status code to send back HTTP status to the client"
(Nginx.return of 2.7.1),
and the 2.7.1 release notes list this case under "Known limitations"
(v2.7.1.md). The documentation of the
methods did not say what a content handler answers after output with
such a status.
- The defect:
- Affected:
mruby_content_handler*handlers that write output and then set
a status below 300 other than 200, 201 and 204, or 0. - What to do: nothing for a handler that means to answer its output with
that status. A handler that should answer 200 setsNginx::HTTP_OK. - Not changed by this release: after output,
Nginx::HTTP_OKanswers 200
with the output, andNginx::HTTP_CREATED,Nginx::HTTP_NO_CONTENTand the
statuses from 300 up get nginx's own response for that status without the
output, as in 2.7.1. A status set before the firstNginx.rputsor
Nginx.echostill does not apply to the output, which gets 200. Handlers
of other phases are not changed: a rewrite handler that writes output and
then setsNginx::HTTP_ACCEPTEDstill sends no response. Subrequests are
not changed either: a subrequest ends without a response body, and its
parent answers. - Tests: port 18154 (
test/conf/conf.d/68-output-then-status.conf,
test/t/cases/output_then_status.rb).
6. Nginx::Var copies the whole value, so a value with a NUL byte no longer exposes uninitialized worker memory
- Before: the
Nginx::Varaccessor (v.name = value) and
Nginx::Var#set(name, value)copied the value into a request-pool buffer
withngx_cpystrn.ngx_cpystrnstops at the first NUL byte in the
source, but the length recorded for the variable (vv->len) was the full
length of the mruby string. mruby strings are byte strings and can hold a
NUL, for example a value taken from client input such as the request body
or a decoded argument. The bytes after the NUL were therefore never
written, while the variable's length still spanned the whole buffer.
Reading the variable back (Nginx::Var#name, or nginx emitting$name)
returnedvv->lenbytes, so the untouched bytes after the NUL came from
uninitialized request-pool memory. Sending that variable to the client
(Nginx.rputs/Nginx.echoof the variable,add_header $name, a value
placed in a proxied request, or a logged value) then sent those
uninitialized bytes out of the worker. On a worker that had already served
requests, that memory could hold fragments of earlier data and heap
pointers. - Now: ngx_mruby copies the whole value with
ngx_memcpyfor its full
length, so a value that holds a NUL is stored byte for byte and the memory
after the NUL is not exposed. Both the accessor (ngx_mrb_var_set_vector)
andNginx::Var#set(ngx_mrb_var_set_func) are changed. - Why it changed:
- The defect:
ngx_cpystrnstopped the copy at the first NUL while the
variable kept the full length, so a variable set from a value with a NUL
read uninitialized request-pool memory past the NUL, as "Before" says. - Why the old behavior could not be kept: the bytes past the NUL were
never written, so the value read back was not the value that was set,
and on a reused worker it could carry fragments of earlier data and heap
pointers out to the client. A value that holds a NUL has to be stored as
it is, and reading memory past it gives no result worth keeping. - What the documentation promised: the 2.7.1 documentation says that the
accessor andsetset the value to the nginx variable
(Nginx::Var#method_missing of 2.7.1,
Nginx::Var#set of 2.7.1).
It does not say that a value is cut off at a NUL byte, or that reading
the variable back can return other memory.
- The defect:
- Affected: a configuration that stores a value that can hold a NUL byte,
derived from client input, into an nginx variable withNginx::Var#setor
thev.name =accessor, and then sends that variable back toward a client. - What to do: nothing; the value is stored in full. On an earlier release
that you cannot upgrade, remove the NUL bytes before you store the value,
for examplevalue.delete("\x00"). - Not changed by this release: a value that holds no NUL byte is stored and
read back as before. - Tests: port 18153 (
test/t/cases/var_input.rb,/set_nul_valueand
/set_nul_value_via_set).
7. A HEAD request to a content handler that writes output receives only the headers
- Before: for a HEAD request, nginx sets
r->header_only, and the response
should carry the headers without a body. But when the content handler of
the main request wrote output withNginx.rputsorNginx.echo,
ngx_mrb_finalize_rputs(src/http/ngx_http_mruby_core.c) called
ngx_http_send_headerand then passed the output chain to
ngx_http_output_filterwithout checkingr->header_only. A HEAD request
to such a location therefore received the body after the headers. On a
keep-alive connection, the extra body bytes shifted where the client read
the next response, so the responses on the connection no longer lined up
with the requests. When a reverse proxy in front reused one upstream
connection for more than one client, it could pair a response with the
wrong request (a response-queue desynchronization, the HTTP
request/response smuggling class). A client triggered it by sending a HEAD
request to a location whose mruby content handler writes output. - Now: a HEAD request receives no body.
ngx_mrb_finalize_rputschecks
r->header_onlybeforengx_http_output_filter, as nginx's own content
handlers do. The headers,Content-Lengthamong them, are unchanged, so
the HEAD response still reports the length the body would have had. This
holds for the "output and then a status" path of
#594 as well: a HEAD
request to a handler that sets 202 after output receives the headers of
202 with no body. - Why it changed:
- The defect:
ngx_mrb_finalize_rputspassed the output chain to
ngx_http_output_filterwithout checkingr->header_only, so a content
handler that wrote output answered a HEAD request with a body, as
"Before" says. - Why the old behavior could not be kept: a HEAD response must carry no
body, and the body on a keep-alive connection shifted the framing of the
responses that followed, which a front proxy that reuses an upstream
connection across clients could pair with the wrong request. nginx's own
content handlers send no body for HEAD, and the mruby content handler
now does the same. - What the documentation promised: the 2.7.1 documentation says that
Nginx.rputs"Puts response text"
(the methods of 2.7.1).
It does not say that a HEAD request receives that output, and HTTP does
not allow a body in the response to a HEAD request.
- The defect:
- Affected: a location whose main-request handler writes output with
Nginx.rputsorNginx.echoand that receives a HEAD request. The fix is
in the shared output path (ngx_mrb_finalize_rputs), so a content, rewrite
or access handler that writes output sends the headers only for a HEAD
request. - What to do: nothing.
- Not changed by this release: a GET request behaves as before.
- Tests: port 18137 (
test/t/cases/head_output.rb) and the HEAD cases added
to port 18154 (test/t/cases/output_then_status.rb).
8. Nginx::Upstream#server= and Nginx::Stream::Connection#upstream_server= keep the peer valid for later requests and connections (a use-after-free fix)
- Before:
Nginx::Upstream#server=(src/http/ngx_http_mruby_upstream.c)
copied the new server name into memory from the request pool
(ngx_palloc(r->pool, ...)), resolved it with
ngx_parse_url(r->pool, ...), and stored the result into the upstream's
round-robin peer. The peer lives for the worker's lifetime (the
configuration pool), and every request that uses the upstream shares it.
Nginx::Stream::Connection#upstream_server=
(src/stream/ngx_stream_mruby_connection.c) did the same on the stream
side, storing into the peer a Ruby string (which mruby's garbage collector
can free or move) or connection-pool memory. When the request or
connection that set the server ended, its pool was freed, but the shared
peer still pointed into it. A later request or connection that used the
same upstream without calling the setter (aproxy_passto the upstream
from another location, a read ofNginx::Upstream#server, or a read on a
later connection) then read freed memory: the address nginx connected to,
and the name it logged, came from a freed allocation. This is a
use-after-free: it could crash the worker, send the upstream connection to
the wrong address, or disclose freed memory in a log. - Now: ngx_mruby copies the name and the resolved sockaddr into
worker-lifetime storage that belongs to the peer (one per peer, allocated
once in the cycle pool and reused), so the peer no longer points at freed
memory. A repeated setter call reuses the one store instead of growing it;
the store holds 1 to 255 bytes, and the fix also checks that the
destination resolved. BothNginx::Upstream#server=(HTTP) and
Nginx::Stream::Connection#upstream_server=(stream) are changed. - Why it changed:
- The defect: the peer, which lives for the worker's lifetime, pointed at
request-pool or connection-pool memory, and on the stream side at an
mruby string that the garbage collector can move, so a later use of the
upstream read memory that had been freed, as "Before" says. - Why the old behavior could not be kept: the peer outlives the request or
connection that set it, so it cannot hold a pointer into their pools.
The name and the address have to live as long as the peer, so the fix
copies them into storage that lives for the worker's lifetime. - What the documentation promised: the documented usage sets the server in
mruby_rewrite_handler_codeand proxy_passes in the same request.
Nothing said that a later request that does not set the server reads a
valid peer, or that readingNginx::Upstream#serverafter the setting
request ended returns valid memory.
- The defect: the peer, which lives for the worker's lifetime, pointed at
- Affected: a configuration that uses
Nginx::Upstream#server=(HTTP) or
Nginx::Stream::Connection#upstream_server=(stream). - What to do: nothing.
- Not changed by this release: setting the server on each request or
connection that uses the upstream still works, and the value read back is
the value that was set. - Not changed by this release: an upstream with a shared-memory
zonekeeps
its peer in shared memory that every worker shares, so pointing the peer
at any one worker's memory (the per-worker store of this fix, or the
request pool of the old code) is invalid across workers. This release
corrects the case without azone. An upstream with azoneneeds the
name and the sockaddr in the zone's slab, which is outside the scope of
this release; the old code was worse here, an existing problem. - Tests: HTTP on port 18139 (
test/t/cases/upstream_server.rb), stream on
ports 12364 and 12365 (test/t/cases/stream_upstream_server.rb).
アップグレードの前に読む挙動の変更
1. 変数を指さないメソッド名や値の無いセッターでNginx::Varを呼ぶと、例外が発生します(#589)
- 変更前:
Nginx::Varは、自分が定義していないメソッドの呼び出しを、同じ名前のnginxの変数へのアクセスとして扱います。たとえばv.http_hostは$http_hostを読みます。名前が=で終わるメソッドは、=の前の名前の変数に値を設定するセッターとして扱います。たとえばv.http_host = "a"は$http_hostに値を設定します。実行時に名前を組み立てるコードは、名前をsendに渡します。次の3種類の名前では、アクセサが名前か引数の外のメモリを読んだので、結果はそのメモリの内容で決まりました。v.send("")のように空の名前で呼ぶと、アクセサは名前の前の1バイトを読みました。結果は、たいていnilでした。v.send("=", "x")のように=だけでできた名前で呼ぶと、アクセサは名前の終わりより先を読みました。nilが返ることも、ワーカープロセスが終了することもありました。v.send("http_host=")のように値を渡さずにセッターを呼ぶと、アクセサは引数の外から値を読みました。ワーカープロセスが終了することも、コードが渡していない値が変数に設定されることもありました。
- 変更後:空の名前と、
=だけでできた名前では、NoMethodErrorが発生します。メッセージは、undefined method '' for Nginx::Varとundefined method '=' for Nginx::Varです。値を渡さずにセッターを呼ぶと、ArgumentErrorが発生し、変数は元の値のままです。メッセージはwrong number of arguments (given 0, expected 1) for Nginx::Var#http_host=です。アクセサは、名前と引数を読む前に、それらを確かめます。 - 変更の理由:
- 不具合:「変更前」に書いたとおり、アクセサは、空の名前では名前の前の1バイトを読みました。
=だけでできた名前では、名前のコピーの終わりより先までstrtokで読みました。値の無いセッターでは、空の引数の並びから最初の要素を読みました(#589)。 - 前の挙動を残せなかった理由:これらの呼び出しの結果は、名前と引数の外のメモリから来ていました。そのため、同じ呼び出しでも、
nilが返ることも、ワーカープロセスが終了することもありました。このような名前はどの変数も指さず、引数の無いセッターには設定する値がありません。そのため、残せる結果がありません。代わりに、Rubyと同じ例外が発生します。受け手に無いメソッドを呼んだときのNoMethodErrorと、メソッドが取る数より少ない引数で呼んだときのArgumentErrorです。 - ドキュメントが示していた挙動:2.7.1のドキュメントには、アクセサが
Nginx::Var#VARNAMEとNginx::Var#VARNAME=で呼ばれると書いてあります。名前が=で終わるときは、「the 2nd arg」を変数に設定するとも書いてあります(2.7.1のNginx::Var#method_missing)。変数の名前を含まない名前と、値の無いセッターについては、何も書いてありません。
- 不具合:「変更前」に書いたとおり、アクセサは、空の名前では名前の前の1バイトを読みました。
- 影響の範囲:
send、public_send、method_missingに実行時に組み立てた名前を渡してNginx::Varを呼ぶコードのうち、名前が空か=だけになりうるものです。値を渡さずにセッターを呼ぶコードも、影響を受けます。 - 必要な対応:呼び出しの前に名前を確かめるか、名前が空になりうるところで
NoMethodErrorをrescueしてください。セッターには、必ず値を渡してください。 - このリリースで変わらない挙動:アクセサが読み書きする変数は、前と同じです。大文字を含む名前も、前と同じく、小文字にした名前の変数を指します。2つ以上の値を渡したセッターは、これまでどおり最初の値を使います。
=foo=のような名前も、これまでどおり$fooに値を設定します。 - テスト:
test/t/cases/var_input.rbのポート18153のテストです。
2. Nginx::Var#setは、名前として渡したStringとSymbolを変えなくなりました(#589)
- 変更前:
Nginx::Var#set(name, value)は、小文字にした名前で変数を探しました。その名前を得るために、nameのバイトをその場で小文字に書き換えました。そのため、呼び出しの後、nameに渡したStringは小文字になっていました。freezeしたStringでも同じでした。バイトを共有するStringも、小文字になりました。たとえば、長いStringからdupで作ったコピーです。長い名前のSymbolでは、setは、ワーカーがそのSymbolのために持つ名前を小文字に書き換えました。そのため、そのワーカーの後のどのリクエストでも、そのSymbolのto_sは小文字の名前を返しました。ここで長いとは、64ビットのビルドで27バイトを超えることです。mrubyは、それより短いStringをStringのオブジェクトの中に持ち、コピーはそのバイトを共有しません。 - 変更後:
setは、名前を小文字にしたコピーで変数を探します。nameに渡したStringとSymbolは、元のままです。setが値を設定する変数と、setが返す値は、前と同じです。 - 変更の理由:
- 不具合:「変更前」に書いたとおり、
setは、nameに渡したStringに書き込みました。その結果、freezeしたString、バイトを共有するString、Symbolの名前まで書き換わりました(#589)。 - 前の挙動を残せなかった理由:freezeしたStringは、変更できないはずのオブジェクトです。バイトを共有するStringは、コードが持つ別のオブジェクトです。Symbolの名前は、ワーカーのすべてのリクエストが使います。変数を探すには小文字の名前が要るので、
setはコピーを小文字にします。 - ドキュメントが示していた挙動:2.7.1のドキュメントには、
setはnginxの変数に値を設定すると書いてあります(2.7.1のNginx::Var#set)。setが引数を変えるとは、書いてありません。
- 不具合:「変更前」に書いたとおり、
- 影響の範囲:
setに渡したStringかSymbolを呼び出しの後で使い、それが小文字になっていると期待するコードです。 - 必要な対応:
setが名前を小文字にすることに頼っていたコードでなければ、対応は要りません。そのようなコードでは、自分で名前にdowncaseを呼んでください。 - テスト:
test/t/cases/var_input.rbのポート18153のテストです。
3. Redisがデフォルトのビルドに戻り、mruby-redisはどのプラットフォームでもhiredisのv1.5.0をビルドし、hiredisの警告では止まらなくなりました(#604、matsumotory/mruby-redis#108)
- 変更前:2.7.1のリリースノートの項目1に書いたとおり、2.7.1のデフォルトの
build_config.rbにはmatsumotory/mruby-redisが入っていません。そのため、このbuild_config.rbでビルドしたバイナリにはRedisクラスが無く、Redisを参照するコードではNameErrorが発生します。そのメッセージは「uninitialized constant Redis」です。conf.gem github: 'matsumotory/mruby-redis'のコメントアウトを外すか、独自のbuild_config.rbでこのgemを有効にしたビルドは、gemのビルドスクリプトからhiredisを得ます。gemのビルドディレクトリにhiredisディレクトリがまだ無いとき、このスクリプトはhiredisをデフォルトブランチの先頭からcloneし、macOSではv0.13.3をcheckoutしました。スクリプトはmrubyのビルドのCのフラグでhiredisをコンパイルし、hiredisの1.2.0以降のMakefileは-Werrorを加えます。そのため、hiredisに新しい警告が出ると、ビルドが止まりました。hiredisの1.4.0以降とmrubyのgccのツールチェーンを組み合わせると、ビルドはffc.h:330:5: error: "FFC_DEBUG" is not defined, evaluates to 0 [-Werror=undef]で止まりました。 - 変更後:デフォルトの
build_config.rbに、matsumotory/mruby-redisが戻りました(#604)。2.7.0以前のデフォルトのbuild_config.rbと同じです。このbuild_config.rbでビルドしたバイナリにはRedisクラスがあり、そのビルドはgemとhiredisをGitHubからcloneします。gemのビルドスクリプトは、macOSを含むすべてのプラットフォームで、hiredisのタグv1.5.0をhiredis-v1.5.0にcloneします。cloneしたツリーが、このタグのコミット5bb7f030f6631b243438cf0fdd3be84352b905bbでないときは、両方のコミットを示すメッセージを出してビルドを止めます。スクリプトはhiredisをUSE_WERROR=0でビルドするので、ビルドはhiredisの警告を表示して先へ進みます。また、スクリプトはhiredisをmake installだけでビルドするので、hiredis-testをビルドしなくなりました。Alpineのようなmuslのシステムでは、linux-headersが要らなくなりました。前のビルドが残したhiredisディレクトリは使いません。hiredisの変更は、gemの変更です。ngx_mrubyの2.xはgemのlockをコミットしていないので、ビルドはgemをmasterブランチの先頭からcloneします。matsumotory/mruby-redis#108のマージの後にgemをcloneするビルドは、すべてこの変更を受けます。2.7.1のビルドも同じです。mrubyは、前にcloneしたgemを更新しません。また、mrubyは、build_config.rb.lockが記録したコミットでgemをcheckoutします。このファイルは、mrubyがビルドの終わりに書き、2.xではgitが無視するファイルです。そのため、マージの前にmruby-redisをビルドしたソースツリーは、mrubyのビルドディレクトリmruby/buildとbuild_config.rb.lockの両方を消すまで、前のコミットのgemとそのhiredisを使い続けます。 - 変更の理由:
- 不具合:バージョンを固定しないcloneのため、hiredisの新しいコミットは、gemを有効にしたすべての新しいビルドに届きました。hiredisの1.4.0は、上の
FFC_DEBUGのエラーで、そのようなビルドを止めました(#528、matsumotory/mruby-redis#108)。2.7.1は、この不具合のために、gemをデフォルトのビルドから外しました。2.7.1のリリースノートの項目1に、そう書いてあります。 - 前の挙動を残せなかった理由:hiredisのデフォルトブランチに追従するビルドは、hiredisのどのコミットでも壊れる可能性があります。2.7.1がgemをデフォルトのビルドから外したのは、このためです。リリースを固定してそのコミットを確かめると、どのビルドも同じhiredisを使います。
-Werrorも外す必要がありました。ngx_mrubyのsanitizerのフラグ-fsanitize=address,undefined -fno-omit-frame-pointerを付けると、gccの13から15では、hiredisのv1.5.0のビルドがsds.c:525のnull format string [-Werror=format-truncation=]で止まります。そのため、-Werrorを残すと、新しいコンパイラーでは、固定したビルドも壊れます。USE_WERROR=0は、-Werrorを使わないビルドのために、hiredisの1.3.0以降が用意したスイッチです(redis/hiredis#1210)。v1.5.0は、LinuxとmacOSでビルドでき、gemのテストに通ります。そのため、macOSでもv0.13.3は要らなくなりました。hiredisを固定したので、gemをデフォルトのビルドから外しておく理由は無くなりました。2.7.1のリリースノートの項目1は、「mruby-redisがhiredisを固定するまで」gemをデフォルトの一覧に残せないとしていました。gemを外したままにすると、2.7.0以前のデフォルトのビルドでRedisを使っていたスクリプトは、Redisを使えないままです。READMEとdocs/use_caseの例と、同梱のauto-sslmrbgemのクライアントも、これに当たります。 - ドキュメントが示していた挙動:2.7.1のリリースノートの項目1には、「#528に書いたhiredisの問題が残っている間は、このgemのビルドが失敗することがあります」と書いてあります。2.7.1のドキュメントには、
build_config.rbでこのgemの行のコメントアウトを外すと書いてあります(2.7.1のbuilt-in mrbgems)。このgemのビルドについては、「clones the hiredis library from an unpinned branch, which broke the build of ngx_mruby」と書いてあります(2.7.1のdocs/install)。hiredisのバージョンは書いてありません。また、Redisクラスについては、「is not in the default build since 2.7.1」と書いてあります。2.7.0のドキュメントでは、mruby-redisが「the default mrbgems」の1つに入っていました(2.7.0のdocs/install)。また、Redisは「with default build configuration」で使えるクラスの1つに入っていました(2.7.0のbuilt-in mrbgems)。
- 不具合:バージョンを固定しないcloneのため、hiredisの新しいコミットは、gemを有効にしたすべての新しいビルドに届きました。hiredisの1.4.0は、上の
- 影響の範囲:2.7.2のデフォルトのビルドです。そのバイナリには
Redisクラスが戻るので、Redisを参照するコードでNameErrorが発生しなくなります。そのビルドは、GitHubから3つのリポジトリを余分にcloneします。それぞれのmasterブランチの先頭のmatsumotory/mruby-redisとmatsumotory/mruby-pointerと、hiredisのタグv1.5.0です。mruby-pointerは、mruby-redisが依存するgemで、クラスを加えません。そして、ビルドはhiredisをnginxか動的モジュールに静的にリンクするので、そのサイズが約190 KB増えます。たとえば、nextの性能の比較は、test/build_release.shでリリースのオプションのnginxをビルドします。そのオプションでビルドしてstripした静的なnginxは、Linux aarch64とgcc 11.4で、3.88 MBから4.08 MBになります。Redisのサーバーが要るのは、Redisを呼ぶスクリプトだけです。hiredisの変更が影響するのは、2.7.2のデフォルトのビルド、mruby-redisを有効にした2.7.1のビルド、2.7.0以前のデフォルトのビルドです。2.7.0以前のデフォルトのbuild_config.rbには、このgemが入っています。これらのビルドは、マージの後にgemをcloneすると、hiredisのデフォルトブランチの先頭の代わりに、macOSではv0.13.3の代わりに、hiredisのv1.5.0を使います。mruby-redis#108は、gemをmruby 3.3.0とmruby 4.0.0で試しました。2.6.0から2.7.2はmruby 3.3.0を同梱し、2.5.0以前はそれより古いmrubyを同梱します。gemはhiredisを静的にリンクするので、前にビルドしたバイナリは、mruby/buildとbuild_config.rb.lockを消してビルドし直すまで前のhiredisのままです。2.7.1のデフォルトのbuild_config.rbでのビルドは、このgemを含まないので、影響を受けません。 - 必要な対応:2.7.2のデフォルトのビルドでは、対応は要りません。ただし、前にこのソースツリーでmruby-redisをビルドしたときは、先に
mruby/buildとbuild_config.rb.lockを消してください。mruby-redisを有効にしたビルドと、2.7.0以前のデフォルトのビルドが、これに当たります。mruby/buildだけを消しても足りません。次のビルドはgemをcloneし直しますが、lockが記録したコミットでcheckoutするので、hiredisはバージョンを固定しないcloneのままです。そのうえで、これまでどおりビルドしてください。2.7.1のリリースノートの項目1の注意「このgemのビルドが失敗することがあります」は、もう当てはまりません。2.7.1のデフォルトのビルドと同じくgemを入れずにビルドするには、build_config.rbのconf.gem github: 'matsumotory/mruby-redis'をコメントアウトしてください。ほかのhiredisのリリースでビルドするには、ビルドのときに環境変数MRUBY_REDIS_HIREDIS_VERSIONにそのタグを設定するか、build_config.rbでENV['MRUBY_REDIS_HIREDIS_VERSION']を設定してください。設定の方法は、mruby-redisのREADMEに書いてあります。ほかのタグでは、ビルドはコミットを確かめません。mruby-redis#108では、前の先頭のコミット2cc63c1で、gccとmruby 3.3.0を使い、v1.4.1でもビルドとテストをしました。 - このリリースで変わらない挙動:2.7.0と、gemを有効にした2.7.1のビルドと同じく、
Redisの呼び出しは、Redisのサーバーが答えるまでワーカーの中で待ちます。gemがhiredisのブロックするAPIを使うためです。その間、ワーカーはほかのリクエストを処理しません。mruby-redis#108は、mruby 4.0.0のためにRedis#ttlの宣言を変えました。同梱のmruby 3.3.0では、Redis#ttlは前と同じに動きます。 - テスト:ngx_mrubyのテストスイートには、Redisを呼ぶテストがありません。また、テストスイートはRedisのサーバーを起動しません。#604から、テストスイートのデフォルトのビルドはこのgemをビルドします。そのため、sanitizerのセルを含むCIのすべてのセルが、gemをビルドしてhiredisをリンクし、テストのnginxには
Redisクラスがあります。#604には、masterでのテストスイートの結果が載っています。静的なモジュール、動的なモジュール、sanitizerのそれぞれの結果です。また、nginxのバイナリにあるgemとhiredisのシンボルと、Redisを呼ぶリクエストの結果も載っています。リクエストの結果は、Redisのサーバーが動いていないときと動いているときの両方です。mruby-redis#108には、ngx_mrubyのmaster(03aad7031)とnext(75bfa6ff4)のテストスイートの結果が載っています。どちらも、そのプルリクエストの先頭のコミットでgemを有効にしてビルドし、テストに通りました。gemのCIは、Ubuntu 22.04とUbuntu 24.04でgemのテストを流します。Ubuntu 24.04では、ngx_mrubyのCIのsanitizerの設定を使います。
4. Redis.connect_set_udptrと引数の無いRedis.newは、接続をmrb->udでなくmrb_stateに持つようになり、引数が1つのRedis.newはArgumentErrorを発生させます(matsumotory/mruby-redis#109)
- 変更前:mruby-redisを含むビルドでは、
Redis.connect_set_udptr host, port[, timeout]がサーバーに接続し、その接続をmatsumotory/mruby-pointerに預けました。このメソッドにはRedis.connect_set_rawという別名もあります。mruby-pointerは、自分の構造体をmrb_stateのユーザーデータのポインタmrb->udに置きます。引数の無いRedis.newは、そこから接続を読みました。一方、ngx_mrubyも自分のデータをmrb->udに置きます。streamのモジュールは、stream {}ブロックのどのコードが動く間も、mrb->udに自分のコンテキストを置きます。HTTPのモジュールは、mruby_server_context_handler_code、mruby_ssl_handshake_handler、mruby_ssl_handshake_handler_codeのコードが動く間、mrb->udにサーバーの設定を置きます。これらのコードでは、2つのメソッドは接続をngx_mrubyのデータに書き込み、そこから読みました。http {}ブロックのほかのコードでは、mrb->udはNULLです。そこでは、Redis.connect_set_udptrは接続した後にRuntimeErrorを発生させ、その接続を開いたまま残しました。メッセージは「can not set, mrb ud pointer was not initialized」です。引数の無いRedis.newもRuntimeErrorを発生させました。メッセージは「can not get. mrb ud pointer was not initialized」です。接続を預けた後は、引数の無いRedis.newを呼ぶたびに、同じ接続を持つオブジェクトが返りました。これらのオブジェクトは、GCで回収されるときに、それぞれその接続を閉じました。引数が1つのRedis.newは、その呼び出しが設定していない値を使いました。新しいオブジェクトでは、その値はNULLのポインタでした。そのため、ワーカープロセスが終了しました。 - 変更後:gemは、接続を
mrb_stateの中に持ちます。置き場はRedisクラスのインスタンス変数で、Rubyのコードからは読めません。gemはmrb->udを読み書きしなくなりました。2つのメソッドは、http {}ブロックでもstream {}ブロックでも、どのコードでも同じに動きます。Redis.connect_set_udptrは接続を持っておきます。接続に成功したときは、前に持っておいた接続のうち、Redis.newがまだ受け取っていないものを閉じます。Redis.connect_set_udptrは、接続に失敗すると、前と同じくRedis::ConnectionErrorを発生させます。このとき、失敗した接続を閉じるようになりました。前に持っておいた接続は、そのまま残ります。引数の無いRedis.newは、持っておいた接続を受け取ります。接続を持つオブジェクトは1つだけになります。そのため、引数の無いRedis.newを2回目に呼ぶと、Redis.connect_set_udptrをもう一度呼ぶまで例外が発生します。持っておいた接続が無いときも同じです。この例外はRuntimeErrorのサブクラスのRedis::ConnectionErrorで、メッセージは「no connection kept: call Redis.connect_set_udptr first」です。引数が1つのRedis.newはArgumentErrorを発生させます。メッセージは「wrong number of arguments (given 1, expected 0, 2 or 3)」です。この変更は、gemの変更です。ngx_mrubyの2.xはgemのlockをコミットしていないので、matsumotory/mruby-redis#109のマージの後にgemをcloneするビルドは、すべてこの変更を受けます。2.7.1のビルドも同じです。前にこのgemをビルドしたソースツリーは、mruby/buildとbuild_config.rb.lockを消すまで、前にcloneしたgemを使い続けます。項目3も参照してください。 - 変更の理由:
- 不具合:mrubyは、
mrb->udを、mrubyを組み込むアプリケーションに任せています。ngx_mrubyは、mrb->udを使います。2つのメソッドは、上に挙げたコードでngx_mrubyのデータをmruby-pointerの構造体として使い、http {}ブロックのほかのコードでは例外を発生させました。引数が1つのRedis.newは、その呼び出しが設定していない値を使いました(matsumotory/mruby-redis#109)。 - 前の挙動を残せなかった理由:
mrb->udには、gemのデータを置く場所がありません。gemが接続をmrb->udに置く限り、2つのメソッドは次のどちらかになります。ngx_mrubyがmrb->udをNULLにしているところでは、例外を発生させます。そうでないところでは、ngx_mrubyのデータを使います。また、1つの接続を複数のオブジェクトに渡すと、オブジェクトはそれぞれその接続を閉じます。そのため、同じ接続が2回以上閉じられます。接続を持つオブジェクトを1つにすると、接続は1回だけ閉じられます。引数が1つの呼び出しには、接続するホストとポートがそろっていません。前の結果は、その呼び出しが設定していないポインタから来ていたので、残せる結果がありません。そのため、引数の数が合わないときにRubyが発生させるArgumentErrorを発生させます。 - ドキュメントが示していた挙動:この変更の前は、mruby-redisのREADMEにも、ngx_mrubyのドキュメントにも、2つのメソッドの説明はありませんでした。mruby-pointerのREADMEには、2つのメソッドを使うCのプログラムの例があります。この例は、
mrb_udptr_initとmrb_udptr_copyを呼んで、2つのmrb_stateの間で接続を共有します。ngx_mrubyは、どちらの関数も呼びません。
- 不具合:mrubyは、
- 影響の範囲:
Redis.connect_set_udptrかRedis.connect_set_rawを呼ぶスクリプトと、引数を付けずに、または引数を1つだけ付けてRedis.newを呼ぶスクリプトです。対象のビルドは、mruby-redisがデフォルトのビルドに戻った2.7.2のデフォルトのビルドと、このgemを含むほかのビルドです。ほかのビルドは、gemを有効にした2.7.1のビルドと、2.7.0以前のデフォルトのビルドです。デフォルトのビルドに戻ったことは、項目3に書いてあります。すべてのRedisのオブジェクトをRedis.new host, port[, timeout]で作るスクリプトは、影響を受けません。 - 必要な対応:引数の無い
Redis.newを2回目以降に呼ぶ前には、Redis.connect_set_udptrをもう一度呼んでください。または、Redis.newが返したオブジェクトを持っておいて使い回すか、代わりにRedis.new host, portを呼んでください。Redis::ConnectionErrorはRuntimeErrorのサブクラスです。そのため、引数の無いRedis.newのRuntimeErrorをrescueしていたコードは、新しい例外もそのままrescueします。例外のクラスをRuntimeErrorと完全に一致させて比べるコードと、メッセージを比べるコードだけを直してください。Redis.connect_set_udptrは、ワーカーで動くコードで呼んでください。mruby_init_worker_code、mruby_stream_init_worker_code、ハンドラーがこれに当たります。mruby_init_code、mruby_server_context_handler_code、mruby_stream_init_code、mruby_stream_server_context_codeで持っておいた接続は、すべてのワーカーにコピーされます。前にこのソースツリーでmruby-redisをビルドしたときは、先にmruby/buildとbuild_config.rb.lockを消してください。 - このリリースで変わらない挙動:
Redis.new host, port[, timeout]と、Redisのほかのメソッドは、前と同じに動きます。mruby-redisのビルドは、gemがもう呼ばないmatsumotory/mruby-pointerを、これまでどおりcloneします。 - テスト:ngx_mrubyのテストスイートには、Redisを使うテストがありません。mruby-redis#109は、
Redis.connect_set_udptr、Redis.connect_set_raw、引数の無いRedis.new、引数が1つのRedis.newのテストをgemに加えます。その中には、ホストのアプリケーションと同じ方法でmrb->udを設定したテストがあります。また、そのプルリクエストには、ngx_mrubyのmasterとnextのテストスイートの結果が載っています。どちらも、そのプルリクエストの先頭のコミットでgemを有効にしてビルドし、テストに通りました。
5. 出力を書いてから300未満のステータスを設定したcontentハンドラは、そのステータスで応答します(#594)
- 変更前:メインリクエストの
mruby_content_handler*が、Nginx.rputsかNginx.echoで出力を書いてから、Nginx.return、Nginx.send_header、Nginx.status_code=のどれかで、200、201、204以外の300未満のステータスか0を設定すると、レスポンスが送られませんでした。300未満のステータスの例はNginx::HTTP_ACCEPTEDです。nginxは、HTTP/1.0の接続を1バイトも送らずに閉じ、HTTP/1.1のkeep-aliveの接続を、keepalive_timeoutまでレスポンスなしで開いたままにしました。keepalive_timeoutのデフォルトは75秒です。そのため、クライアントは自分のタイムアウトまで待ちました。2.7.1では、この件を「既知の制限」の節に書いていました。 - 変更後:そのようなリクエストには、ハンドラが設定したステータスで出力が返ります。
Content-Lengthは出力の長さです。これは、nginx自身のreturn 202 "text";の応答からContent-Typeを除いたものと同じです。ngx_mrubyは、出力の後の200と同じく、Content-Typeを付けません。Nginx::Async::HTTP.sub_requestが再開した後にこのように終わった場合も、同じです。たとえば、Nginx.rputs "queued"の後にNginx.return Nginx::HTTP_ACCEPTEDを呼ぶと、ボディがqueuedの202 Acceptedが返ります。200未満のステータスも同じように送られ、ステータス行は理由句の無い数字だけになります。たとえば、100のステータス行はHTTP/1.1 100です。nginx自身のreturn 100 "text";も、同じように送ります。ただし、HTTPでは、このようなステータスを最終のレスポンスに使えません。Nginx.return 0はステータスを設定しないので、ステータスの無い出力と同じく、出力は200で返ります。keep-aliveの接続は、出力のある200の後と同じく、次のリクエストのために開いたままです。 - 変更の理由:
- 不具合:出力の後の
Nginx.returnは出力の終わりに印を付け、ngx_mrubyは、出力を送らずにステータスをnginxに渡していました。nginxは、201、204、300以上のステータスには、自分でレスポンスを送ります。しかし、それ以外の300未満のステータスでは、何も送らずにリクエストを終えます。そのため、リクエストにレスポンスがありませんでした。#566は出力の無いハンドラについてこれを直し、そのレビューが記録したとおり、この場合は残していました。このリリースで、この場合を直しました(#594)。 - 前の挙動を残せなかった理由:残すと、これらのリクエストはレスポンスの無いままになります。出力を書いてから200を設定するcontentハンドラは、既に出力で応答しています。この修正は、nginxが自分で応答しない残りのステータスにも、同じように、ハンドラが設定したステータスで応答します。2.7.1でレスポンスを受け取っていたリクエストが、違うレスポンスを受け取ることはありません。
- ドキュメントが示していた挙動:2.7.1のドキュメントには、
Nginx.rputsは「Puts response text」、Nginx.returnは「Returns nginx status code to send back HTTP status to the client」と書いてあります(2.7.1のNginx.return)。2.7.1のリリースノートは、この場合を「既知の制限」の節に書いていました(v2.7.1.ja.md)。メソッドのドキュメントには、出力の後にこのようなステータスを設定したcontentハンドラが何を返すかは、書いてありませんでした。
- 不具合:出力の後の
- 影響の範囲:出力を書いてから、200、201、204以外の300未満のステータスか0を設定する
mruby_content_handler*のハンドラです。 - 必要な対応:出力をそのステータスで返すつもりのハンドラには、対応は要りません。200で応答すべきハンドラは、
Nginx::HTTP_OKを設定してください。 - このリリースで変わらない挙動:出力の後の
Nginx::HTTP_OKは、2.7.1と同じく、出力を200で返します。出力の後のNginx::HTTP_CREATED、Nginx::HTTP_NO_CONTENT、300以上のステータスには、2.7.1と同じく、出力の無い、nginx自身のそのステータスの応答が返ります。最初のNginx.rputsかNginx.echoより前に設定したステータスは、これまでどおり出力に使われず、出力は200で返ります。ほかのフェーズのハンドラも変わりません。出力を書いてからNginx::HTTP_ACCEPTEDを設定するrewriteハンドラは、これまでどおりレスポンスを送りません。サブリクエストも変わりません。サブリクエストはレスポンスのボディなしで終わり、親のリクエストが応答します。 - テスト:
test/conf/conf.d/68-output-then-status.confとtest/t/cases/output_then_status.rbの、ポート18154のテストです。
6. Nginx::Varは値の全体をコピーするので、NULバイトを含む値でもワーカーの未初期化メモリが漏れなくなりました
- 変更前:
Nginx::Varのアクセサ(v.name = value)とNginx::Var#set(name, value)は、値をngx_cpystrnでリクエストのプールのバッファにコピーしました。ngx_cpystrnは、元の値の最初のNULバイトでコピーを止めます。しかし、変数に記録する長さ(vv->len)は、mrubyの文字列の全長でした。mrubyの文字列はバイト列で、NULを含むことがあります。リクエストボディやデコードした引数のような、クライアント由来の値がこれに当たります。そのため、NULより後ろのバイトは書かれないまま残り、変数の長さはバッファの全体を指しました。変数を読み戻すと、vv->lenバイトが返ります。読み戻すのは、Nginx::Var#nameを呼ぶときや、nginxが$nameを出力するときです。そのため、NULより後ろの手つかずのバイトは、リクエストのプールにある未初期化のメモリから来ました。さらに、その変数をクライアントへ出すと、未初期化のバイトがワーカーの外へ出ました。クライアントへ出すのは、変数のNginx.rputsやNginx.echo、add_header $name、proxyするリクエストに入れた値、ログに出した値のときです。既にリクエストを処理したワーカーでは、そのメモリは、前のデータの断片やヒープのポインタを持つことがありました。 - 変更後:値の全長を
ngx_memcpyでコピーします。そのため、NULを含む値もバイト単位でそのまま保存され、NULより後ろのメモリは露出しません。アクセサ(ngx_mrb_var_set_vector)とNginx::Var#set(ngx_mrb_var_set_func)の両方を直しました。 - 変更の理由:
- 不具合:「変更前」に書いたとおり、
ngx_cpystrnは最初のNULでコピーを止める一方、変数は全長を持ちました。そのため、NULを含む値で設定した変数は、NULより後ろの、リクエストのプールにある未初期化のメモリを読みました。 - 前の挙動を残せなかった理由:NULより後ろのバイトは書かれていないので、読み戻す値は、設定した値ではありませんでした。また、使い回したワーカーでは、前のデータの断片やヒープのポインタをクライアントへ運ぶことがありました。NULを含む値はそのまま保存する必要があり、その後ろのメモリを読んでも、残せる結果はありません。
- ドキュメントが示していた挙動:2.7.1のドキュメントには、アクセサと
setはnginxの変数に値を設定すると書いてあります(2.7.1のNginx::Var#method_missing、2.7.1のNginx::Var#set)。値がNULバイトで切れることや、変数を読み戻すとほかのメモリが返ることは、書いてありません。
- 不具合:「変更前」に書いたとおり、
- 影響の範囲:クライアント由来でNULバイトを含みうる値を、
Nginx::Var#setかv.name =のアクセサでnginxの変数に入れ、その変数をクライアントへ出す設定です。 - 必要な対応:対応は要りません。値は全長で保存されます。アップグレードできない旧版では、値を保存する前にNULバイトを除いてください。たとえば
value.delete("\x00")です。 - このリリースで変わらない挙動:NULバイトを含まない値は、前と同じく保存され、読み戻されます。
- テスト:
test/t/cases/var_input.rbの/set_nul_valueと/set_nul_value_via_setの、ポート18153のテストです。
7. 出力を書くcontentハンドラへのHEADリクエストは、ヘッダだけを受け取るようになりました
- 変更前:HEADリクエストでは、nginxが
r->header_onlyを立て、レスポンスはボディなしのヘッダだけであるべきです。しかし、メインリクエストのcontentハンドラがNginx.rputsかNginx.echoで出力を書くと、ngx_mrb_finalize_rputs(src/http/ngx_http_mruby_core.c)は、r->header_onlyを見ずに、ngx_http_send_headerの後で出力のチェインをngx_http_output_filterに渡しました。そのため、このようなlocationへのHEADリクエストは、ヘッダの後にボディを受け取りました。keep-aliveの接続では、余分なボディのバイトが、クライアントが次のレスポンスを読む位置をずらしました。そのため、その接続のレスポンスとリクエストの対応が崩れました。前段のリバースproxyが1本の上流の接続を複数のクライアントで使い回すと、レスポンスを別のリクエストに対応づけることがありました。これは、レスポンスのキューがずれる問題で、HTTPのリクエストとレスポンスのスマグリングの類です。クライアントは、出力するmrubyのcontentハンドラのあるlocationへHEADリクエストを送るだけで、これを起こせました。 - 変更後:HEADリクエストには、ボディを送りません。
ngx_mrb_finalize_rputsは、nginx自身のcontentハンドラと同じく、ngx_http_output_filterの前にr->header_onlyを見ます。Content-Lengthを含むヘッダは変わらないので、HEADのレスポンスは、ボディが持つはずだった長さを、これまでどおり報告します。これは、#594の「出力の後にステータスを設定する」経路にも効きます。出力の後に202を設定するハンドラへのHEADリクエストは、ボディなしで202のヘッダを受け取ります。 - 変更の理由:
- 不具合:「変更前」に書いたとおり、
ngx_mrb_finalize_rputsは、r->header_onlyを見ずに出力のチェインをngx_http_output_filterに渡しました。そのため、出力を書いたcontentハンドラは、HEADリクエストにボディで応答しました。 - 前の挙動を残せなかった理由:HEADのレスポンスはボディを持てません。keep-aliveの接続では、このボディが後続のレスポンスのフレーミングをずらし、上流の接続をクライアントをまたいで使い回す前段のproxyが、それを別のリクエストに対応づけることがありました。nginx自身のcontentハンドラは、HEADにボディを送りません。mrubyのcontentハンドラも、同じようにします。
- ドキュメントが示していた挙動:2.7.1のドキュメントには、
Nginx.rputsは「Puts response text」と書いてあります(2.7.1のメソッド)。HEADリクエストがその出力を受け取るとは、書いてありません。また、HTTPは、HEADリクエストへのレスポンスにボディを認めていません。
- 不具合:「変更前」に書いたとおり、
- 影響の範囲:
Nginx.rputsかNginx.echoで出力を書く、メインリクエストのハンドラのあるlocationで、HEADリクエストを受け取る設定です。この修正は共有の出力処理ngx_mrb_finalize_rputsにあるので、contentハンドラだけでなく、出力を書くrewriteハンドラやaccessハンドラも、HEADリクエストにはヘッダだけを返します。 - 必要な対応:対応は要りません。
- このリリースで変わらない挙動:GETリクエストは、前と同じに動きます。
- テスト:
test/t/cases/head_output.rbのポート18137のテストと、test/t/cases/output_then_status.rbのポート18154に足したHEADのケースです。
8. Nginx::Upstream#server=とNginx::Stream::Connection#upstream_server=は、後続のリクエストや接続でもpeerを有効に保ち、use-after-freeが起きなくなりました
- 変更前:
Nginx::Upstream#server=(src/http/ngx_http_mruby_upstream.c)は、新しいサーバー名をリクエストのプールのメモリ(ngx_palloc(r->pool, ...))にコピーし、ngx_parse_url(r->pool, ...)で解決して、その結果をupstreamのround-robinのpeerに入れました。peerは、ワーカーの寿命を持つconfiguration poolにあり、そのupstreamを使うすべてのリクエストが共有します。stream側のNginx::Stream::Connection#upstream_server=(src/stream/ngx_stream_mruby_connection.c)も同じで、peerにRubyの文字列や、connection poolのメモリを入れました。このRubyの文字列は、mrubyのGCが解放や移動をしうる文字列です。サーバーを設定したリクエストや接続が終わると、そのプールは解放されますが、共有のpeerは、そこを指したままでした。server=を呼ばずに同じupstreamを使う後続のリクエストや接続は、解放済みのメモリを読みました。これに当たるのは、別のlocationからそのupstreamへのproxy_passや、Nginx::Upstream#serverの読み取りや、後続の接続での読み取りです。nginxが接続する宛先と、ログに出す名前が、解放済みの領域から来ました。これはuse-after-freeで、ワーカーのクラッシュ、宛先の取り違え、ログへの解放済みメモリの漏洩が起こりえました。 - 変更後:名前と解決後のsockaddrを、peerごとに、ワーカーの寿命を持つストアにコピーします。このストアは、peerにつき1つで、cycle poolに1回だけ確保して再利用します。そのため、peerは解放済みのメモリを指しません。server=を繰り返して呼んでも、1つのストアを再利用するので、増え続けません。ストアは1から255バイトを持ち、宛先が解決できたことも確かめます。
Nginx::Upstream#server=(HTTP)とNginx::Stream::Connection#upstream_server=(stream)の両方を直しました。 - 変更の理由:
- 不具合:「変更前」に書いたとおり、ワーカーの寿命を持つpeerが、リクエストのプールやconnection poolのメモリを指し、stream側ではGCが移動しうるmrubyの文字列を指しました。そのため、後でupstreamを使うと、解放済みのメモリを読みました。
- 前の挙動を残せなかった理由:peerは、それを設定したリクエストや接続より長く生きるので、それらのプールへのポインタを持てません。名前と宛先は、peerと同じだけ生きる必要があるので、ワーカーの寿命を持つストアにコピーします。
- ドキュメントが示していた挙動:ドキュメントに載った使い方は、
mruby_rewrite_handler_codeでサーバーを設定し、同じリクエストでproxy_passします。server=を呼ばない後続のリクエストが有効なpeerを読むことや、設定したリクエストが終わった後にNginx::Upstream#serverを読むと有効なメモリが返ることは、書いてありませんでした。
- 影響の範囲:
Nginx::Upstream#server=(HTTP)かNginx::Stream::Connection#upstream_server=(stream)を使う設定です。 - 必要な対応:対応は要りません。
- このリリースで変わらない挙動:upstreamを使うリクエストや接続ごとにサーバーを設定する使い方は、これまでどおり動きます。読み戻す値は、設定した値です。
- このリリースで変わらない挙動:共有メモリの
zoneを持つupstreamは、すべてのワーカーが共有する共有メモリにpeerを置きます。そのため、peerをどれか1つのワーカーのメモリに向けることは、この修正のワーカーごとのストアでも、旧コードのリクエストのプールでも、ワーカーをまたいで不正です。このリリースは、zoneを使わない場合を正します。zoneを持つupstreamは、名前とsockaddrをzoneのslabに置く必要があり、本リリースの範囲外です。ここは旧コードのほうが悪く、前からある問題です。 - テスト:HTTPは
test/t/cases/upstream_server.rbのポート18139のテスト、streamはtest/t/cases/stream_upstream_server.rbのポート12364と12365のテストです。
Performance
Measured with the callgrind comparison (test/perf/compare.sh) against the
tag v2.7.1, 20000 requests per scenario on Ubuntu 22.04 aarch64. Every
scenario stays below the 3% at which the comparison warns; the largest change
is sleep at +1.78% and auth at +1.53%. The security fixes touch code off the request hot path
(the value copy in Nginx::Var#set, a single r->header_only check, and the
server= setter, which no benchmark scenario calls), so they add no
measurable per-request work.
Upgrading
Supported nginx versions: the nginx mainline and stable lines; CI builds nginx
1.31.6, 1.30.5, 1.28.3 and 1.26.3. See "Upgrading" in the notes for the
per-entry "What to do".
Full release notes
The complete, per-entry notes are in the repository:
docs/releases/v2.7.2.md
(English) and
docs/releases/v2.7.2.ja.md
(Japanese).