Whenever `gdImageGifAnimAddPtr()` calls `gdImageGifAnimAddCtx()` and
the latter fails, we must not call `gdDPExtractData()`; otherwise a
double-free would occur. Since `gdImageGifAnimAddCtx` is a void
function, and we can't change that for BC reasons, we're introducing
a static helper which is used internally.
Whenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we
must not call `gdDPExtractData()`; otherwise a double-free would
happen. Since `gdImage*Ctx()` are void functions, and we can't change
that for BC reasons, we're introducing static helpers which are used
internally.
We're adding a regression test for `gdImageJpegPtr()`, but not for
`gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to
trigger failure of the respective `gdImage*Ctx()` calls.
This potential security issue has been reported by Solmaz Salimi (aka.
Rooney).
The fix for PHP bug 43828[1] changed the algorithm from drawing filled
pies from drawing multiple triangles to drawing a single polygon. Due
to quirks of the filled polygon drawing algorithm, we had to filter out
extraneous vertices. This lead, however, to a bug regarding displaced
starting and ending points near 90° and 270° degrees, which we fix by
reinserting these vertices if they had been removed.
[1] <https://bugs.php.net/bug.php?id=43828>
After calculating the top crop amount, we bail out if the whole image
was going to be cropped away. The condition to check this
is off-by-one, though, since `y` would be equal to `height` in this
case. However, `y` would be equal to `height` also in case only the
last row of the image would have to be retained. We instead check for
`match` which indicates whether all pixels have the same color.
After calculating the bottom crop amount, we must never calculate the
`crop.height` based on the image height, since its irrelevant.
When calculating the left and right crop amount, we must not ignore the
last row of the image.
The partially identical implementation of `gdImageCropThreshold()` has
exactly the same issues, so we fix it as well.
Future scope for *improvements*:
- Replace the `match` flag with respective `goto`s (basically, `break
2`) is supposed to yield clearer code.
- Don't check the rows which will be top-cropped anyway, when
calculating the left and right crop amount, for efficiency.
- Join the implementations of calculating the crop rectangle of
`gdImageCropAuto()` and `gdImageCropThreshold()`.
CMake process of generating VS solution and projects fails, because libgd_static target is not visible at this point. This is a fix for this problem.
Fixes#467.
Git ident attributes were in most cases utilized with SVN and keywords
substitutions, where $Id$ were replaced with certain revision from the
repository. In Git this functionality is different. Each $Id$ needs to
be defined in .gitattributes file to be effective. This patch removes
unused and outdated attributes.
All the uses of strncpy in here are based on strlen of the input, so
there's no need to run through an str-based func again. Switch to a
straight memcpy. Plus this avoids static checkers that blindly choke
on strncpy. The code was already adding a trailing NUL byte, so that
isn't problematic either.
We've been tracking program deps in the build files, so it ends up
being redundant for a lot of our test/example programs. Clean them
up, and update some of the cmake/automake files as needed.
If the png error handle is triggered during output, the allocated
rows aren't freed. Change the allocation to calloc to zero out all
the rows, and then walk them in the jump callback to release them.
When reading images in GD or GD2 format, we have to ensure that the
transparent color is not set, if it would refer to a non-extant palette
entry.
We back that up with respective regression tests.
When using `gdImageCopy()` for image cropping, we have to make sure
that it doesn't use alpha blending (the current default), but rather
`gdEffectReplace`. We reset the `alphaBlendingFlag` after finishing
the copy operation.
Since getopt is only needed by various helper programs, we start a new
program utility static library to stuff things into so they don't fill
up the gd library itself.
This comes from NetBSD. Fixes#401.
Due to a signedness confusion in `GetCode_` a corrupt GIF file can
trigger an infinite loop. Furthermore we make sure that a GIF without
any palette entries is treated as invalid *after* open palette entries
have been removed.
CVE-2018-5711
See also https://bugs.php.net/bug.php?id=75571.
oss-fuzz pointed out:
gd_gd2.c:456:10: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
We must not allow chunk sizes (aka. lengths) of INT_MAX, since we need
to alloc size+1 bytes.
oss-fuzz pointed out:
gd_bmp.c:641:18: runtime error: negation of -2147483648 cannot be represented in type 'int';
cast to an unsigned type to negate this value to itself
This is a bit of a false positive issue as -2147483648 is -2147483648
with gcc/clang which we check for later on. But lets check for it up
front to avoid the undefined behavior.
For OS/2 BMP 1.0 files, the spec says only 1/4/8/24 bit images are
supported, so ignore other depths as invalid.
oss-fuzz pointed out:
gd_bmp.c:670:22: runtime error: shift exponent 12803 is too large for 32-bit type 'int'
oss-fuzz pointed out:
gd_gd2.c:441:11: runtime error: signed integer overflow: 65535 * 65535 cannot be represented in type 'int'
Add some checks on the inputs from the header file and which are used
later on in multiplication.
oss-fuzz pointed out:
gd_tga.c:209:52: runtime error: signed integer overflow: 838848000 * 3 cannot be represented in type 'int'
This is somewhat of a false positive as we already have overflow checks
after this assignment, but we can delay the code until afterwards to
avoid warnings.
oss-fuzz pointed out:
gd_gif_in.c:605:16: runtime error: index 5595 out of bounds for type 'int [4096]'
Add some bounds checking on each code that we read from the file.
oss-fuzz pointed out:
wbmp.c:48:14: runtime error: left shift of 253751679 by 7 places cannot be represented in type 'int'
See previous commit for more details.
oss-fuzz pointed out:
gd_io.c:174:10: runtime error: left shift of 255 by 24 places cannot be represented in type 'int'
See previous commit for more details.
oss-fuzz pointed out:
gd_io.c:139:14: runtime error: left shift of 199 by 24 places cannot be represented in type 'int'
Switch the temp var we use here to unsigned to avoid that. We do an
unsigned int to a signed int at the end which is undefined, but since
compilers don't seem to mind that, we won't care just yet. It also
makes the code match gdGetIntLSB behavior.
The palette headers always consist of 256 palette entries, and if
`\377\377\377\377` is given for the transparency, that means that there
is no transparent color.
The issue is that `gdImagePngCtxEx` (which is called by `gdImagePngPtr`
and the other PNG output functions to do the real work) does not return
whether it succeeded or failed, so this is not checked in
`gdImagePngPtr` and the function wrongly assumes everything is okay,
which is not, in this case, because the palette image contains no
palette entries.
We can't change the signature of `gdImagePngCtxEx` for API
compatibility reasons, so we introduce the static helper
`_gdImagePngCtxEx` which returns success respective failure, so
`gdImagePngPtr` and `gdImagePngPtrEx` can check the return value. We
leave it solely to libpng for now to report warnings regarding the
failing write.
CVE-2017-6362
We have to make sure to avoid alpha-blending issues by explicitly
switching to `gdEffectReplace` and to restore the old value afterwards.
We also document the algorithm used by `gdImageGrayScale()` and note
its limitations regarding palette images.
We have to initialize `trans_col` to the value that guards the call to
`gdImageColorTransparent()`. To avoid confusion, we replace the magic
numbers with a macro.
Although libgd is not really affected by this issue, because contrary
to PHP's bundled libgd it does not allow to read from negative offsets,
we consider it still a bug that `dynamicSeek()` does not behave like
`fileSeek()` with regard to negative positions.
As this behavior cannot be probed from outside, we omit the regression
test.
The stack allocated color map buffers were not zeroed before usage, and
so undefined palette indexes could cause information leakage.
This issue has been reported by Matviy Kotoniy to security@libgd.org in
<CAKm_7a-AO++B6cXYWM_DtycPENG5WNWK7NSEvQ5OmZziMY_JyA@mail.gmail.com>.
The following API functions now accept the font names and the text to be
printed as `const char*` rater than `char*`. This makes the functions
much more `C++` friendly.
gdImageStringFT();
gdImageStringTTF();
gdImageStringFTEx();
Other functions/types affected:
typeed struct fontkey_t;
any2eucjp();
gdTcl_UtfToUniChar();
DetectKanjiCode();
do_convert();
do_check_and_conv();
If the reading of GD2 images fails due to a truncated file, we have to
make sure that all resources are freed. We do so by going to `fail`
instead of bailing out early.
This is a minor issue, though, as GD2 isn't recommended for production
use at all.
Due to #82 the optimized support for reading 1 bps TIFF files (black &
white) had been disabled. Tony Lew already pointed out a fix in #88.
Furthermore, there was the following missing and improper error handling:
* TIFFReadScanline() returns -1 on error, not 0
* the result of TIFFReadTile() hasn't been checked
* in case of failure of these functions, the error had not been
propagated
We fix this, and re-enable direct support for 1 bps TIFFs, which is
more memory efficient than the general RGBA support. We also make sure
not to hit any not yet implemented code path.
GD2 stores the number of horizontal and vertical chunks as words (i.e. 2
byte unsigned). These values are multiplied and assigned to an int when
reading the image, what can cause integer overflows. We have to avoid
that, and also make sure that either chunk count is actually greater
than zero. If illegal chunk counts are detected, we bail out from
reading the image.
gdImageCreate() doesn't check for oversized images and as such is prone
to DoS vulnerabilities. We fix that by applying the same overflow check
that is already in place for gdImageCreateTrueColor().
CVE-2016-9317
It is possible to craft TGA files which will overflow the decompression
buffer, but not the image's bitmap. Therefore we also have to check for
potential decompression buffer overflows.
This issue had been reported by Ibrahim El-Sayed to security@libgd.org;
a modified case exposing an off-by-one error of the first patch had been
provided by Konrad Beckmann.
This commit is an amendment to commit fb0e0cce, so we use CVE-2016-6906
as well.
No need to decrease `u`, so we don't do it. While we're at it, we also factor
out the overflow check of the loop, what improves performance and readability.
This issue has been reported by Stefan Esser to security@libgd.org.
The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and
the other WebP output functions to do the real work) does not return whether
it succeeded or failed, so this is not checked in gdImageWebpPtr() and the
function wrongly assumes everything is okay, which is not, in this case,
because there is a size limitation for WebP, namely that the width and
height must by less than 16383.
We can't change the signature of gdImageWebpCtx() for API compatibility
reasons, so we introduce the static helper _gdImageWebpCtx() which returns
success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can
check the return value. We leave it solely to libwebp for now to report
warnings regarding the failing write.
This issue had been reported by Ibrahim El-Sayed to security@libgd.org.
CVE-2016-6912
tiff_invalid_read.tiff is corrupt, and causes an invalid read in
gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit
is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case,
dynamicGetbuf() is called with a negative dp->pos, but also positive buffer
overflows have to be handled, in which case 0 has to be returned (cf. commit
75e29a9).
Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create
the image, because the return value of TIFFReadRGBAImage() is not checked.
We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails.
This issue had been reported by Ibrahim El-Sayed to security@libgd.org.
CVE-2016-6911
It is possible to craft TGA files which will overflow the decompression
buffer, but not the image's bitmap. Therefore we augment the check for the
bitmap's overflow with a check for the buffer's overflow.
This issue had been reported by Ibrahim El-Sayed to security@libgd.org.
CVE-2016-6906
libgd clients need to be able to distinguish between fatal and
"extremely fatal" libjpeg and libpng errors, because in the former case
execution can proceed, but in the latter case libgd calls exit().
Therefore we report fatal errors as GD_WARNING.
Pull out the library versioning info out of configure and into a common
script that both cmake & autotools can run. This way we have a single
source of truth for the versioning info.
The buffer underflow happens at the start of the bitstream and after
each clear code, where the wrap-around is actually unnecessary. To
avoid the buffer underflow we simply initialize scd->last_byte to 2,
instead of adding further control logic to skip the relevant
assignments altogether.
We do not add a regression test, because the buffer underflow could
only be detected with ASAN or a similar memory-checker (or debugging),
and it happens for all proper GIFs anyway, so other tests (such as
tests/gif/gif_im2im) already exhibited the behavior.
We're passing `pixel1` as default color to `getPixelOverflow*()` for
pixels which may be outside the valid bounds. `pixel1` is supposed to
be always valid due to the fixed arithmetic's round towards zero
behavior.
Lossless WebP is a rather interesting alternative to PNG, and already
supported by `gdImageCreateFromWebp*()`, so we add support for
`gdImageWebp*()`, too.
We can stick with the existing API, using the quality parameter to
request lossless encoding if it is set to `gdWebpLossless`, which we
define to `PHP_INT` (to avoid adding a new dependency to gd.h, we hard-
code the value – we're assuming `sizeof(int)==4` anyway).
Before we copy the quantized palette image onto the original image, we have
to mark the latter as palette image. We also have to free the allocated
truecolor pixels; free_truecolor_image_data() does all that for us.
This is obviously a relict of PHP's bundled libgd, which we should remove.
And actually, the #ifdef isn't necessary anymore for PHP's bundled libgd
either, because it supports gdImageAlphaBlending().
We remove the special casing for "point" rectangles with thick!=1 altogether,
and restrict the special casing for "line" rectangles to thick==1. We move
this necessary special casing (it fixes issue #172) towards the bottom of the
function like it is in PHP's bundled libgd.
Integer overflow can be happened in expression gdImageSX(im) * 4 *
gdImageSY(im). It could lead to heap buffer overflow in the following
code. This issue has been reported to the PHP Bug Tracking System. The
proof-of-concept file will be supplied some days later. This issue was
discovered by Ke Liu of Tencent's Xuanwu LAB.
gdImageTrueColorToPalette() is sometimes wasteful by putting multiple white
color entries into the palette. This is caused by an obvious typo, where
to avoid a division by zero when `total` is zero, `count` is checked instead
of `total`.
We fix this issue, to improve the quality of the color quantization.
If fontconfig support is disabled, the static functions font_pattern() and
useFontConfig() are never used. This can lead to build errors, and does so
with the current default settings `-Wall -Werror`. Therefore we ensure that
these functions are not compiled when they are not needed.
This makes the code better readable in the sources, and we get syntax
highlighting in the generated HTML wherever we want it (i.e. not necessarily
always as with `-hl all`).
We make it work only, for now. Actually, it doesn't make sense that
`oTga::bitmap` is an `int *` as we're storing only bytes there. If this
will be changed, we can even get rid of the `conversion_buffer` in
`read_image_tga` altogether, and read the image data into the
`decompression_buffer` (if RLE'd) or the `tga->bitmap` (if uncompressed)
directly.
In file included from gdft.c:20:0:
entities.h:17:4: error: 'entities' defined but not used [-Werror=unused-variable]
gdft.c:1741:15: error: 'font_path' defined but not used [-Werror=unused-function]
static char * font_path(char **fontpath, char *name_list)
That happens only when RLE is applied. The culprit is in compress_row(),
where the rightmost pixels which wouldn't be run-length encoded were
ignored; instead we now add them uncompressed to the `row`.
That happens only when RLE is applied. The culprit is in compress_row(),
where the rightmost pixels which wouldn't be run-length encoded were
ignored; instead we now add them uncompressed to the `row`.
The cmake build was missing gd_color_match.c which meant the library
didn't export the gdImageColorMatch function. Sync the two lists in
the autotools and cmake files to make this easier to check. Listing
header files in autotools source lists isn't a problem.
This makes sure we don't export symbols in libgd.so that we shouldn't.
We now assume that, if you're using gcc, you're using at least version
3.3 as that's the first to support the visibility attribute. We can
wait to see if anyone complains before worrying about older ones.
The standard behavior in distros nowadays is to build shared libs and
omit static libs. Split the build knobs in cmake to support this. It
also matches what's available with the autotools build.
We fix the unintended sign extension issue #150385 by declaring encoded_pixels
as int, and the logical vs. bitwise operator issue #150382 by using the
proper operator.
Otherwise we get artifacts regarding transparency. That happens with the
current implementation of gdImageFilledArc() unless gdChord or gdNoFill
are set. When gdPie is set, however, the filled arc is drawn in wedges,
which are polygons of three points, and so some overlap is natural.
To resolve the issue, we stick with the current algorithm of calculating the
wedges, but instead of drawing each polygon separately, we put the *relevant*
points in a large array, and draw a single polygon. That also is supposed to
improve the performance considerably.
Note that this modification will change the results when gdImageSetStyle()
or gdImageSetBrush() are used, but we believe that this modification is
also an improvement in this regard, even though it still might not make much
sense to use these functions with gdImageFilledArc().
Currently gd_error() forwards to gd_error_ex(). However, both functions
accept a variable number of arguments, and simply forwarding the va_list
isn't portable, see <http://c-faq.com/varargs/handoff.html>. This article
also describes the usual workaround, namely to let the second function
accept a va_list instead of variable number of arguments.
We do so by introducing a static helper, what does not affect API/ABI
compatibility.
This pull request (based on Asma's works) adds support for languages that require [complex text
layout](https://en.wikipedia.org/wiki/Complex_text_layout).
We are using [libraqm](https://github.com/HOST-Oman/libraqm), a small source
code-only library that wraps FriBidi (for bidirectional text support) and
HarfBuzz (for text shaping), and does proper BiDi and script itemization.
The CTL support is enabled by default but can be disabled at compiling time,
and we provide a fallback function that uses your original code without CTL
support.