idx
int64 | project
string | commit_id
string | project_url
string | commit_url
string | commit_message
string | target
int64 | func
string | func_hash
string | file_name
string | file_hash
string | cwe
string | cve
string | cve_desc
string | nvd_url
string |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
206,043
|
gimp
|
c57f9dcf1934a9ab0cd67650f2dea18cb0902270
|
https://github.com/GNOME/gimp
|
https://git.gnome.org/browse/gimp/commit/?id=c57f9dcf1934a9ab0cd67650f2dea18cb0902270
|
Bug 790784 - (CVE-2017-17784) heap overread in gbr parser / load_image.
We were assuming the input name was well formed, hence was
nul-terminated. As any data coming from external input, this has to be
thorougly checked.
Similar to commit 06d24a79af94837d615d0024916bb95a01bf3c59 but adapted
to older gimp-2-8 code.
| 1
|
load_image (const gchar *filename,
GError **error)
{
gchar *name;
gint fd;
BrushHeader bh;
guchar *brush_buf = NULL;
gint32 image_ID;
gint32 layer_ID;
GimpParasite *parasite;
GimpDrawable *drawable;
GimpPixelRgn pixel_rgn;
gint bn_size;
GimpImageBaseType base_type;
GimpImageType image_type;
gsize size;
fd = g_open (filename, O_RDONLY | _O_BINARY, 0);
if (fd == -1)
{
g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),
_("Could not open '%s' for reading: %s"),
gimp_filename_to_utf8 (filename), g_strerror (errno));
return -1;
}
gimp_progress_init_printf (_("Opening '%s'"),
gimp_filename_to_utf8 (filename));
if (read (fd, &bh, sizeof (BrushHeader)) != sizeof (BrushHeader))
{
close (fd);
return -1;
}
/* rearrange the bytes in each unsigned int */
bh.header_size = g_ntohl (bh.header_size);
bh.version = g_ntohl (bh.version);
bh.width = g_ntohl (bh.width);
bh.height = g_ntohl (bh.height);
bh.bytes = g_ntohl (bh.bytes);
bh.magic_number = g_ntohl (bh.magic_number);
bh.spacing = g_ntohl (bh.spacing);
/* Sanitize values */
if ((bh.width == 0) || (bh.width > GIMP_MAX_IMAGE_SIZE) ||
(bh.height == 0) || (bh.height > GIMP_MAX_IMAGE_SIZE) ||
((bh.bytes != 1) && (bh.bytes != 2) && (bh.bytes != 4) &&
(bh.bytes != 18)) ||
(G_MAXSIZE / bh.width / bh.height / bh.bytes < 1))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Invalid header data in '%s': width=%lu, height=%lu, "
"bytes=%lu"), gimp_filename_to_utf8 (filename),
(unsigned long int)bh.width, (unsigned long int)bh.height,
(unsigned long int)bh.bytes);
return -1;
}
switch (bh.version)
{
case 1:
/* Version 1 didn't have a magic number and had no spacing */
bh.spacing = 25;
/* And we need to rewind the handle, 4 due spacing and 4 due magic */
lseek (fd, -8, SEEK_CUR);
bh.header_size += 8;
break;
case 3: /* cinepaint brush */
if (bh.bytes == 18 /* FLOAT16_GRAY_GIMAGE */)
{
bh.bytes = 2;
}
else
{
g_message (_("Unsupported brush format"));
close (fd);
return -1;
}
/* fallthrough */
case 2:
if (bh.magic_number == GBRUSH_MAGIC &&
bh.header_size > sizeof (BrushHeader))
break;
default:
g_message (_("Unsupported brush format"));
close (fd);
return -1;
}
if ((bn_size = (bh.header_size - sizeof (BrushHeader))) > 0)
{
gchar *temp = g_new (gchar, bn_size);
if ((read (fd, temp, bn_size)) < bn_size)
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Error in GIMP brush file '%s'"),
gimp_filename_to_utf8 (filename));
close (fd);
g_free (temp);
return -1;
}
name = gimp_any_to_utf8 (temp, -1,
_("Invalid UTF-8 string in brush file '%s'."),
gimp_filename_to_utf8 (filename));
g_free (temp);
}
else
{
name = g_strdup (_("Unnamed"));
}
/* Now there's just raw data left. */
size = bh.width * bh.height * bh.bytes;
brush_buf = g_malloc (size);
if (read (fd, brush_buf, size) != size)
{
close (fd);
g_free (brush_buf);
g_free (name);
return -1;
}
switch (bh.bytes)
{
case 1:
{
PatternHeader ph;
/* For backwards-compatibility, check if a pattern follows.
The obsolete .gpb format did it this way. */
if (read (fd, &ph, sizeof (PatternHeader)) == sizeof(PatternHeader))
{
/* rearrange the bytes in each unsigned int */
ph.header_size = g_ntohl (ph.header_size);
ph.version = g_ntohl (ph.version);
ph.width = g_ntohl (ph.width);
ph.height = g_ntohl (ph.height);
ph.bytes = g_ntohl (ph.bytes);
ph.magic_number = g_ntohl (ph.magic_number);
if (ph.magic_number == GPATTERN_MAGIC &&
ph.version == 1 &&
ph.header_size > sizeof (PatternHeader) &&
ph.bytes == 3 &&
ph.width == bh.width &&
ph.height == bh.height &&
lseek (fd, ph.header_size - sizeof (PatternHeader),
SEEK_CUR) > 0)
{
guchar *plain_brush = brush_buf;
gint i;
bh.bytes = 4;
brush_buf = g_malloc (4 * bh.width * bh.height);
for (i = 0; i < ph.width * ph.height; i++)
{
if (read (fd, brush_buf + i * 4, 3) != 3)
{
close (fd);
g_free (name);
g_free (plain_brush);
g_free (brush_buf);
return -1;
}
brush_buf[i * 4 + 3] = plain_brush[i];
}
g_free (plain_brush);
}
}
}
break;
case 2:
{
guint16 *buf = (guint16 *) brush_buf;
gint i;
for (i = 0; i < bh.width * bh.height; i++, buf++)
{
union
{
guint16 u[2];
gfloat f;
} short_float;
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
short_float.u[0] = 0;
short_float.u[1] = GUINT16_FROM_BE (*buf);
#else
short_float.u[0] = GUINT16_FROM_BE (*buf);
short_float.u[1] = 0;
#endif
brush_buf[i] = (guchar) (short_float.f * 255.0 + 0.5);
}
bh.bytes = 1;
}
break;
default:
break;
}
/*
* Create a new image of the proper size and
* associate the filename with it.
*/
switch (bh.bytes)
{
case 1:
base_type = GIMP_GRAY;
image_type = GIMP_GRAY_IMAGE;
break;
case 4:
base_type = GIMP_RGB;
image_type = GIMP_RGBA_IMAGE;
break;
default:
g_message ("Unsupported brush depth: %d\n"
"GIMP Brushes must be GRAY or RGBA\n",
bh.bytes);
g_free (name);
return -1;
}
image_ID = gimp_image_new (bh.width, bh.height, base_type);
gimp_image_set_filename (image_ID, filename);
parasite = gimp_parasite_new ("gimp-brush-name",
GIMP_PARASITE_PERSISTENT,
strlen (name) + 1, name);
gimp_image_attach_parasite (image_ID, parasite);
gimp_parasite_free (parasite);
layer_ID = gimp_layer_new (image_ID, name, bh.width, bh.height,
image_type, 100, GIMP_NORMAL_MODE);
gimp_image_insert_layer (image_ID, layer_ID, -1, 0);
g_free (name);
drawable = gimp_drawable_get (layer_ID);
gimp_pixel_rgn_init (&pixel_rgn, drawable,
0, 0, drawable->width, drawable->height,
TRUE, FALSE);
gimp_pixel_rgn_set_rect (&pixel_rgn, brush_buf,
0, 0, bh.width, bh.height);
g_free (brush_buf);
if (image_type == GIMP_GRAY_IMAGE)
gimp_invert (layer_ID);
close (fd);
gimp_drawable_flush (drawable);
gimp_progress_update (1.0);
return image_ID;
}
|
219487381392289910094593757172224969152
|
file-gbr.c
|
210537502330856952427982223109888523462
|
CWE-125
|
CVE-2017-17784
|
In GIMP 2.8.22, there is a heap-based buffer over-read in load_image in plug-ins/common/file-gbr.c in the gbr import parser, related to mishandling of UTF-8 data.
|
https://nvd.nist.gov/vuln/detail/CVE-2017-17784
|
376,678
|
gimp
|
c57f9dcf1934a9ab0cd67650f2dea18cb0902270
|
https://github.com/GNOME/gimp
|
https://git.gnome.org/browse/gimp/commit/?id=c57f9dcf1934a9ab0cd67650f2dea18cb0902270
|
Bug 790784 - (CVE-2017-17784) heap overread in gbr parser / load_image.
We were assuming the input name was well formed, hence was
nul-terminated. As any data coming from external input, this has to be
thorougly checked.
Similar to commit 06d24a79af94837d615d0024916bb95a01bf3c59 but adapted
to older gimp-2-8 code.
| 0
|
load_image (const gchar *filename,
GError **error)
{
gchar *name;
gint fd;
BrushHeader bh;
guchar *brush_buf = NULL;
gint32 image_ID;
gint32 layer_ID;
GimpParasite *parasite;
GimpDrawable *drawable;
GimpPixelRgn pixel_rgn;
gint bn_size;
GimpImageBaseType base_type;
GimpImageType image_type;
gsize size;
fd = g_open (filename, O_RDONLY | _O_BINARY, 0);
if (fd == -1)
{
g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),
_("Could not open '%s' for reading: %s"),
gimp_filename_to_utf8 (filename), g_strerror (errno));
return -1;
}
gimp_progress_init_printf (_("Opening '%s'"),
gimp_filename_to_utf8 (filename));
if (read (fd, &bh, sizeof (BrushHeader)) != sizeof (BrushHeader))
{
close (fd);
return -1;
}
/* rearrange the bytes in each unsigned int */
bh.header_size = g_ntohl (bh.header_size);
bh.version = g_ntohl (bh.version);
bh.width = g_ntohl (bh.width);
bh.height = g_ntohl (bh.height);
bh.bytes = g_ntohl (bh.bytes);
bh.magic_number = g_ntohl (bh.magic_number);
bh.spacing = g_ntohl (bh.spacing);
/* Sanitize values */
if ((bh.width == 0) || (bh.width > GIMP_MAX_IMAGE_SIZE) ||
(bh.height == 0) || (bh.height > GIMP_MAX_IMAGE_SIZE) ||
((bh.bytes != 1) && (bh.bytes != 2) && (bh.bytes != 4) &&
(bh.bytes != 18)) ||
(G_MAXSIZE / bh.width / bh.height / bh.bytes < 1))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Invalid header data in '%s': width=%lu, height=%lu, "
"bytes=%lu"), gimp_filename_to_utf8 (filename),
(unsigned long int)bh.width, (unsigned long int)bh.height,
(unsigned long int)bh.bytes);
return -1;
}
switch (bh.version)
{
case 1:
/* Version 1 didn't have a magic number and had no spacing */
bh.spacing = 25;
/* And we need to rewind the handle, 4 due spacing and 4 due magic */
lseek (fd, -8, SEEK_CUR);
bh.header_size += 8;
break;
case 3: /* cinepaint brush */
if (bh.bytes == 18 /* FLOAT16_GRAY_GIMAGE */)
{
bh.bytes = 2;
}
else
{
g_message (_("Unsupported brush format"));
close (fd);
return -1;
}
/* fallthrough */
case 2:
if (bh.magic_number == GBRUSH_MAGIC &&
bh.header_size > sizeof (BrushHeader))
break;
default:
g_message (_("Unsupported brush format"));
close (fd);
return -1;
}
if ((bn_size = (bh.header_size - sizeof (BrushHeader))) > 0)
{
gchar *temp = g_new (gchar, bn_size);
if ((read (fd, temp, bn_size)) < bn_size ||
temp[bn_size - 1] != '\0')
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Error in GIMP brush file '%s'"),
gimp_filename_to_utf8 (filename));
close (fd);
g_free (temp);
return -1;
}
name = gimp_any_to_utf8 (temp, -1,
_("Invalid UTF-8 string in brush file '%s'."),
gimp_filename_to_utf8 (filename));
g_free (temp);
}
else
{
name = g_strdup (_("Unnamed"));
}
/* Now there's just raw data left. */
size = bh.width * bh.height * bh.bytes;
brush_buf = g_malloc (size);
if (read (fd, brush_buf, size) != size)
{
close (fd);
g_free (brush_buf);
g_free (name);
return -1;
}
switch (bh.bytes)
{
case 1:
{
PatternHeader ph;
/* For backwards-compatibility, check if a pattern follows.
The obsolete .gpb format did it this way. */
if (read (fd, &ph, sizeof (PatternHeader)) == sizeof(PatternHeader))
{
/* rearrange the bytes in each unsigned int */
ph.header_size = g_ntohl (ph.header_size);
ph.version = g_ntohl (ph.version);
ph.width = g_ntohl (ph.width);
ph.height = g_ntohl (ph.height);
ph.bytes = g_ntohl (ph.bytes);
ph.magic_number = g_ntohl (ph.magic_number);
if (ph.magic_number == GPATTERN_MAGIC &&
ph.version == 1 &&
ph.header_size > sizeof (PatternHeader) &&
ph.bytes == 3 &&
ph.width == bh.width &&
ph.height == bh.height &&
lseek (fd, ph.header_size - sizeof (PatternHeader),
SEEK_CUR) > 0)
{
guchar *plain_brush = brush_buf;
gint i;
bh.bytes = 4;
brush_buf = g_malloc (4 * bh.width * bh.height);
for (i = 0; i < ph.width * ph.height; i++)
{
if (read (fd, brush_buf + i * 4, 3) != 3)
{
close (fd);
g_free (name);
g_free (plain_brush);
g_free (brush_buf);
return -1;
}
brush_buf[i * 4 + 3] = plain_brush[i];
}
g_free (plain_brush);
}
}
}
break;
case 2:
{
guint16 *buf = (guint16 *) brush_buf;
gint i;
for (i = 0; i < bh.width * bh.height; i++, buf++)
{
union
{
guint16 u[2];
gfloat f;
} short_float;
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
short_float.u[0] = 0;
short_float.u[1] = GUINT16_FROM_BE (*buf);
#else
short_float.u[0] = GUINT16_FROM_BE (*buf);
short_float.u[1] = 0;
#endif
brush_buf[i] = (guchar) (short_float.f * 255.0 + 0.5);
}
bh.bytes = 1;
}
break;
default:
break;
}
/*
* Create a new image of the proper size and
* associate the filename with it.
*/
switch (bh.bytes)
{
case 1:
base_type = GIMP_GRAY;
image_type = GIMP_GRAY_IMAGE;
break;
case 4:
base_type = GIMP_RGB;
image_type = GIMP_RGBA_IMAGE;
break;
default:
g_message ("Unsupported brush depth: %d\n"
"GIMP Brushes must be GRAY or RGBA\n",
bh.bytes);
g_free (name);
return -1;
}
image_ID = gimp_image_new (bh.width, bh.height, base_type);
gimp_image_set_filename (image_ID, filename);
parasite = gimp_parasite_new ("gimp-brush-name",
GIMP_PARASITE_PERSISTENT,
strlen (name) + 1, name);
gimp_image_attach_parasite (image_ID, parasite);
gimp_parasite_free (parasite);
layer_ID = gimp_layer_new (image_ID, name, bh.width, bh.height,
image_type, 100, GIMP_NORMAL_MODE);
gimp_image_insert_layer (image_ID, layer_ID, -1, 0);
g_free (name);
drawable = gimp_drawable_get (layer_ID);
gimp_pixel_rgn_init (&pixel_rgn, drawable,
0, 0, drawable->width, drawable->height,
TRUE, FALSE);
gimp_pixel_rgn_set_rect (&pixel_rgn, brush_buf,
0, 0, bh.width, bh.height);
g_free (brush_buf);
if (image_type == GIMP_GRAY_IMAGE)
gimp_invert (layer_ID);
close (fd);
gimp_drawable_flush (drawable);
gimp_progress_update (1.0);
return image_ID;
}
|
269327823766609487068724383051357537961
|
file-gbr.c
|
146644042188037261041231342134151379601
|
CWE-125
|
CVE-2017-17784
|
In GIMP 2.8.22, there is a heap-based buffer over-read in load_image in plug-ins/common/file-gbr.c in the gbr import parser, related to mishandling of UTF-8 data.
|
https://nvd.nist.gov/vuln/detail/CVE-2017-17784
|
206,044
|
tigervnc
|
d61a767d6842b530ffb532ddd5a3d233119aad40
|
https://github.com/CendioOssman/tigervnc
|
https://github.com/CendioOssman/tigervnc/commit/d61a767d6842b530ffb532ddd5a3d233119aad40
|
Make ZlibInStream more robust against failures
Move the checks around to avoid missing cases where we might access
memory that is no longer valid. Also avoid touching the underlying
stream implicitly (e.g. via the destructor) as it might also no
longer be valid.
A malicious server could theoretically use this for remote code
execution in the client.
Issue found by Pavel Cheremushkin from Kaspersky Lab
| 1
|
void ZRLE_DECODE (const Rect& r, rdr::InStream* is,
rdr::ZlibInStream* zis,
const PixelFormat& pf, ModifiablePixelBuffer* pb)
{
int length = is->readU32();
zis->setUnderlying(is, length);
Rect t;
PIXEL_T buf[64 * 64];
for (t.tl.y = r.tl.y; t.tl.y < r.br.y; t.tl.y += 64) {
t.br.y = __rfbmin(r.br.y, t.tl.y + 64);
for (t.tl.x = r.tl.x; t.tl.x < r.br.x; t.tl.x += 64) {
t.br.x = __rfbmin(r.br.x, t.tl.x + 64);
int mode = zis->readU8();
bool rle = mode & 128;
int palSize = mode & 127;
PIXEL_T palette[128];
for (int i = 0; i < palSize; i++) {
palette[i] = READ_PIXEL(zis);
}
if (palSize == 1) {
PIXEL_T pix = palette[0];
pb->fillRect(pf, t, &pix);
continue;
}
if (!rle) {
if (palSize == 0) {
// raw
#ifdef CPIXEL
for (PIXEL_T* ptr = buf; ptr < buf+t.area(); ptr++) {
*ptr = READ_PIXEL(zis);
}
#else
zis->readBytes(buf, t.area() * (BPP / 8));
#endif
} else {
// packed pixels
int bppp = ((palSize > 16) ? 8 :
((palSize > 4) ? 4 : ((palSize > 2) ? 2 : 1)));
PIXEL_T* ptr = buf;
for (int i = 0; i < t.height(); i++) {
PIXEL_T* eol = ptr + t.width();
rdr::U8 byte = 0;
rdr::U8 nbits = 0;
while (ptr < eol) {
if (nbits == 0) {
byte = zis->readU8();
nbits = 8;
}
nbits -= bppp;
rdr::U8 index = (byte >> nbits) & ((1 << bppp) - 1) & 127;
*ptr++ = palette[index];
}
}
}
} else {
if (palSize == 0) {
// plain RLE
PIXEL_T* ptr = buf;
PIXEL_T* end = ptr + t.area();
while (ptr < end) {
PIXEL_T pix = READ_PIXEL(zis);
int len = 1;
int b;
do {
b = zis->readU8();
len += b;
} while (b == 255);
if (end - ptr < len) {
throw Exception ("ZRLE decode error");
}
while (len-- > 0) *ptr++ = pix;
}
} else {
// palette RLE
PIXEL_T* ptr = buf;
PIXEL_T* end = ptr + t.area();
while (ptr < end) {
int index = zis->readU8();
int len = 1;
if (index & 128) {
int b;
do {
b = zis->readU8();
len += b;
} while (b == 255);
if (end - ptr < len) {
throw Exception ("ZRLE decode error");
}
}
index &= 127;
PIXEL_T pix = palette[index];
while (len-- > 0) *ptr++ = pix;
}
}
}
pb->imageRect(pf, t, buf);
}
}
zis->removeUnderlying();
}
|
266797184622822909427515310440359797331
|
None
|
CWE-672
|
CVE-2019-15691
|
TigerVNC version prior to 1.10.1 is vulnerable to stack use-after-return, which occurs due to incorrect usage of stack memory in ZRLEDecoder. If decoding routine would throw an exception, ZRLEDecoder may try to access stack variable, which has been already freed during the process of stack unwinding. Exploitation of this vulnerability could potentially result into remote code execution. This attack appear to be exploitable via network connectivity.
|
https://nvd.nist.gov/vuln/detail/CVE-2019-15691
|
|
376,682
|
tigervnc
|
d61a767d6842b530ffb532ddd5a3d233119aad40
|
https://github.com/CendioOssman/tigervnc
|
https://github.com/CendioOssman/tigervnc/commit/d61a767d6842b530ffb532ddd5a3d233119aad40
|
Make ZlibInStream more robust against failures
Move the checks around to avoid missing cases where we might access
memory that is no longer valid. Also avoid touching the underlying
stream implicitly (e.g. via the destructor) as it might also no
longer be valid.
A malicious server could theoretically use this for remote code
execution in the client.
Issue found by Pavel Cheremushkin from Kaspersky Lab
| 0
|
void ZRLE_DECODE (const Rect& r, rdr::InStream* is,
rdr::ZlibInStream* zis,
const PixelFormat& pf, ModifiablePixelBuffer* pb)
{
int length = is->readU32();
zis->setUnderlying(is, length);
Rect t;
PIXEL_T buf[64 * 64];
for (t.tl.y = r.tl.y; t.tl.y < r.br.y; t.tl.y += 64) {
t.br.y = __rfbmin(r.br.y, t.tl.y + 64);
for (t.tl.x = r.tl.x; t.tl.x < r.br.x; t.tl.x += 64) {
t.br.x = __rfbmin(r.br.x, t.tl.x + 64);
int mode = zis->readU8();
bool rle = mode & 128;
int palSize = mode & 127;
PIXEL_T palette[128];
for (int i = 0; i < palSize; i++) {
palette[i] = READ_PIXEL(zis);
}
if (palSize == 1) {
PIXEL_T pix = palette[0];
pb->fillRect(pf, t, &pix);
continue;
}
if (!rle) {
if (palSize == 0) {
// raw
#ifdef CPIXEL
for (PIXEL_T* ptr = buf; ptr < buf+t.area(); ptr++) {
*ptr = READ_PIXEL(zis);
}
#else
zis->readBytes(buf, t.area() * (BPP / 8));
#endif
} else {
// packed pixels
int bppp = ((palSize > 16) ? 8 :
((palSize > 4) ? 4 : ((palSize > 2) ? 2 : 1)));
PIXEL_T* ptr = buf;
for (int i = 0; i < t.height(); i++) {
PIXEL_T* eol = ptr + t.width();
rdr::U8 byte = 0;
rdr::U8 nbits = 0;
while (ptr < eol) {
if (nbits == 0) {
byte = zis->readU8();
nbits = 8;
}
nbits -= bppp;
rdr::U8 index = (byte >> nbits) & ((1 << bppp) - 1) & 127;
*ptr++ = palette[index];
}
}
}
} else {
if (palSize == 0) {
// plain RLE
PIXEL_T* ptr = buf;
PIXEL_T* end = ptr + t.area();
while (ptr < end) {
PIXEL_T pix = READ_PIXEL(zis);
int len = 1;
int b;
do {
b = zis->readU8();
len += b;
} while (b == 255);
if (end - ptr < len) {
throw Exception ("ZRLE decode error");
}
while (len-- > 0) *ptr++ = pix;
}
} else {
// palette RLE
PIXEL_T* ptr = buf;
PIXEL_T* end = ptr + t.area();
while (ptr < end) {
int index = zis->readU8();
int len = 1;
if (index & 128) {
int b;
do {
b = zis->readU8();
len += b;
} while (b == 255);
if (end - ptr < len) {
throw Exception ("ZRLE decode error");
}
}
index &= 127;
PIXEL_T pix = palette[index];
while (len-- > 0) *ptr++ = pix;
}
}
}
pb->imageRect(pf, t, buf);
}
}
zis->flushUnderlying();
zis->setUnderlying(NULL, 0);
}
|
147406355021092564490243997240144808169
|
None
|
CWE-672
|
CVE-2019-15691
|
TigerVNC version prior to 1.10.1 is vulnerable to stack use-after-return, which occurs due to incorrect usage of stack memory in ZRLEDecoder. If decoding routine would throw an exception, ZRLEDecoder may try to access stack variable, which has been already freed during the process of stack unwinding. Exploitation of this vulnerability could potentially result into remote code execution. This attack appear to be exploitable via network connectivity.
|
https://nvd.nist.gov/vuln/detail/CVE-2019-15691
|
|
206,262
|
vim
|
c6fdb15d423df22e1776844811d082322475e48a
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/c6fdb15d423df22e1776844811d082322475e48a
|
patch 9.0.0025: accessing beyond allocated memory with the cmdline window
Problem: Accessing beyond allocated memory when using the cmdline window in
Ex mode.
Solution: Use "*" instead of "'<,'>" for Visual mode.
| 1
|
parse_command_modifiers(
exarg_T *eap,
char **errormsg,
cmdmod_T *cmod,
int skip_only)
{
char_u *orig_cmd = eap->cmd;
char_u *cmd_start = NULL;
int use_plus_cmd = FALSE;
int starts_with_colon = FALSE;
int vim9script = in_vim9script();
int has_visual_range = FALSE;
CLEAR_POINTER(cmod);
cmod->cmod_flags = sticky_cmdmod_flags;
if (STRNCMP(eap->cmd, "'<,'>", 5) == 0)
{
// The automatically inserted Visual area range is skipped, so that
// typing ":cmdmod cmd" in Visual mode works without having to move the
// range to after the modififiers. The command will be
// "'<,'>cmdmod cmd", parse "cmdmod cmd" and then put back "'<,'>"
// before "cmd" below.
eap->cmd += 5;
cmd_start = eap->cmd;
has_visual_range = TRUE;
}
// Repeat until no more command modifiers are found.
for (;;)
{
char_u *p;
while (*eap->cmd == ' ' || *eap->cmd == '\t' || *eap->cmd == ':')
{
if (*eap->cmd == ':')
starts_with_colon = TRUE;
++eap->cmd;
}
// in ex mode, an empty command (after modifiers) works like :+
if (*eap->cmd == NUL && exmode_active
&& (getline_equal(eap->getline, eap->cookie, getexmodeline)
|| getline_equal(eap->getline, eap->cookie, getexline))
&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
{
use_plus_cmd = TRUE;
if (!skip_only)
ex_pressedreturn = TRUE;
break; // no modifiers following
}
// ignore comment and empty lines
if (comment_start(eap->cmd, starts_with_colon))
{
// a comment ends at a NL
if (eap->nextcmd == NULL)
{
eap->nextcmd = vim_strchr(eap->cmd, '\n');
if (eap->nextcmd != NULL)
++eap->nextcmd;
}
if (vim9script && has_cmdmod(cmod, FALSE))
*errormsg = _(e_command_modifier_without_command);
return FAIL;
}
if (*eap->cmd == NUL)
{
if (!skip_only)
{
ex_pressedreturn = TRUE;
if (vim9script && has_cmdmod(cmod, FALSE))
*errormsg = _(e_command_modifier_without_command);
}
return FAIL;
}
p = skip_range(eap->cmd, TRUE, NULL);
// In Vim9 script a variable can shadow a command modifier:
// verbose = 123
// verbose += 123
// silent! verbose = func()
// verbose.member = 2
// verbose[expr] = 2
// But not:
// verbose [a, b] = list
if (vim9script)
{
char_u *s, *n;
for (s = eap->cmd; ASCII_ISALPHA(*s); ++s)
;
n = skipwhite(s);
if (*n == '.' || *n == '=' || (*n != NUL && n[1] == '=')
|| *s == '[')
break;
}
switch (*p)
{
// When adding an entry, also modify cmd_exists().
case 'a': if (!checkforcmd_noparen(&eap->cmd, "aboveleft", 3))
break;
cmod->cmod_split |= WSP_ABOVE;
continue;
case 'b': if (checkforcmd_noparen(&eap->cmd, "belowright", 3))
{
cmod->cmod_split |= WSP_BELOW;
continue;
}
if (checkforcmd_opt(&eap->cmd, "browse", 3, TRUE))
{
#ifdef FEAT_BROWSE_CMD
cmod->cmod_flags |= CMOD_BROWSE;
#endif
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "botright", 2))
break;
cmod->cmod_split |= WSP_BOT;
continue;
case 'c': if (!checkforcmd_opt(&eap->cmd, "confirm", 4, TRUE))
break;
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
cmod->cmod_flags |= CMOD_CONFIRM;
#endif
continue;
case 'k': if (checkforcmd_noparen(&eap->cmd, "keepmarks", 3))
{
cmod->cmod_flags |= CMOD_KEEPMARKS;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "keepalt", 5))
{
cmod->cmod_flags |= CMOD_KEEPALT;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "keeppatterns", 5))
{
cmod->cmod_flags |= CMOD_KEEPPATTERNS;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "keepjumps", 5))
break;
cmod->cmod_flags |= CMOD_KEEPJUMPS;
continue;
case 'f': // only accept ":filter {pat} cmd"
{
char_u *reg_pat;
char_u *nulp = NULL;
int c = 0;
if (!checkforcmd_noparen(&p, "filter", 4)
|| *p == NUL
|| (ends_excmd(*p)
#ifdef FEAT_EVAL
// in ":filter #pat# cmd" # does not
// start a comment
&& (!vim9script || VIM_ISWHITE(p[1]))
#endif
))
break;
if (*p == '!')
{
cmod->cmod_filter_force = TRUE;
p = skipwhite(p + 1);
if (*p == NUL || ends_excmd(*p))
break;
}
#ifdef FEAT_EVAL
// Avoid that "filter(arg)" is recognized.
if (vim9script && !VIM_ISWHITE(p[-1]))
break;
#endif
if (skip_only)
p = skip_vimgrep_pat(p, NULL, NULL);
else
// NOTE: This puts a NUL after the pattern.
p = skip_vimgrep_pat_ext(p, ®_pat, NULL,
&nulp, &c);
if (p == NULL || *p == NUL)
break;
if (!skip_only)
{
cmod->cmod_filter_regmatch.regprog =
vim_regcomp(reg_pat, RE_MAGIC);
if (cmod->cmod_filter_regmatch.regprog == NULL)
break;
// restore the character overwritten by NUL
if (nulp != NULL)
*nulp = c;
}
eap->cmd = p;
continue;
}
// ":hide" and ":hide | cmd" are not modifiers
case 'h': if (p != eap->cmd || !checkforcmd_noparen(&p, "hide", 3)
|| *p == NUL || ends_excmd(*p))
break;
eap->cmd = p;
cmod->cmod_flags |= CMOD_HIDE;
continue;
case 'l': if (checkforcmd_noparen(&eap->cmd, "lockmarks", 3))
{
cmod->cmod_flags |= CMOD_LOCKMARKS;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "legacy", 3))
{
if (ends_excmd2(p, eap->cmd))
{
*errormsg =
_(e_legacy_must_be_followed_by_command);
return FAIL;
}
cmod->cmod_flags |= CMOD_LEGACY;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "leftabove", 5))
break;
cmod->cmod_split |= WSP_ABOVE;
continue;
case 'n': if (checkforcmd_noparen(&eap->cmd, "noautocmd", 3))
{
cmod->cmod_flags |= CMOD_NOAUTOCMD;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "noswapfile", 3))
break;
cmod->cmod_flags |= CMOD_NOSWAPFILE;
continue;
case 'r': if (!checkforcmd_noparen(&eap->cmd, "rightbelow", 6))
break;
cmod->cmod_split |= WSP_BELOW;
continue;
case 's': if (checkforcmd_noparen(&eap->cmd, "sandbox", 3))
{
cmod->cmod_flags |= CMOD_SANDBOX;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "silent", 3))
break;
cmod->cmod_flags |= CMOD_SILENT;
if (*eap->cmd == '!' && !VIM_ISWHITE(eap->cmd[-1]))
{
// ":silent!", but not "silent !cmd"
eap->cmd = skipwhite(eap->cmd + 1);
cmod->cmod_flags |= CMOD_ERRSILENT;
}
continue;
case 't': if (checkforcmd_noparen(&p, "tab", 3))
{
if (!skip_only)
{
long tabnr = get_address(eap, &eap->cmd,
ADDR_TABS, eap->skip,
skip_only, FALSE, 1);
if (tabnr == MAXLNUM)
cmod->cmod_tab = tabpage_index(curtab) + 1;
else
{
if (tabnr < 0 || tabnr > LAST_TAB_NR)
{
*errormsg = _(e_invalid_range);
return FAIL;
}
cmod->cmod_tab = tabnr + 1;
}
}
eap->cmd = p;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "topleft", 2))
break;
cmod->cmod_split |= WSP_TOP;
continue;
case 'u': if (!checkforcmd_noparen(&eap->cmd, "unsilent", 3))
break;
cmod->cmod_flags |= CMOD_UNSILENT;
continue;
case 'v': if (checkforcmd_noparen(&eap->cmd, "vertical", 4))
{
cmod->cmod_split |= WSP_VERT;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "vim9cmd", 4))
{
if (ends_excmd2(p, eap->cmd))
{
*errormsg =
_(e_vim9cmd_must_be_followed_by_command);
return FAIL;
}
cmod->cmod_flags |= CMOD_VIM9CMD;
continue;
}
if (!checkforcmd_noparen(&p, "verbose", 4))
break;
if (vim_isdigit(*eap->cmd))
{
// zero means not set, one is verbose == 0, etc.
cmod->cmod_verbose = atoi((char *)eap->cmd) + 1;
}
else
cmod->cmod_verbose = 2; // default: verbose == 1
eap->cmd = p;
continue;
}
break;
}
if (has_visual_range)
{
if (eap->cmd > cmd_start)
{
// Move the '<,'> range to after the modifiers and insert a colon.
// Since the modifiers have been parsed put the colon on top of the
// space: "'<,'>mod cmd" -> "mod:'<,'>cmd
// Put eap->cmd after the colon.
if (use_plus_cmd)
{
size_t len = STRLEN(cmd_start);
// Special case: empty command uses "+":
// "'<,'>mods" -> "mods'<,'>+
mch_memmove(orig_cmd, cmd_start, len);
STRCPY(orig_cmd + len, "'<,'>+");
}
else
{
mch_memmove(cmd_start - 5, cmd_start, eap->cmd - cmd_start);
eap->cmd -= 5;
mch_memmove(eap->cmd - 1, ":'<,'>", 6);
}
}
else
// No modifiers, move the pointer back.
// Special case: change empty command to "+".
if (use_plus_cmd)
eap->cmd = (char_u *)"'<,'>+";
else
eap->cmd = orig_cmd;
}
else if (use_plus_cmd)
eap->cmd = (char_u *)"+";
return OK;
}
|
61928994098668347793112269457604758897
|
ex_docmd.c
|
287878878694425028301990758845576774946
|
CWE-787
|
CVE-2022-2288
|
Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2288
|
379,334
|
vim
|
c6fdb15d423df22e1776844811d082322475e48a
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/c6fdb15d423df22e1776844811d082322475e48a
|
patch 9.0.0025: accessing beyond allocated memory with the cmdline window
Problem: Accessing beyond allocated memory when using the cmdline window in
Ex mode.
Solution: Use "*" instead of "'<,'>" for Visual mode.
| 0
|
parse_command_modifiers(
exarg_T *eap,
char **errormsg,
cmdmod_T *cmod,
int skip_only)
{
char_u *orig_cmd = eap->cmd;
char_u *cmd_start = NULL;
int use_plus_cmd = FALSE;
int starts_with_colon = FALSE;
int vim9script = in_vim9script();
int has_visual_range = FALSE;
CLEAR_POINTER(cmod);
cmod->cmod_flags = sticky_cmdmod_flags;
if (STRNCMP(eap->cmd, "'<,'>", 5) == 0)
{
// The automatically inserted Visual area range is skipped, so that
// typing ":cmdmod cmd" in Visual mode works without having to move the
// range to after the modififiers. The command will be
// "'<,'>cmdmod cmd", parse "cmdmod cmd" and then put back "'<,'>"
// before "cmd" below.
eap->cmd += 5;
cmd_start = eap->cmd;
has_visual_range = TRUE;
}
// Repeat until no more command modifiers are found.
for (;;)
{
char_u *p;
while (*eap->cmd == ' ' || *eap->cmd == '\t' || *eap->cmd == ':')
{
if (*eap->cmd == ':')
starts_with_colon = TRUE;
++eap->cmd;
}
// in ex mode, an empty command (after modifiers) works like :+
if (*eap->cmd == NUL && exmode_active
&& (getline_equal(eap->getline, eap->cookie, getexmodeline)
|| getline_equal(eap->getline, eap->cookie, getexline))
&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
{
use_plus_cmd = TRUE;
if (!skip_only)
ex_pressedreturn = TRUE;
break; // no modifiers following
}
// ignore comment and empty lines
if (comment_start(eap->cmd, starts_with_colon))
{
// a comment ends at a NL
if (eap->nextcmd == NULL)
{
eap->nextcmd = vim_strchr(eap->cmd, '\n');
if (eap->nextcmd != NULL)
++eap->nextcmd;
}
if (vim9script && has_cmdmod(cmod, FALSE))
*errormsg = _(e_command_modifier_without_command);
return FAIL;
}
if (*eap->cmd == NUL)
{
if (!skip_only)
{
ex_pressedreturn = TRUE;
if (vim9script && has_cmdmod(cmod, FALSE))
*errormsg = _(e_command_modifier_without_command);
}
return FAIL;
}
p = skip_range(eap->cmd, TRUE, NULL);
// In Vim9 script a variable can shadow a command modifier:
// verbose = 123
// verbose += 123
// silent! verbose = func()
// verbose.member = 2
// verbose[expr] = 2
// But not:
// verbose [a, b] = list
if (vim9script)
{
char_u *s, *n;
for (s = eap->cmd; ASCII_ISALPHA(*s); ++s)
;
n = skipwhite(s);
if (*n == '.' || *n == '=' || (*n != NUL && n[1] == '=')
|| *s == '[')
break;
}
switch (*p)
{
// When adding an entry, also modify cmd_exists().
case 'a': if (!checkforcmd_noparen(&eap->cmd, "aboveleft", 3))
break;
cmod->cmod_split |= WSP_ABOVE;
continue;
case 'b': if (checkforcmd_noparen(&eap->cmd, "belowright", 3))
{
cmod->cmod_split |= WSP_BELOW;
continue;
}
if (checkforcmd_opt(&eap->cmd, "browse", 3, TRUE))
{
#ifdef FEAT_BROWSE_CMD
cmod->cmod_flags |= CMOD_BROWSE;
#endif
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "botright", 2))
break;
cmod->cmod_split |= WSP_BOT;
continue;
case 'c': if (!checkforcmd_opt(&eap->cmd, "confirm", 4, TRUE))
break;
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
cmod->cmod_flags |= CMOD_CONFIRM;
#endif
continue;
case 'k': if (checkforcmd_noparen(&eap->cmd, "keepmarks", 3))
{
cmod->cmod_flags |= CMOD_KEEPMARKS;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "keepalt", 5))
{
cmod->cmod_flags |= CMOD_KEEPALT;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "keeppatterns", 5))
{
cmod->cmod_flags |= CMOD_KEEPPATTERNS;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "keepjumps", 5))
break;
cmod->cmod_flags |= CMOD_KEEPJUMPS;
continue;
case 'f': // only accept ":filter {pat} cmd"
{
char_u *reg_pat;
char_u *nulp = NULL;
int c = 0;
if (!checkforcmd_noparen(&p, "filter", 4)
|| *p == NUL
|| (ends_excmd(*p)
#ifdef FEAT_EVAL
// in ":filter #pat# cmd" # does not
// start a comment
&& (!vim9script || VIM_ISWHITE(p[1]))
#endif
))
break;
if (*p == '!')
{
cmod->cmod_filter_force = TRUE;
p = skipwhite(p + 1);
if (*p == NUL || ends_excmd(*p))
break;
}
#ifdef FEAT_EVAL
// Avoid that "filter(arg)" is recognized.
if (vim9script && !VIM_ISWHITE(p[-1]))
break;
#endif
if (skip_only)
p = skip_vimgrep_pat(p, NULL, NULL);
else
// NOTE: This puts a NUL after the pattern.
p = skip_vimgrep_pat_ext(p, ®_pat, NULL,
&nulp, &c);
if (p == NULL || *p == NUL)
break;
if (!skip_only)
{
cmod->cmod_filter_regmatch.regprog =
vim_regcomp(reg_pat, RE_MAGIC);
if (cmod->cmod_filter_regmatch.regprog == NULL)
break;
// restore the character overwritten by NUL
if (nulp != NULL)
*nulp = c;
}
eap->cmd = p;
continue;
}
// ":hide" and ":hide | cmd" are not modifiers
case 'h': if (p != eap->cmd || !checkforcmd_noparen(&p, "hide", 3)
|| *p == NUL || ends_excmd(*p))
break;
eap->cmd = p;
cmod->cmod_flags |= CMOD_HIDE;
continue;
case 'l': if (checkforcmd_noparen(&eap->cmd, "lockmarks", 3))
{
cmod->cmod_flags |= CMOD_LOCKMARKS;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "legacy", 3))
{
if (ends_excmd2(p, eap->cmd))
{
*errormsg =
_(e_legacy_must_be_followed_by_command);
return FAIL;
}
cmod->cmod_flags |= CMOD_LEGACY;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "leftabove", 5))
break;
cmod->cmod_split |= WSP_ABOVE;
continue;
case 'n': if (checkforcmd_noparen(&eap->cmd, "noautocmd", 3))
{
cmod->cmod_flags |= CMOD_NOAUTOCMD;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "noswapfile", 3))
break;
cmod->cmod_flags |= CMOD_NOSWAPFILE;
continue;
case 'r': if (!checkforcmd_noparen(&eap->cmd, "rightbelow", 6))
break;
cmod->cmod_split |= WSP_BELOW;
continue;
case 's': if (checkforcmd_noparen(&eap->cmd, "sandbox", 3))
{
cmod->cmod_flags |= CMOD_SANDBOX;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "silent", 3))
break;
cmod->cmod_flags |= CMOD_SILENT;
if (*eap->cmd == '!' && !VIM_ISWHITE(eap->cmd[-1]))
{
// ":silent!", but not "silent !cmd"
eap->cmd = skipwhite(eap->cmd + 1);
cmod->cmod_flags |= CMOD_ERRSILENT;
}
continue;
case 't': if (checkforcmd_noparen(&p, "tab", 3))
{
if (!skip_only)
{
long tabnr = get_address(eap, &eap->cmd,
ADDR_TABS, eap->skip,
skip_only, FALSE, 1);
if (tabnr == MAXLNUM)
cmod->cmod_tab = tabpage_index(curtab) + 1;
else
{
if (tabnr < 0 || tabnr > LAST_TAB_NR)
{
*errormsg = _(e_invalid_range);
return FAIL;
}
cmod->cmod_tab = tabnr + 1;
}
}
eap->cmd = p;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "topleft", 2))
break;
cmod->cmod_split |= WSP_TOP;
continue;
case 'u': if (!checkforcmd_noparen(&eap->cmd, "unsilent", 3))
break;
cmod->cmod_flags |= CMOD_UNSILENT;
continue;
case 'v': if (checkforcmd_noparen(&eap->cmd, "vertical", 4))
{
cmod->cmod_split |= WSP_VERT;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "vim9cmd", 4))
{
if (ends_excmd2(p, eap->cmd))
{
*errormsg =
_(e_vim9cmd_must_be_followed_by_command);
return FAIL;
}
cmod->cmod_flags |= CMOD_VIM9CMD;
continue;
}
if (!checkforcmd_noparen(&p, "verbose", 4))
break;
if (vim_isdigit(*eap->cmd))
{
// zero means not set, one is verbose == 0, etc.
cmod->cmod_verbose = atoi((char *)eap->cmd) + 1;
}
else
cmod->cmod_verbose = 2; // default: verbose == 1
eap->cmd = p;
continue;
}
break;
}
if (has_visual_range)
{
if (eap->cmd > cmd_start)
{
// Move the '<,'> range to after the modifiers and insert a colon.
// Since the modifiers have been parsed put the colon on top of the
// space: "'<,'>mod cmd" -> "mod:'<,'>cmd
// Put eap->cmd after the colon.
if (use_plus_cmd)
{
size_t len = STRLEN(cmd_start);
// Special case: empty command uses "+":
// "'<,'>mods" -> "mods *+
// Use "*" instead of "'<,'>" to avoid the command getting
// longer, in case is was allocated.
mch_memmove(orig_cmd, cmd_start, len);
STRCPY(orig_cmd + len, " *+");
}
else
{
mch_memmove(cmd_start - 5, cmd_start, eap->cmd - cmd_start);
eap->cmd -= 5;
mch_memmove(eap->cmd - 1, ":'<,'>", 6);
}
}
else
// No modifiers, move the pointer back.
// Special case: change empty command to "+".
if (use_plus_cmd)
eap->cmd = (char_u *)"'<,'>+";
else
eap->cmd = orig_cmd;
}
else if (use_plus_cmd)
eap->cmd = (char_u *)"+";
return OK;
}
|
128847198820720658441664267481456465295
|
ex_docmd.c
|
80050062526332961104670632599823980115
|
CWE-787
|
CVE-2022-2288
|
Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2288
|
206,273
|
radare2
|
a7ce29647fcb38386d7439696375e16e093d6acb
|
https://github.com/radare/radare2
|
https://github.com/radareorg/radare2/commit/a7ce29647fcb38386d7439696375e16e093d6acb
|
Fix UAF in aaaa on arm/thumb switching ##crash
* Reported by @peacock-doris via huntr.dev
* Reproducer tests_65185
* This is a logic fix, but not the fully safe as changes in the code
can result on UAF again, to properly protect r2 from crashing we
need to break the ABI and add refcounting to RRegItem, which can't
happen in 5.6.x because of abi-compat rules
| 1
|
static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char *reg, const char *sign, char type) {
st64 ptr = 0;
char *addr, *esil_buf = NULL;
const st64 maxstackframe = 1024 * 8;
r_return_if_fail (anal && fcn && op && reg);
size_t i;
for (i = 0; i < R_ARRAY_SIZE (op->src); i++) {
if (op->src[i] && op->src[i]->reg && op->src[i]->reg->name) {
if (!strcmp (reg, op->src[i]->reg->name)) {
st64 delta = op->src[i]->delta;
if ((delta > 0 && *sign == '+') || (delta < 0 && *sign == '-')) {
ptr = R_ABS (op->src[i]->delta);
break;
}
}
}
}
if (!ptr) {
const char *op_esil = r_strbuf_get (&op->esil);
if (!op_esil) {
return;
}
esil_buf = strdup (op_esil);
if (!esil_buf) {
return;
}
r_strf_var (esilexpr, 64, ",%s,%s,", reg, sign);
char *ptr_end = strstr (esil_buf, esilexpr);
if (!ptr_end) {
free (esil_buf);
return;
}
*ptr_end = 0;
addr = ptr_end;
while ((addr[0] != '0' || addr[1] != 'x') && addr >= esil_buf + 1 && *addr != ',') {
addr--;
}
if (strncmp (addr, "0x", 2)) {
//XXX: This is a workaround for inconsistent esil
if (!op->stackop && op->dst) {
const char *sp = r_reg_get_name (anal->reg, R_REG_NAME_SP);
const char *bp = r_reg_get_name (anal->reg, R_REG_NAME_BP);
const char *rn = op->dst->reg ? op->dst->reg->name : NULL;
if (rn && ((bp && !strcmp (bp, rn)) || (sp && !strcmp (sp, rn)))) {
if (anal->verbose) {
eprintf ("Warning: Analysis didn't fill op->stackop for instruction that alters stack at 0x%" PFMT64x ".\n", op->addr);
}
goto beach;
}
}
if (*addr == ',') {
addr++;
}
if (!op->stackop && op->type != R_ANAL_OP_TYPE_PUSH && op->type != R_ANAL_OP_TYPE_POP
&& op->type != R_ANAL_OP_TYPE_RET && r_str_isnumber (addr)) {
ptr = (st64)r_num_get (NULL, addr);
if (ptr && op->src[0] && ptr == op->src[0]->imm) {
goto beach;
}
} else if ((op->stackop == R_ANAL_STACK_SET) || (op->stackop == R_ANAL_STACK_GET)) {
if (op->ptr % 4) {
goto beach;
}
ptr = R_ABS (op->ptr);
} else {
goto beach;
}
} else {
ptr = (st64)r_num_get (NULL, addr);
}
}
if (anal->verbose && (!op->src[0] || !op->dst)) {
eprintf ("Warning: Analysis didn't fill op->src/dst at 0x%" PFMT64x ".\n", op->addr);
}
int rw = (op->direction == R_ANAL_OP_DIR_WRITE) ? R_ANAL_VAR_ACCESS_TYPE_WRITE : R_ANAL_VAR_ACCESS_TYPE_READ;
if (*sign == '+') {
const bool isarg = type == R_ANAL_VAR_KIND_SPV ? ptr >= fcn->stack : ptr >= fcn->bp_off;
const char *pfx = isarg ? ARGPREFIX : VARPREFIX;
st64 frame_off;
if (type == R_ANAL_VAR_KIND_SPV) {
frame_off = ptr - fcn->stack;
} else {
frame_off = ptr - fcn->bp_off;
}
if (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {
goto beach;
}
RAnalVar *var = get_stack_var (fcn, frame_off);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, ptr);
goto beach;
}
char *varname = NULL, *vartype = NULL;
if (isarg) {
const char *place = fcn->cc ? r_anal_cc_arg (anal, fcn->cc, ST32_MAX) : NULL;
bool stack_rev = place ? !strcmp (place, "stack_rev") : false;
char *fname = r_type_func_guess (anal->sdb_types, fcn->name);
if (fname) {
ut64 sum_sz = 0;
size_t from, to, i;
if (stack_rev) {
const size_t cnt = r_type_func_args_count (anal->sdb_types, fname);
from = cnt ? cnt - 1 : cnt;
to = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;
} else {
from = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;
to = r_type_func_args_count (anal->sdb_types, fname);
}
const int bytes = (fcn->bits ? fcn->bits : anal->bits) / 8;
for (i = from; stack_rev ? i >= to : i < to; stack_rev ? i-- : i++) {
char *tp = r_type_func_args_type (anal->sdb_types, fname, i);
if (!tp) {
break;
}
if (sum_sz == frame_off) {
vartype = tp;
varname = strdup (r_type_func_args_name (anal->sdb_types, fname, i));
break;
}
ut64 bit_sz = r_type_get_bitsize (anal->sdb_types, tp);
sum_sz += bit_sz ? bit_sz / 8 : bytes;
sum_sz = R_ROUND (sum_sz, bytes);
free (tp);
}
free (fname);
}
}
if (!varname) {
if (anal->opt.varname_stack) {
varname = r_str_newf ("%s_%" PFMT64x "h", pfx, R_ABS (frame_off));
} else {
varname = r_anal_function_autoname_var (fcn, type, pfx, ptr);
}
}
if (varname) {
#if 0
if (isarg && frame_off > 48) {
free (varname);
goto beach;
}
#endif
RAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, vartype, anal->bits / 8, isarg, varname);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, ptr);
}
free (varname);
}
free (vartype);
} else {
st64 frame_off = -(ptr + fcn->bp_off);
if (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {
goto beach;
}
RAnalVar *var = get_stack_var (fcn, frame_off);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, -ptr);
goto beach;
}
char *varname = anal->opt.varname_stack
? r_str_newf ("%s_%" PFMT64x "h", VARPREFIX, R_ABS (frame_off))
: r_anal_function_autoname_var (fcn, type, VARPREFIX, -ptr);
if (varname) {
RAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, NULL, anal->bits / 8, false, varname);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, -ptr);
}
free (varname);
}
}
beach:
free (esil_buf);
}
|
336184840247355587470651192558617642560
|
None
|
CWE-416
|
CVE-2022-1031
|
Use After Free in op_is_set_bp in GitHub repository radareorg/radare2 prior to 5.6.6.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-1031
|
|
379,671
|
radare2
|
a7ce29647fcb38386d7439696375e16e093d6acb
|
https://github.com/radare/radare2
|
https://github.com/radareorg/radare2/commit/a7ce29647fcb38386d7439696375e16e093d6acb
|
Fix UAF in aaaa on arm/thumb switching ##crash
* Reported by @peacock-doris via huntr.dev
* Reproducer tests_65185
* This is a logic fix, but not the fully safe as changes in the code
can result on UAF again, to properly protect r2 from crashing we
need to break the ABI and add refcounting to RRegItem, which can't
happen in 5.6.x because of abi-compat rules
| 0
|
static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char *reg, const char *sign, char type) {
st64 ptr = 0;
char *addr, *esil_buf = NULL;
const st64 maxstackframe = 1024 * 8;
r_return_if_fail (anal && fcn && op && reg);
size_t i;
for (i = 0; i < R_ARRAY_SIZE (op->src); i++) {
if (op->src[i] && op->src[i]->reg && op->src[i]->reg->name) {
if (!strcmp (reg, op->src[i]->reg->name)) {
st64 delta = op->src[i]->delta;
if ((delta > 0 && *sign == '+') || (delta < 0 && *sign == '-')) {
ptr = R_ABS (op->src[i]->delta);
break;
}
}
}
}
if (!ptr) {
const char *op_esil = r_strbuf_get (&op->esil);
if (!op_esil) {
return;
}
esil_buf = strdup (op_esil);
if (!esil_buf) {
return;
}
r_strf_var (esilexpr, 64, ",%s,%s,", reg, sign);
char *ptr_end = strstr (esil_buf, esilexpr);
if (!ptr_end) {
free (esil_buf);
return;
}
*ptr_end = 0;
addr = ptr_end;
while ((addr[0] != '0' || addr[1] != 'x') && addr >= esil_buf + 1 && *addr != ',') {
addr--;
}
if (strncmp (addr, "0x", 2)) {
//XXX: This is a workaround for inconsistent esil
if (!op->stackop && op->dst) {
const char *sp = r_reg_get_name (anal->reg, R_REG_NAME_SP);
const char *bp = r_reg_get_name (anal->reg, R_REG_NAME_BP);
const char *rn = op->dst->reg ? op->dst->reg->name : NULL;
if (rn && ((bp && !strcmp (bp, rn)) || (sp && !strcmp (sp, rn)))) {
if (anal->verbose) {
eprintf ("Warning: Analysis didn't fill op->stackop for instruction that alters stack at 0x%" PFMT64x ".\n", op->addr);
}
goto beach;
}
}
if (*addr == ',') {
addr++;
}
if (!op->stackop && op->type != R_ANAL_OP_TYPE_PUSH && op->type != R_ANAL_OP_TYPE_POP
&& op->type != R_ANAL_OP_TYPE_RET && r_str_isnumber (addr)) {
ptr = (st64)r_num_get (NULL, addr);
if (ptr && op->src[0] && ptr == op->src[0]->imm) {
goto beach;
}
} else if ((op->stackop == R_ANAL_STACK_SET) || (op->stackop == R_ANAL_STACK_GET)) {
if (op->ptr % 4) {
goto beach;
}
ptr = R_ABS (op->ptr);
} else {
goto beach;
}
} else {
ptr = (st64)r_num_get (NULL, addr);
}
}
if (anal->verbose && (!op->src[0] || !op->dst)) {
eprintf ("Warning: Analysis didn't fill op->src/dst at 0x%" PFMT64x ".\n", op->addr);
}
int rw = (op->direction == R_ANAL_OP_DIR_WRITE) ? R_ANAL_VAR_ACCESS_TYPE_WRITE : R_ANAL_VAR_ACCESS_TYPE_READ;
if (*sign == '+') {
const bool isarg = type == R_ANAL_VAR_KIND_SPV ? ptr >= fcn->stack : ptr >= fcn->bp_off;
const char *pfx = isarg ? ARGPREFIX : VARPREFIX;
st64 frame_off;
if (type == R_ANAL_VAR_KIND_SPV) {
frame_off = ptr - fcn->stack;
} else {
frame_off = ptr - fcn->bp_off;
}
if (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {
goto beach;
}
RAnalVar *var = get_stack_var (fcn, frame_off);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, ptr);
goto beach;
}
char *varname = NULL, *vartype = NULL;
if (isarg) {
const char *place = fcn->cc ? r_anal_cc_arg (anal, fcn->cc, ST32_MAX) : NULL;
bool stack_rev = place ? !strcmp (place, "stack_rev") : false;
char *fname = r_type_func_guess (anal->sdb_types, fcn->name);
if (fname) {
ut64 sum_sz = 0;
size_t from, to, i;
if (stack_rev) {
const size_t cnt = r_type_func_args_count (anal->sdb_types, fname);
from = cnt ? cnt - 1 : cnt;
to = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;
} else {
from = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;
to = r_type_func_args_count (anal->sdb_types, fname);
}
const int bytes = (fcn->bits ? fcn->bits : anal->bits) / 8;
for (i = from; stack_rev ? i >= to : i < to; stack_rev ? i-- : i++) {
char *tp = r_type_func_args_type (anal->sdb_types, fname, i);
if (!tp) {
break;
}
if (sum_sz == frame_off) {
vartype = tp;
varname = strdup (r_type_func_args_name (anal->sdb_types, fname, i));
break;
}
ut64 bit_sz = r_type_get_bitsize (anal->sdb_types, tp);
sum_sz += bit_sz ? bit_sz / 8 : bytes;
sum_sz = R_ROUND (sum_sz, bytes);
free (tp);
}
free (fname);
}
}
if (!varname) {
if (anal->opt.varname_stack) {
varname = r_str_newf ("%s_%" PFMT64x "h", pfx, R_ABS (frame_off));
} else {
varname = r_anal_function_autoname_var (fcn, type, pfx, ptr);
}
}
if (varname) {
#if 0
if (isarg && frame_off > 48) {
free (varname);
goto beach;
}
#endif
RAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, vartype, anal->bits / 8, isarg, varname);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, ptr);
}
free (varname);
}
free (vartype);
} else {
st64 frame_off = -(ptr + fcn->bp_off);
if (maxstackframe > 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {
goto beach;
}
RAnalVar *var = get_stack_var (fcn, frame_off);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, -ptr);
goto beach;
}
char *varname = anal->opt.varname_stack
? r_str_newf ("%s_%" PFMT64x "h", VARPREFIX, R_ABS (frame_off))
: r_anal_function_autoname_var (fcn, type, VARPREFIX, -ptr);
if (varname) {
RAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, NULL, anal->bits / 8, false, varname);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, -ptr);
}
free (varname);
}
}
beach:
free (esil_buf);
}
|
117008167646492270733743639992860727677
|
None
|
CWE-416
|
CVE-2022-1031
|
Use After Free in op_is_set_bp in GitHub repository radareorg/radare2 prior to 5.6.6.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-1031
|
|
206,417
|
vim
|
0971c7a4e537ea120a6bb2195960be8d0815e97b
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/0971c7a4e537ea120a6bb2195960be8d0815e97b
|
patch 8.2.5162: reading before the start of the line with BS in Replace mode
Problem: Reading before the start of the line with BS in Replace mode.
Solution: Check the cursor column is more than zero.
| 1
|
ins_bs(
int c,
int mode,
int *inserted_space_p)
{
linenr_T lnum;
int cc;
int temp = 0; // init for GCC
colnr_T save_col;
colnr_T mincol;
int did_backspace = FALSE;
int in_indent;
int oldState;
int cpc[MAX_MCO]; // composing characters
int call_fix_indent = FALSE;
/*
* can't delete anything in an empty file
* can't backup past first character in buffer
* can't backup past starting point unless 'backspace' > 1
* can backup to a previous line if 'backspace' == 0
*/
if ( BUFEMPTY()
|| (
#ifdef FEAT_RIGHTLEFT
!revins_on &&
#endif
((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
|| (!can_bs(BS_START)
&& ((arrow_used
#ifdef FEAT_JOB_CHANNEL
&& !bt_prompt(curbuf)
#endif
) || (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col <= Insstart_orig.col)))
|| (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
&& curwin->w_cursor.col <= ai_col)
|| (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
{
vim_beep(BO_BS);
return FALSE;
}
if (stop_arrow() == FAIL)
return FALSE;
in_indent = inindent(0);
if (in_indent)
can_cindent = FALSE;
end_comment_pending = NUL; // After BS, don't auto-end comment
#ifdef FEAT_RIGHTLEFT
if (revins_on) // put cursor after last inserted char
inc_cursor();
#endif
// Virtualedit:
// BACKSPACE_CHAR eats a virtual space
// BACKSPACE_WORD eats all coladd
// BACKSPACE_LINE eats all coladd and keeps going
if (curwin->w_cursor.coladd > 0)
{
if (mode == BACKSPACE_CHAR)
{
--curwin->w_cursor.coladd;
return TRUE;
}
if (mode == BACKSPACE_WORD)
{
curwin->w_cursor.coladd = 0;
return TRUE;
}
curwin->w_cursor.coladd = 0;
}
/*
* Delete newline!
*/
if (curwin->w_cursor.col == 0)
{
lnum = Insstart.lnum;
if (curwin->w_cursor.lnum == lnum
#ifdef FEAT_RIGHTLEFT
|| revins_on
#endif
)
{
if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
(linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
return FALSE;
--Insstart.lnum;
Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum));
}
/*
* In replace mode:
* cc < 0: NL was inserted, delete it
* cc >= 0: NL was replaced, put original characters back
*/
cc = -1;
if (State & REPLACE_FLAG)
cc = replace_pop(); // returns -1 if NL was inserted
/*
* In replace mode, in the line we started replacing, we only move the
* cursor.
*/
if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
{
dec_cursor();
}
else
{
if (!(State & VREPLACE_FLAG)
|| curwin->w_cursor.lnum > orig_line_count)
{
temp = gchar_cursor(); // remember current char
--curwin->w_cursor.lnum;
// When "aw" is in 'formatoptions' we must delete the space at
// the end of the line, otherwise the line will be broken
// again when auto-formatting.
if (has_format_option(FO_AUTO)
&& has_format_option(FO_WHITE_PAR))
{
char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
TRUE);
int len;
len = (int)STRLEN(ptr);
if (len > 0 && ptr[len - 1] == ' ')
ptr[len - 1] = NUL;
}
(void)do_join(2, FALSE, FALSE, FALSE, FALSE);
if (temp == NUL && gchar_cursor() != NUL)
inc_cursor();
}
else
dec_cursor();
/*
* In MODE_REPLACE mode we have to put back the text that was
* replaced by the NL. On the replace stack is first a
* NUL-terminated sequence of characters that were deleted and then
* the characters that NL replaced.
*/
if (State & REPLACE_FLAG)
{
/*
* Do the next ins_char() in MODE_NORMAL state, to
* prevent ins_char() from replacing characters and
* avoiding showmatch().
*/
oldState = State;
State = MODE_NORMAL;
/*
* restore characters (blanks) deleted after cursor
*/
while (cc > 0)
{
save_col = curwin->w_cursor.col;
mb_replace_pop_ins(cc);
curwin->w_cursor.col = save_col;
cc = replace_pop();
}
// restore the characters that NL replaced
replace_pop_ins();
State = oldState;
}
}
did_ai = FALSE;
}
else
{
/*
* Delete character(s) before the cursor.
*/
#ifdef FEAT_RIGHTLEFT
if (revins_on) // put cursor on last inserted char
dec_cursor();
#endif
mincol = 0;
// keep indent
if (mode == BACKSPACE_LINE
&& (curbuf->b_p_ai || cindent_on())
#ifdef FEAT_RIGHTLEFT
&& !revins_on
#endif
)
{
save_col = curwin->w_cursor.col;
beginline(BL_WHITE);
if (curwin->w_cursor.col < save_col)
{
mincol = curwin->w_cursor.col;
// should now fix the indent to match with the previous line
call_fix_indent = TRUE;
}
curwin->w_cursor.col = save_col;
}
/*
* Handle deleting one 'shiftwidth' or 'softtabstop'.
*/
if ( mode == BACKSPACE_CHAR
&& ((p_sta && in_indent)
|| ((get_sts_value() != 0
#ifdef FEAT_VARTABS
|| tabstop_count(curbuf->b_p_vsts_array)
#endif
)
&& curwin->w_cursor.col > 0
&& (*(ml_get_cursor() - 1) == TAB
|| (*(ml_get_cursor() - 1) == ' '
&& (!*inserted_space_p
|| arrow_used))))))
{
int ts;
colnr_T vcol;
colnr_T want_vcol;
colnr_T start_vcol;
*inserted_space_p = FALSE;
// Compute the virtual column where we want to be. Since
// 'showbreak' may get in the way, need to get the last column of
// the previous character.
getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
start_vcol = vcol;
dec_cursor();
getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
inc_cursor();
#ifdef FEAT_VARTABS
if (p_sta && in_indent)
{
ts = (int)get_sw_value(curbuf);
want_vcol = (want_vcol / ts) * ts;
}
else
want_vcol = tabstop_start(want_vcol, get_sts_value(),
curbuf->b_p_vsts_array);
#else
if (p_sta && in_indent)
ts = (int)get_sw_value(curbuf);
else
ts = (int)get_sts_value();
want_vcol = (want_vcol / ts) * ts;
#endif
// delete characters until we are at or before want_vcol
while (vcol > want_vcol
&& (cc = *(ml_get_cursor() - 1), VIM_ISWHITE(cc)))
ins_bs_one(&vcol);
// insert extra spaces until we are at want_vcol
while (vcol < want_vcol)
{
// Remember the first char we inserted
if (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col < Insstart_orig.col)
Insstart_orig.col = curwin->w_cursor.col;
if (State & VREPLACE_FLAG)
ins_char(' ');
else
{
ins_str((char_u *)" ");
if ((State & REPLACE_FLAG))
replace_push(NUL);
}
getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
}
// If we are now back where we started delete one character. Can
// happen when using 'sts' and 'linebreak'.
if (vcol >= start_vcol)
ins_bs_one(&vcol);
}
/*
* Delete up to starting point, start of line or previous word.
*/
else
{
int cclass = 0, prev_cclass = 0;
if (has_mbyte)
cclass = mb_get_class(ml_get_cursor());
do
{
#ifdef FEAT_RIGHTLEFT
if (!revins_on) // put cursor on char to be deleted
#endif
dec_cursor();
cc = gchar_cursor();
// look multi-byte character class
if (has_mbyte)
{
prev_cclass = cclass;
cclass = mb_get_class(ml_get_cursor());
}
// start of word?
if (mode == BACKSPACE_WORD && !vim_isspace(cc))
{
mode = BACKSPACE_WORD_NOT_SPACE;
temp = vim_iswordc(cc);
}
// end of word?
else if (mode == BACKSPACE_WORD_NOT_SPACE
&& ((vim_isspace(cc) || vim_iswordc(cc) != temp)
|| prev_cclass != cclass))
{
#ifdef FEAT_RIGHTLEFT
if (!revins_on)
#endif
inc_cursor();
#ifdef FEAT_RIGHTLEFT
else if (State & REPLACE_FLAG)
dec_cursor();
#endif
break;
}
if (State & REPLACE_FLAG)
replace_do_bs(-1);
else
{
if (enc_utf8 && p_deco)
(void)utfc_ptr2char(ml_get_cursor(), cpc);
(void)del_char(FALSE);
/*
* If there are combining characters and 'delcombine' is set
* move the cursor back. Don't back up before the base
* character.
*/
if (enc_utf8 && p_deco && cpc[0] != NUL)
inc_cursor();
#ifdef FEAT_RIGHTLEFT
if (revins_chars)
{
revins_chars--;
revins_legal++;
}
if (revins_on && gchar_cursor() == NUL)
break;
#endif
}
// Just a single backspace?:
if (mode == BACKSPACE_CHAR)
break;
} while (
#ifdef FEAT_RIGHTLEFT
revins_on ||
#endif
(curwin->w_cursor.col > mincol
&& (can_bs(BS_NOSTOP)
|| (curwin->w_cursor.lnum != Insstart_orig.lnum
|| curwin->w_cursor.col != Insstart_orig.col)
)));
}
did_backspace = TRUE;
}
did_si = FALSE;
can_si = FALSE;
can_si_back = FALSE;
if (curwin->w_cursor.col <= 1)
did_ai = FALSE;
if (call_fix_indent)
fix_indent();
/*
* It's a little strange to put backspaces into the redo
* buffer, but it makes auto-indent a lot easier to deal
* with.
*/
AppendCharToRedobuff(c);
// If deleted before the insertion point, adjust it
if (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col < Insstart_orig.col)
Insstart_orig.col = curwin->w_cursor.col;
// vi behaviour: the cursor moves backward but the character that
// was there remains visible
// Vim behaviour: the cursor moves backward and the character that
// was there is erased from the screen.
// We can emulate the vi behaviour by pretending there is a dollar
// displayed even when there isn't.
// --pkv Sun Jan 19 01:56:40 EST 2003
if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1)
dollar_vcol = curwin->w_virtcol;
#ifdef FEAT_FOLDING
// When deleting a char the cursor line must never be in a closed fold.
// E.g., when 'foldmethod' is indent and deleting the first non-white
// char before a Tab.
if (did_backspace)
foldOpenCursor();
#endif
return did_backspace;
}
|
172194519756788339453675041357999010208
|
edit.c
|
334216402611901751671385717284214475763
|
CWE-787
|
CVE-2022-2207
|
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2207
|
380,955
|
vim
|
0971c7a4e537ea120a6bb2195960be8d0815e97b
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/0971c7a4e537ea120a6bb2195960be8d0815e97b
|
patch 8.2.5162: reading before the start of the line with BS in Replace mode
Problem: Reading before the start of the line with BS in Replace mode.
Solution: Check the cursor column is more than zero.
| 0
|
ins_bs(
int c,
int mode,
int *inserted_space_p)
{
linenr_T lnum;
int cc;
int temp = 0; // init for GCC
colnr_T save_col;
colnr_T mincol;
int did_backspace = FALSE;
int in_indent;
int oldState;
int cpc[MAX_MCO]; // composing characters
int call_fix_indent = FALSE;
/*
* can't delete anything in an empty file
* can't backup past first character in buffer
* can't backup past starting point unless 'backspace' > 1
* can backup to a previous line if 'backspace' == 0
*/
if ( BUFEMPTY()
|| (
#ifdef FEAT_RIGHTLEFT
!revins_on &&
#endif
((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
|| (!can_bs(BS_START)
&& ((arrow_used
#ifdef FEAT_JOB_CHANNEL
&& !bt_prompt(curbuf)
#endif
) || (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col <= Insstart_orig.col)))
|| (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
&& curwin->w_cursor.col <= ai_col)
|| (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
{
vim_beep(BO_BS);
return FALSE;
}
if (stop_arrow() == FAIL)
return FALSE;
in_indent = inindent(0);
if (in_indent)
can_cindent = FALSE;
end_comment_pending = NUL; // After BS, don't auto-end comment
#ifdef FEAT_RIGHTLEFT
if (revins_on) // put cursor after last inserted char
inc_cursor();
#endif
// Virtualedit:
// BACKSPACE_CHAR eats a virtual space
// BACKSPACE_WORD eats all coladd
// BACKSPACE_LINE eats all coladd and keeps going
if (curwin->w_cursor.coladd > 0)
{
if (mode == BACKSPACE_CHAR)
{
--curwin->w_cursor.coladd;
return TRUE;
}
if (mode == BACKSPACE_WORD)
{
curwin->w_cursor.coladd = 0;
return TRUE;
}
curwin->w_cursor.coladd = 0;
}
/*
* Delete newline!
*/
if (curwin->w_cursor.col == 0)
{
lnum = Insstart.lnum;
if (curwin->w_cursor.lnum == lnum
#ifdef FEAT_RIGHTLEFT
|| revins_on
#endif
)
{
if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
(linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
return FALSE;
--Insstart.lnum;
Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum));
}
/*
* In replace mode:
* cc < 0: NL was inserted, delete it
* cc >= 0: NL was replaced, put original characters back
*/
cc = -1;
if (State & REPLACE_FLAG)
cc = replace_pop(); // returns -1 if NL was inserted
/*
* In replace mode, in the line we started replacing, we only move the
* cursor.
*/
if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
{
dec_cursor();
}
else
{
if (!(State & VREPLACE_FLAG)
|| curwin->w_cursor.lnum > orig_line_count)
{
temp = gchar_cursor(); // remember current char
--curwin->w_cursor.lnum;
// When "aw" is in 'formatoptions' we must delete the space at
// the end of the line, otherwise the line will be broken
// again when auto-formatting.
if (has_format_option(FO_AUTO)
&& has_format_option(FO_WHITE_PAR))
{
char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
TRUE);
int len;
len = (int)STRLEN(ptr);
if (len > 0 && ptr[len - 1] == ' ')
ptr[len - 1] = NUL;
}
(void)do_join(2, FALSE, FALSE, FALSE, FALSE);
if (temp == NUL && gchar_cursor() != NUL)
inc_cursor();
}
else
dec_cursor();
/*
* In MODE_REPLACE mode we have to put back the text that was
* replaced by the NL. On the replace stack is first a
* NUL-terminated sequence of characters that were deleted and then
* the characters that NL replaced.
*/
if (State & REPLACE_FLAG)
{
/*
* Do the next ins_char() in MODE_NORMAL state, to
* prevent ins_char() from replacing characters and
* avoiding showmatch().
*/
oldState = State;
State = MODE_NORMAL;
/*
* restore characters (blanks) deleted after cursor
*/
while (cc > 0)
{
save_col = curwin->w_cursor.col;
mb_replace_pop_ins(cc);
curwin->w_cursor.col = save_col;
cc = replace_pop();
}
// restore the characters that NL replaced
replace_pop_ins();
State = oldState;
}
}
did_ai = FALSE;
}
else
{
/*
* Delete character(s) before the cursor.
*/
#ifdef FEAT_RIGHTLEFT
if (revins_on) // put cursor on last inserted char
dec_cursor();
#endif
mincol = 0;
// keep indent
if (mode == BACKSPACE_LINE
&& (curbuf->b_p_ai || cindent_on())
#ifdef FEAT_RIGHTLEFT
&& !revins_on
#endif
)
{
save_col = curwin->w_cursor.col;
beginline(BL_WHITE);
if (curwin->w_cursor.col < save_col)
{
mincol = curwin->w_cursor.col;
// should now fix the indent to match with the previous line
call_fix_indent = TRUE;
}
curwin->w_cursor.col = save_col;
}
/*
* Handle deleting one 'shiftwidth' or 'softtabstop'.
*/
if ( mode == BACKSPACE_CHAR
&& ((p_sta && in_indent)
|| ((get_sts_value() != 0
#ifdef FEAT_VARTABS
|| tabstop_count(curbuf->b_p_vsts_array)
#endif
)
&& curwin->w_cursor.col > 0
&& (*(ml_get_cursor() - 1) == TAB
|| (*(ml_get_cursor() - 1) == ' '
&& (!*inserted_space_p
|| arrow_used))))))
{
int ts;
colnr_T vcol;
colnr_T want_vcol;
colnr_T start_vcol;
*inserted_space_p = FALSE;
// Compute the virtual column where we want to be. Since
// 'showbreak' may get in the way, need to get the last column of
// the previous character.
getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
start_vcol = vcol;
dec_cursor();
getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
inc_cursor();
#ifdef FEAT_VARTABS
if (p_sta && in_indent)
{
ts = (int)get_sw_value(curbuf);
want_vcol = (want_vcol / ts) * ts;
}
else
want_vcol = tabstop_start(want_vcol, get_sts_value(),
curbuf->b_p_vsts_array);
#else
if (p_sta && in_indent)
ts = (int)get_sw_value(curbuf);
else
ts = (int)get_sts_value();
want_vcol = (want_vcol / ts) * ts;
#endif
// delete characters until we are at or before want_vcol
while (vcol > want_vcol && curwin->w_cursor.col > 0
&& (cc = *(ml_get_cursor() - 1), VIM_ISWHITE(cc)))
ins_bs_one(&vcol);
// insert extra spaces until we are at want_vcol
while (vcol < want_vcol)
{
// Remember the first char we inserted
if (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col < Insstart_orig.col)
Insstart_orig.col = curwin->w_cursor.col;
if (State & VREPLACE_FLAG)
ins_char(' ');
else
{
ins_str((char_u *)" ");
if ((State & REPLACE_FLAG))
replace_push(NUL);
}
getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
}
// If we are now back where we started delete one character. Can
// happen when using 'sts' and 'linebreak'.
if (vcol >= start_vcol)
ins_bs_one(&vcol);
}
/*
* Delete up to starting point, start of line or previous word.
*/
else
{
int cclass = 0, prev_cclass = 0;
if (has_mbyte)
cclass = mb_get_class(ml_get_cursor());
do
{
#ifdef FEAT_RIGHTLEFT
if (!revins_on) // put cursor on char to be deleted
#endif
dec_cursor();
cc = gchar_cursor();
// look multi-byte character class
if (has_mbyte)
{
prev_cclass = cclass;
cclass = mb_get_class(ml_get_cursor());
}
// start of word?
if (mode == BACKSPACE_WORD && !vim_isspace(cc))
{
mode = BACKSPACE_WORD_NOT_SPACE;
temp = vim_iswordc(cc);
}
// end of word?
else if (mode == BACKSPACE_WORD_NOT_SPACE
&& ((vim_isspace(cc) || vim_iswordc(cc) != temp)
|| prev_cclass != cclass))
{
#ifdef FEAT_RIGHTLEFT
if (!revins_on)
#endif
inc_cursor();
#ifdef FEAT_RIGHTLEFT
else if (State & REPLACE_FLAG)
dec_cursor();
#endif
break;
}
if (State & REPLACE_FLAG)
replace_do_bs(-1);
else
{
if (enc_utf8 && p_deco)
(void)utfc_ptr2char(ml_get_cursor(), cpc);
(void)del_char(FALSE);
/*
* If there are combining characters and 'delcombine' is set
* move the cursor back. Don't back up before the base
* character.
*/
if (enc_utf8 && p_deco && cpc[0] != NUL)
inc_cursor();
#ifdef FEAT_RIGHTLEFT
if (revins_chars)
{
revins_chars--;
revins_legal++;
}
if (revins_on && gchar_cursor() == NUL)
break;
#endif
}
// Just a single backspace?:
if (mode == BACKSPACE_CHAR)
break;
} while (
#ifdef FEAT_RIGHTLEFT
revins_on ||
#endif
(curwin->w_cursor.col > mincol
&& (can_bs(BS_NOSTOP)
|| (curwin->w_cursor.lnum != Insstart_orig.lnum
|| curwin->w_cursor.col != Insstart_orig.col)
)));
}
did_backspace = TRUE;
}
did_si = FALSE;
can_si = FALSE;
can_si_back = FALSE;
if (curwin->w_cursor.col <= 1)
did_ai = FALSE;
if (call_fix_indent)
fix_indent();
/*
* It's a little strange to put backspaces into the redo
* buffer, but it makes auto-indent a lot easier to deal
* with.
*/
AppendCharToRedobuff(c);
// If deleted before the insertion point, adjust it
if (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col < Insstart_orig.col)
Insstart_orig.col = curwin->w_cursor.col;
// vi behaviour: the cursor moves backward but the character that
// was there remains visible
// Vim behaviour: the cursor moves backward and the character that
// was there is erased from the screen.
// We can emulate the vi behaviour by pretending there is a dollar
// displayed even when there isn't.
// --pkv Sun Jan 19 01:56:40 EST 2003
if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1)
dollar_vcol = curwin->w_virtcol;
#ifdef FEAT_FOLDING
// When deleting a char the cursor line must never be in a closed fold.
// E.g., when 'foldmethod' is indent and deleting the first non-white
// char before a Tab.
if (did_backspace)
foldOpenCursor();
#endif
return did_backspace;
}
|
64259932111379563055532506605085485351
|
edit.c
|
91657375912486719968624749742093008286
|
CWE-787
|
CVE-2022-2207
|
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2207
|
206,555
|
php-src
|
cc08cbc84d46933c1e9e0149633f1ed5d19e45e9
|
https://github.com/php/php-src
|
https://git.php.net/?p=php-src.git;a=commit;h=cc08cbc84d46933c1e9e0149633f1ed5d19e45e9
|
Fix #73280: Stack Buffer Overflow in GD dynamicGetbuf
We make sure to never pass a negative `rlen` as size to memcpy().
Cf. <https://github.com/libgd/libgd/commit/53110871>.
| 1
|
static int dynamicGetbuf (gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if (remain >= len) {
rlen = len;
} else {
if (remain == 0) {
return EOF;
}
rlen = remain;
}
memcpy(buf, (void *) ((char *) dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
|
44554623121680820346289655905713695377
|
gd_io_dp.c
|
66950500877592745162628589676156559345
|
CWE-119
|
CVE-2016-8670
|
Integer signedness error in the dynamicGetbuf function in gd_io_dp.c in the GD Graphics Library (aka libgd) through 2.2.3, as used in PHP before 5.6.28 and 7.x before 7.0.13, allows remote attackers to cause a denial of service (stack-based buffer overflow) or possibly have unspecified other impact via a crafted imagecreatefromstring call.
|
https://nvd.nist.gov/vuln/detail/CVE-2016-8670
|
382,797
|
php-src
|
cc08cbc84d46933c1e9e0149633f1ed5d19e45e9
|
https://github.com/php/php-src
|
https://git.php.net/?p=php-src.git;a=commit;h=cc08cbc84d46933c1e9e0149633f1ed5d19e45e9
|
Fix #73280: Stack Buffer Overflow in GD dynamicGetbuf
We make sure to never pass a negative `rlen` as size to memcpy().
Cf. <https://github.com/libgd/libgd/commit/53110871>.
| 0
|
static int dynamicGetbuf (gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if (remain >= len) {
rlen = len;
} else {
if (remain <= 0) {
return EOF;
}
rlen = remain;
}
memcpy(buf, (void *) ((char *) dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
|
227798178939410399739015256330671261805
|
gd_io_dp.c
|
171487762597506665250744911889099357441
|
CWE-119
|
CVE-2016-8670
|
Integer signedness error in the dynamicGetbuf function in gd_io_dp.c in the GD Graphics Library (aka libgd) through 2.2.3, as used in PHP before 5.6.28 and 7.x before 7.0.13, allows remote attackers to cause a denial of service (stack-based buffer overflow) or possibly have unspecified other impact via a crafted imagecreatefromstring call.
|
https://nvd.nist.gov/vuln/detail/CVE-2016-8670
|
206,588
|
php-src
|
feba44546c27b0158f9ac20e72040a224b918c75
|
https://github.com/php/php-src
|
http://git.php.net/?p=php-src.git;a=commitdiff;h=feba44546c27b0158f9ac20e72040a224b918c75
|
Fixed bug #22965 (Crash in gd lib's ImageFillToBorder()).
| 1
|
gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit, rightLimit;
int i;
leftLimit = (-1);
if (border < 0)
{
/* Refuse to fill to a non-solid border */
return;
}
for (i = x; (i >= 0); i--)
{
if (gdImageGetPixel (im, i, y) == border)
{
break;
}
gdImageSetPixel (im, i, y, color);
leftLimit = i;
}
if (leftLimit == (-1))
{
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); (i < im->sx); i++)
{
if (gdImageGetPixel (im, i, y) == border)
{
break;
}
gdImageSetPixel (im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0)
{
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++)
{
int c;
c = gdImageGetPixel (im, i, y - 1);
if (lastBorder)
{
if ((c != border) && (c != color))
{
gdImageFillToBorder (im, i, y - 1,
border, color);
lastBorder = 0;
}
}
else if ((c == border) || (c == color))
{
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1))
{
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++)
{
int c;
c = gdImageGetPixel (im, i, y + 1);
if (lastBorder)
{
if ((c != border) && (c != color))
{
gdImageFillToBorder (im, i, y + 1,
border, color);
lastBorder = 0;
}
}
else if ((c == border) || (c == color))
{
lastBorder = 1;
}
}
}
}
|
198226344899217828573742271884272950799
|
None
|
CWE-119
|
CVE-2015-8874
|
Stack consumption vulnerability in GD in PHP before 5.6.12 allows remote attackers to cause a denial of service via a crafted imagefilltoborder call.
|
https://nvd.nist.gov/vuln/detail/CVE-2015-8874
|
|
383,316
|
php-src
|
feba44546c27b0158f9ac20e72040a224b918c75
|
https://github.com/php/php-src
|
http://git.php.net/?p=php-src.git;a=commitdiff;h=feba44546c27b0158f9ac20e72040a224b918c75
|
Fixed bug #22965 (Crash in gd lib's ImageFillToBorder()).
| 0
|
void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit = -1, rightLimit;
int i;
if (border < 0) {
/* Refuse to fill to a non-solid border */
return;
}
if (x >= im->sx) {
x = im->sx - 1;
}
if (y >= im->sy) {
y = im->sy - 1;
}
for (i = x; i >= 0; i--) {
if (gdImageGetPixel(im, i, y) == border) {
break;
}
gdImageSetPixel(im, i, y, color);
leftLimit = i;
}
if (leftLimit == -1) {
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); i < im->sx; i++) {
if (gdImageGetPixel(im, i, y) == border) {
break;
}
gdImageSetPixel(im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0) {
lastBorder = 1;
for (i = leftLimit; i <= rightLimit; i++) {
int c = gdImageGetPixel(im, i, y - 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder(im, i, y - 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1)) {
lastBorder = 1;
for (i = leftLimit; i <= rightLimit; i++) {
int c = gdImageGetPixel(im, i, y + 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder(im, i, y + 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
}
|
4519916874419069747672345142292777613
|
None
|
CWE-119
|
CVE-2015-8874
|
Stack consumption vulnerability in GD in PHP before 5.6.12 allows remote attackers to cause a denial of service via a crafted imagefilltoborder call.
|
https://nvd.nist.gov/vuln/detail/CVE-2015-8874
|
|
206,625
|
raptor
|
590681e546cd9aa18d57dc2ea1858cb734a3863f
|
https://github.com/dajobe/raptor
|
https://github.com/dajobe/raptor/commit/590681e546cd9aa18d57dc2ea1858cb734a3863f
|
Calcualte max nspace declarations correctly for XML writer
(raptor_xml_writer_start_element_common): Calculate max including for
each attribute a potential name and value.
Fixes Issues #0000617 http://bugs.librdf.org/mantis/view.php?id=617
and #0000618 http://bugs.librdf.org/mantis/view.php?id=618
| 1
|
raptor_xml_writer_start_element_common(raptor_xml_writer* xml_writer,
raptor_xml_element* element,
int auto_empty)
{
raptor_iostream* iostr = xml_writer->iostr;
raptor_namespace_stack *nstack = xml_writer->nstack;
int depth = xml_writer->depth;
int auto_indent = XML_WRITER_AUTO_INDENT(xml_writer);
struct nsd *nspace_declarations = NULL;
size_t nspace_declarations_count = 0;
unsigned int i;
/* max is 1 per element and 1 for each attribute + size of declared */
if(nstack) {
int nspace_max_count = element->attribute_count+1;
if(element->declared_nspaces)
nspace_max_count += raptor_sequence_size(element->declared_nspaces);
if(element->xml_language)
nspace_max_count++;
nspace_declarations = RAPTOR_CALLOC(struct nsd*, nspace_max_count,
sizeof(struct nsd));
if(!nspace_declarations)
return 1;
}
if(element->name->nspace) {
if(nstack && !raptor_namespaces_namespace_in_scope(nstack, element->name->nspace)) {
nspace_declarations[0].declaration=
raptor_namespace_format_as_xml(element->name->nspace,
&nspace_declarations[0].length);
if(!nspace_declarations[0].declaration)
goto error;
nspace_declarations[0].nspace = element->name->nspace;
nspace_declarations_count++;
}
}
if(nstack && element->attributes) {
for(i = 0; i < element->attribute_count; i++) {
/* qname */
if(element->attributes[i]->nspace) {
/* Check if we need a namespace declaration attribute */
if(nstack &&
!raptor_namespaces_namespace_in_scope(nstack, element->attributes[i]->nspace) && element->attributes[i]->nspace != element->name->nspace) {
/* not in scope and not same as element (so already going to be declared)*/
unsigned int j;
int declare_me = 1;
/* check it wasn't an earlier declaration too */
for(j = 0; j < nspace_declarations_count; j++)
if(nspace_declarations[j].nspace == element->attributes[j]->nspace) {
declare_me = 0;
break;
}
if(declare_me) {
nspace_declarations[nspace_declarations_count].declaration=
raptor_namespace_format_as_xml(element->attributes[i]->nspace,
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = element->attributes[i]->nspace;
nspace_declarations_count++;
}
}
}
/* Add the attribute + value */
nspace_declarations[nspace_declarations_count].declaration=
raptor_qname_format_as_xml(element->attributes[i],
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = NULL;
nspace_declarations_count++;
}
}
if(nstack && element->declared_nspaces &&
raptor_sequence_size(element->declared_nspaces) > 0) {
for(i = 0; i< (unsigned int)raptor_sequence_size(element->declared_nspaces); i++) {
raptor_namespace* nspace = (raptor_namespace*)raptor_sequence_get_at(element->declared_nspaces, i);
unsigned int j;
int declare_me = 1;
/* check it wasn't an earlier declaration too */
for(j = 0; j < nspace_declarations_count; j++)
if(nspace_declarations[j].nspace == nspace) {
declare_me = 0;
break;
}
if(declare_me) {
nspace_declarations[nspace_declarations_count].declaration=
raptor_namespace_format_as_xml(nspace,
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = nspace;
nspace_declarations_count++;
}
}
}
if(nstack && element->xml_language) {
size_t lang_len = strlen(RAPTOR_GOOD_CAST(char*, element->xml_language));
#define XML_LANG_PREFIX_LEN 10
size_t buf_length = XML_LANG_PREFIX_LEN + lang_len + 1;
unsigned char* buffer = RAPTOR_MALLOC(unsigned char*, buf_length + 1);
const char quote = '\"';
unsigned char* p;
memcpy(buffer, "xml:lang=\"", XML_LANG_PREFIX_LEN);
p = buffer + XML_LANG_PREFIX_LEN;
p += raptor_xml_escape_string(xml_writer->world,
element->xml_language, lang_len,
p, buf_length, quote);
*p++ = quote;
*p = '\0';
nspace_declarations[nspace_declarations_count].declaration = buffer;
nspace_declarations[nspace_declarations_count].length = buf_length;
nspace_declarations[nspace_declarations_count].nspace = NULL;
nspace_declarations_count++;
}
raptor_iostream_write_byte('<', iostr);
if(element->name->nspace && element->name->nspace->prefix_length > 0) {
raptor_iostream_counted_string_write((const char*)element->name->nspace->prefix,
element->name->nspace->prefix_length,
iostr);
raptor_iostream_write_byte(':', iostr);
}
raptor_iostream_counted_string_write((const char*)element->name->local_name,
element->name->local_name_length,
iostr);
/* declare namespaces and attributes */
if(nspace_declarations_count) {
int need_indent = 0;
/* sort them into the canonical order */
qsort((void*)nspace_declarations,
nspace_declarations_count, sizeof(struct nsd),
raptor_xml_writer_nsd_compare);
/* declare namespaces first */
for(i = 0; i < nspace_declarations_count; i++) {
if(!nspace_declarations[i].nspace)
continue;
if(auto_indent && need_indent) {
/* indent attributes */
raptor_xml_writer_newline(xml_writer);
xml_writer->depth++;
raptor_xml_writer_indent(xml_writer);
xml_writer->depth--;
}
raptor_iostream_write_byte(' ', iostr);
raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,
nspace_declarations[i].length,
iostr);
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
nspace_declarations[i].declaration = NULL;
need_indent = 1;
if(raptor_namespace_stack_start_namespace(nstack,
(raptor_namespace*)nspace_declarations[i].nspace,
depth))
goto error;
}
/* declare attributes */
for(i = 0; i < nspace_declarations_count; i++) {
if(nspace_declarations[i].nspace)
continue;
if(auto_indent && need_indent) {
/* indent attributes */
raptor_xml_writer_newline(xml_writer);
xml_writer->depth++;
raptor_xml_writer_indent(xml_writer);
xml_writer->depth--;
}
raptor_iostream_write_byte(' ', iostr);
raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,
nspace_declarations[i].length,
iostr);
need_indent = 1;
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
nspace_declarations[i].declaration = NULL;
}
}
if(!auto_empty)
raptor_iostream_write_byte('>', iostr);
if(nstack)
RAPTOR_FREE(stringarray, nspace_declarations);
return 0;
/* Clean up nspace_declarations on error */
error:
for(i = 0; i < nspace_declarations_count; i++) {
if(nspace_declarations[i].declaration)
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
}
RAPTOR_FREE(stringarray, nspace_declarations);
return 1;
}
|
183974089624650942434351568312452779610
|
raptor_xml_writer.c
|
303005196227120175198140448209688194758
|
CWE-787
|
CVE-2017-18926
|
raptor_xml_writer_start_element_common in raptor_xml_writer.c in Raptor RDF Syntax Library 2.0.15 miscalculates the maximum nspace declarations for the XML writer, leading to heap-based buffer overflows (sometimes seen in raptor_qname_format_as_xml).
|
https://nvd.nist.gov/vuln/detail/CVE-2017-18926
|
384,124
|
raptor
|
590681e546cd9aa18d57dc2ea1858cb734a3863f
|
https://github.com/dajobe/raptor
|
https://github.com/dajobe/raptor/commit/590681e546cd9aa18d57dc2ea1858cb734a3863f
|
Calcualte max nspace declarations correctly for XML writer
(raptor_xml_writer_start_element_common): Calculate max including for
each attribute a potential name and value.
Fixes Issues #0000617 http://bugs.librdf.org/mantis/view.php?id=617
and #0000618 http://bugs.librdf.org/mantis/view.php?id=618
| 0
|
raptor_xml_writer_start_element_common(raptor_xml_writer* xml_writer,
raptor_xml_element* element,
int auto_empty)
{
raptor_iostream* iostr = xml_writer->iostr;
raptor_namespace_stack *nstack = xml_writer->nstack;
int depth = xml_writer->depth;
int auto_indent = XML_WRITER_AUTO_INDENT(xml_writer);
struct nsd *nspace_declarations = NULL;
size_t nspace_declarations_count = 0;
unsigned int i;
if(nstack) {
int nspace_max_count = element->attribute_count * 2; /* attr and value */
if(element->name->nspace)
nspace_max_count++;
if(element->declared_nspaces)
nspace_max_count += raptor_sequence_size(element->declared_nspaces);
if(element->xml_language)
nspace_max_count++;
nspace_declarations = RAPTOR_CALLOC(struct nsd*, nspace_max_count,
sizeof(struct nsd));
if(!nspace_declarations)
return 1;
}
if(element->name->nspace) {
if(nstack && !raptor_namespaces_namespace_in_scope(nstack, element->name->nspace)) {
nspace_declarations[0].declaration=
raptor_namespace_format_as_xml(element->name->nspace,
&nspace_declarations[0].length);
if(!nspace_declarations[0].declaration)
goto error;
nspace_declarations[0].nspace = element->name->nspace;
nspace_declarations_count++;
}
}
if(nstack && element->attributes) {
for(i = 0; i < element->attribute_count; i++) {
/* qname */
if(element->attributes[i]->nspace) {
/* Check if we need a namespace declaration attribute */
if(nstack &&
!raptor_namespaces_namespace_in_scope(nstack, element->attributes[i]->nspace) && element->attributes[i]->nspace != element->name->nspace) {
/* not in scope and not same as element (so already going to be declared)*/
unsigned int j;
int declare_me = 1;
/* check it wasn't an earlier declaration too */
for(j = 0; j < nspace_declarations_count; j++)
if(nspace_declarations[j].nspace == element->attributes[j]->nspace) {
declare_me = 0;
break;
}
if(declare_me) {
nspace_declarations[nspace_declarations_count].declaration=
raptor_namespace_format_as_xml(element->attributes[i]->nspace,
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = element->attributes[i]->nspace;
nspace_declarations_count++;
}
}
}
/* Add the attribute's value */
nspace_declarations[nspace_declarations_count].declaration=
raptor_qname_format_as_xml(element->attributes[i],
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = NULL;
nspace_declarations_count++;
}
}
if(nstack && element->declared_nspaces &&
raptor_sequence_size(element->declared_nspaces) > 0) {
for(i = 0; i< (unsigned int)raptor_sequence_size(element->declared_nspaces); i++) {
raptor_namespace* nspace = (raptor_namespace*)raptor_sequence_get_at(element->declared_nspaces, i);
unsigned int j;
int declare_me = 1;
/* check it wasn't an earlier declaration too */
for(j = 0; j < nspace_declarations_count; j++)
if(nspace_declarations[j].nspace == nspace) {
declare_me = 0;
break;
}
if(declare_me) {
nspace_declarations[nspace_declarations_count].declaration=
raptor_namespace_format_as_xml(nspace,
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = nspace;
nspace_declarations_count++;
}
}
}
if(nstack && element->xml_language) {
size_t lang_len = strlen(RAPTOR_GOOD_CAST(char*, element->xml_language));
#define XML_LANG_PREFIX_LEN 10
size_t buf_length = XML_LANG_PREFIX_LEN + lang_len + 1;
unsigned char* buffer = RAPTOR_MALLOC(unsigned char*, buf_length + 1);
const char quote = '\"';
unsigned char* p;
memcpy(buffer, "xml:lang=\"", XML_LANG_PREFIX_LEN);
p = buffer + XML_LANG_PREFIX_LEN;
p += raptor_xml_escape_string(xml_writer->world,
element->xml_language, lang_len,
p, buf_length, quote);
*p++ = quote;
*p = '\0';
nspace_declarations[nspace_declarations_count].declaration = buffer;
nspace_declarations[nspace_declarations_count].length = buf_length;
nspace_declarations[nspace_declarations_count].nspace = NULL;
nspace_declarations_count++;
}
raptor_iostream_write_byte('<', iostr);
if(element->name->nspace && element->name->nspace->prefix_length > 0) {
raptor_iostream_counted_string_write((const char*)element->name->nspace->prefix,
element->name->nspace->prefix_length,
iostr);
raptor_iostream_write_byte(':', iostr);
}
raptor_iostream_counted_string_write((const char*)element->name->local_name,
element->name->local_name_length,
iostr);
/* declare namespaces and attributes */
if(nspace_declarations_count) {
int need_indent = 0;
/* sort them into the canonical order */
qsort((void*)nspace_declarations,
nspace_declarations_count, sizeof(struct nsd),
raptor_xml_writer_nsd_compare);
/* declare namespaces first */
for(i = 0; i < nspace_declarations_count; i++) {
if(!nspace_declarations[i].nspace)
continue;
if(auto_indent && need_indent) {
/* indent attributes */
raptor_xml_writer_newline(xml_writer);
xml_writer->depth++;
raptor_xml_writer_indent(xml_writer);
xml_writer->depth--;
}
raptor_iostream_write_byte(' ', iostr);
raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,
nspace_declarations[i].length,
iostr);
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
nspace_declarations[i].declaration = NULL;
need_indent = 1;
if(raptor_namespace_stack_start_namespace(nstack,
(raptor_namespace*)nspace_declarations[i].nspace,
depth))
goto error;
}
/* declare attributes */
for(i = 0; i < nspace_declarations_count; i++) {
if(nspace_declarations[i].nspace)
continue;
if(auto_indent && need_indent) {
/* indent attributes */
raptor_xml_writer_newline(xml_writer);
xml_writer->depth++;
raptor_xml_writer_indent(xml_writer);
xml_writer->depth--;
}
raptor_iostream_write_byte(' ', iostr);
raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,
nspace_declarations[i].length,
iostr);
need_indent = 1;
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
nspace_declarations[i].declaration = NULL;
}
}
if(!auto_empty)
raptor_iostream_write_byte('>', iostr);
if(nstack)
RAPTOR_FREE(stringarray, nspace_declarations);
return 0;
/* Clean up nspace_declarations on error */
error:
for(i = 0; i < nspace_declarations_count; i++) {
if(nspace_declarations[i].declaration)
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
}
RAPTOR_FREE(stringarray, nspace_declarations);
return 1;
}
|
82963305933956175677502497774267767451
|
raptor_xml_writer.c
|
139112831165877018854969912519011883099
|
CWE-787
|
CVE-2017-18926
|
raptor_xml_writer_start_element_common in raptor_xml_writer.c in Raptor RDF Syntax Library 2.0.15 miscalculates the maximum nspace declarations for the XML writer, leading to heap-based buffer overflows (sometimes seen in raptor_qname_format_as_xml).
|
https://nvd.nist.gov/vuln/detail/CVE-2017-18926
|
206,639
|
linux
|
e02f0d3970404bfea385b6edb86f2d936db0ea2b
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/e02f0d3970404bfea385b6edb86f2d936db0ea2b
|
netfilter: nf_tables: disallow binding to already bound chain
Update nft_data_init() to report EINVAL if chain is already bound.
Fixes: d0e2c7de92c7 ("netfilter: nf_tables: add NFT_CHAIN_BINDING")
Reported-by: Gwangun Jung <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
| 1
|
static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
struct nft_data_desc *desc, const struct nlattr *nla)
{
u8 genmask = nft_genmask_next(ctx->net);
struct nlattr *tb[NFTA_VERDICT_MAX + 1];
struct nft_chain *chain;
int err;
err = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla,
nft_verdict_policy, NULL);
if (err < 0)
return err;
if (!tb[NFTA_VERDICT_CODE])
return -EINVAL;
data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
switch (data->verdict.code) {
default:
switch (data->verdict.code & NF_VERDICT_MASK) {
case NF_ACCEPT:
case NF_DROP:
case NF_QUEUE:
break;
default:
return -EINVAL;
}
fallthrough;
case NFT_CONTINUE:
case NFT_BREAK:
case NFT_RETURN:
break;
case NFT_JUMP:
case NFT_GOTO:
if (tb[NFTA_VERDICT_CHAIN]) {
chain = nft_chain_lookup(ctx->net, ctx->table,
tb[NFTA_VERDICT_CHAIN],
genmask);
} else if (tb[NFTA_VERDICT_CHAIN_ID]) {
chain = nft_chain_lookup_byid(ctx->net, ctx->table,
tb[NFTA_VERDICT_CHAIN_ID]);
if (IS_ERR(chain))
return PTR_ERR(chain);
} else {
return -EINVAL;
}
if (IS_ERR(chain))
return PTR_ERR(chain);
if (nft_is_base_chain(chain))
return -EOPNOTSUPP;
if (desc->flags & NFT_DATA_DESC_SETELEM &&
chain->flags & NFT_CHAIN_BINDING)
return -EINVAL;
chain->use++;
data->verdict.chain = chain;
break;
}
desc->len = sizeof(data->verdict);
return 0;
}
|
76294390154807140346030498178733770308
|
nf_tables_api.c
|
280373467088228575441623327249382307245
|
CWE-703
|
CVE-2022-39190
|
An issue was discovered in net/netfilter/nf_tables_api.c in the Linux kernel before 5.19.6. A denial of service can occur upon binding to an already bound chain.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-39190
|
384,201
|
linux
|
e02f0d3970404bfea385b6edb86f2d936db0ea2b
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/e02f0d3970404bfea385b6edb86f2d936db0ea2b
|
netfilter: nf_tables: disallow binding to already bound chain
Update nft_data_init() to report EINVAL if chain is already bound.
Fixes: d0e2c7de92c7 ("netfilter: nf_tables: add NFT_CHAIN_BINDING")
Reported-by: Gwangun Jung <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
| 0
|
static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
struct nft_data_desc *desc, const struct nlattr *nla)
{
u8 genmask = nft_genmask_next(ctx->net);
struct nlattr *tb[NFTA_VERDICT_MAX + 1];
struct nft_chain *chain;
int err;
err = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla,
nft_verdict_policy, NULL);
if (err < 0)
return err;
if (!tb[NFTA_VERDICT_CODE])
return -EINVAL;
data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
switch (data->verdict.code) {
default:
switch (data->verdict.code & NF_VERDICT_MASK) {
case NF_ACCEPT:
case NF_DROP:
case NF_QUEUE:
break;
default:
return -EINVAL;
}
fallthrough;
case NFT_CONTINUE:
case NFT_BREAK:
case NFT_RETURN:
break;
case NFT_JUMP:
case NFT_GOTO:
if (tb[NFTA_VERDICT_CHAIN]) {
chain = nft_chain_lookup(ctx->net, ctx->table,
tb[NFTA_VERDICT_CHAIN],
genmask);
} else if (tb[NFTA_VERDICT_CHAIN_ID]) {
chain = nft_chain_lookup_byid(ctx->net, ctx->table,
tb[NFTA_VERDICT_CHAIN_ID]);
if (IS_ERR(chain))
return PTR_ERR(chain);
} else {
return -EINVAL;
}
if (IS_ERR(chain))
return PTR_ERR(chain);
if (nft_is_base_chain(chain))
return -EOPNOTSUPP;
if (nft_chain_is_bound(chain))
return -EINVAL;
if (desc->flags & NFT_DATA_DESC_SETELEM &&
chain->flags & NFT_CHAIN_BINDING)
return -EINVAL;
chain->use++;
data->verdict.chain = chain;
break;
}
desc->len = sizeof(data->verdict);
return 0;
}
|
189225679685979204194302814541477257663
|
nf_tables_api.c
|
161585463478410786724773068235961577198
|
CWE-703
|
CVE-2022-39190
|
An issue was discovered in net/netfilter/nf_tables_api.c in the Linux kernel before 5.19.6. A denial of service can occur upon binding to an already bound chain.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-39190
|
206,670
|
nbdkit
|
6c5faac6a37077cf2366388a80862bb00616d0d8
|
https://github.com/libguestfs/nbdkit
|
https://gitlab.com/nbdkit/nbdkit/-/commit/6c5faac6a37077cf2366388a80862bb00616d0d8
|
server: reset meta context replies on starttls
Related to CVE-2021-3716, but not as severe. No compliant client will
send NBD_CMD_BLOCK_STATUS unless it first negotiates
NBD_OPT_SET_META_CONTEXT. If an attacker injects a premature
SET_META_CONTEXT, either the client will never notice (because it
never uses BLOCK_STATUS), or the client will overwrite the attacker's
attempt with the client's own SET_META_CONTEXT request after
encryption is enabled. So I don't class this as having the potential
to trigger denial-of-service due to any protocol mismatch between
compliant client and server (I don't care what happens with
non-compliant clients).
Fixes: 26455d45 (server: protocol: Implement Block Status "base:allocation".)
| 1
|
negotiate_handshake_newstyle_options (void)
{
GET_CONN;
struct nbd_new_option new_option;
size_t nr_options;
bool list_seen = false;
uint64_t version;
uint32_t option;
uint32_t optlen;
struct nbd_export_name_option_reply handshake_finish;
const char *optname;
uint64_t exportsize;
struct backend *b;
for (nr_options = MAX_NR_OPTIONS; nr_options > 0; --nr_options) {
CLEANUP_FREE char *data = NULL;
if (conn_recv_full (&new_option, sizeof new_option,
"reading option: conn->recv: %m") == -1)
return -1;
version = be64toh (new_option.version);
if (version != NBD_NEW_VERSION) {
nbdkit_error ("unknown option version %" PRIx64
", expecting %" PRIx64,
version, NBD_NEW_VERSION);
return -1;
}
/* There is a maximum option length we will accept, regardless
* of the option type.
*/
optlen = be32toh (new_option.optlen);
if (optlen > MAX_REQUEST_SIZE) {
nbdkit_error ("client option data too long (%" PRIu32 ")", optlen);
return -1;
}
data = malloc (optlen + 1); /* Allowing a trailing NUL helps some uses */
if (data == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
option = be32toh (new_option.option);
optname = name_of_nbd_opt (option);
/* If the client lacks fixed newstyle support, it should only send
* NBD_OPT_EXPORT_NAME.
*/
if (!(conn->cflags & NBD_FLAG_FIXED_NEWSTYLE) &&
option != NBD_OPT_EXPORT_NAME) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID))
return -1;
continue;
}
/* In --tls=require / FORCEDTLS mode the only options allowed
* before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.
*/
if (tls == 2 && !conn->using_tls &&
!(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_TLS_REQD))
return -1;
continue;
}
switch (option) {
case NBD_OPT_EXPORT_NAME:
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
if (check_export_name (option, data, optlen, optlen) == -1)
return -1;
/* We have to finish the handshake by sending handshake_finish.
* On failure, we have to disconnect.
*/
if (finish_newstyle_options (&exportsize, data, optlen) == -1)
return -1;
memset (&handshake_finish, 0, sizeof handshake_finish);
handshake_finish.exportsize = htobe64 (exportsize);
handshake_finish.eflags = htobe16 (conn->eflags);
if (conn->send (&handshake_finish,
(conn->cflags & NBD_FLAG_NO_ZEROES)
? offsetof (struct nbd_export_name_option_reply, zeroes)
: sizeof handshake_finish, 0) == -1) {
nbdkit_error ("write: %s: %m", optname);
return -1;
}
break;
case NBD_OPT_ABORT:
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
debug ("client sent %s to abort the connection",
name_of_nbd_opt (option));
return -1;
case NBD_OPT_LIST:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (list_seen) {
debug ("newstyle negotiation: %s: export list already advertised",
name_of_nbd_opt (option));
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
else {
/* Send back the exportname list. */
debug ("newstyle negotiation: %s: advertising exports",
name_of_nbd_opt (option));
if (send_newstyle_option_reply_exportnames (option, &nr_options) == -1)
return -1;
list_seen = true;
}
break;
case NBD_OPT_STARTTLS:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (tls == 0) { /* --tls=off (NOTLS mode). */
#ifdef HAVE_GNUTLS
#define NO_TLS_REPLY NBD_REP_ERR_POLICY
#else
#define NO_TLS_REPLY NBD_REP_ERR_UNSUP
#endif
if (send_newstyle_option_reply (option, NO_TLS_REPLY) == -1)
return -1;
}
else /* --tls=on or --tls=require */ {
/* We can't upgrade to TLS twice on the same connection. */
if (conn->using_tls) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
/* We have to send the (unencrypted) reply before starting
* the handshake.
*/
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
/* Upgrade the connection to TLS. Also performs access control. */
if (crypto_negotiate_tls (conn->sockin, conn->sockout) == -1)
return -1;
conn->using_tls = true;
debug ("using TLS on this connection");
/* Wipe out any cached state. */
conn->structured_replies = false;
for_each_backend (b) {
free (conn->default_exportname[b->i]);
conn->default_exportname[b->i] = NULL;
}
}
break;
case NBD_OPT_INFO:
case NBD_OPT_GO:
if (conn_recv_full (data, optlen, "read: %s: %m", optname) == -1)
return -1;
if (optlen < 6) { /* 32 bit export length + 16 bit nr info */
debug ("newstyle negotiation: %s option length < 6", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
{
uint32_t exportnamelen;
uint16_t nrinfos;
uint16_t info;
size_t i;
/* Validate the name length and number of INFO requests. */
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {
debug ("newstyle negotiation: %s: export name too long", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&nrinfos, &data[exportnamelen+4], 2);
nrinfos = be16toh (nrinfos);
if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {
debug ("newstyle negotiation: %s: "
"number of information requests incorrect", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* As with NBD_OPT_EXPORT_NAME we print the export name and
* save it in the connection. If an earlier
* NBD_OPT_SET_META_CONTEXT used an export name, it must match
* or else we drop the support for that context.
*/
if (check_export_name (option, &data[4], exportnamelen,
optlen - 6) == -1) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* The spec is confusing, but it is required that we send back
* NBD_INFO_EXPORT, even if the client did not request it!
* qemu client in particular does not request this, but will
* fail if we don't send it. Note that if .open fails, but we
* succeed at .close, then we merely return an error to the
* client and let them try another NBD_OPT, rather than
* disconnecting.
*/
if (finish_newstyle_options (&exportsize,
&data[4], exportnamelen) == -1) {
if (conn->top_context) {
if (backend_finalize (conn->top_context) == -1)
return -1;
backend_close (conn->top_context);
conn->top_context = NULL;
}
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNKNOWN) == -1)
return -1;
continue;
}
if (send_newstyle_option_reply_info_export (option,
NBD_REP_INFO,
NBD_INFO_EXPORT,
exportsize) == -1)
return -1;
/* For now we send NBD_INFO_NAME and NBD_INFO_DESCRIPTION if
* requested, and ignore all other info requests (including
* NBD_INFO_EXPORT if it was requested, because we replied
* already above).
*/
for (i = 0; i < nrinfos; ++i) {
memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);
info = be16toh (info);
switch (info) {
case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;
case NBD_INFO_NAME:
{
const char *name = &data[4];
size_t namelen = exportnamelen;
if (exportnamelen == 0) {
name = backend_default_export (top, read_only);
if (!name) {
debug ("newstyle negotiation: %s: "
"NBD_INFO_NAME: no name to send", optname);
break;
}
namelen = -1;
}
if (send_newstyle_option_reply_info_str (option,
NBD_REP_INFO,
NBD_INFO_NAME,
name, namelen) == -1)
return -1;
}
break;
case NBD_INFO_DESCRIPTION:
{
const char *desc = backend_export_description (conn->top_context);
if (!desc) {
debug ("newstyle negotiation: %s: "
"NBD_INFO_DESCRIPTION: no description to send",
optname);
break;
}
if (send_newstyle_option_reply_info_str (option,
NBD_REP_INFO,
NBD_INFO_DESCRIPTION,
desc, -1) == -1)
return -1;
}
break;
default:
debug ("newstyle negotiation: %s: "
"ignoring NBD_INFO_* request %u (%s)",
optname, (unsigned) info, name_of_nbd_info (info));
break;
}
}
}
/* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK
* or ERROR packet. If this was NBD_OPT_LIST, call .close.
*/
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
if (option == NBD_OPT_INFO) {
if (backend_finalize (conn->top_context) == -1)
return -1;
backend_close (conn->top_context);
conn->top_context = NULL;
}
break;
case NBD_OPT_STRUCTURED_REPLY:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
debug ("newstyle negotiation: %s: client requested structured replies",
name_of_nbd_opt (option));
if (no_sr) {
/* Must fail with ERR_UNSUP for qemu 4.2 to remain happy;
* but failing with ERR_POLICY would have been nicer.
*/
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)
return -1;
debug ("newstyle negotiation: %s: structured replies are disabled",
name_of_nbd_opt (option));
break;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
conn->structured_replies = true;
break;
case NBD_OPT_LIST_META_CONTEXT:
case NBD_OPT_SET_META_CONTEXT:
{
uint32_t opt_index;
uint32_t exportnamelen;
uint32_t nr_queries;
uint32_t querylen;
const char *what;
if (conn_recv_full (data, optlen, "read: %s: %m", optname) == -1)
return -1;
/* Note that we support base:allocation whether or not the plugin
* supports can_extents.
*/
if (!conn->structured_replies) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* Minimum length of the option payload is:
* 32 bit export name length followed by empty export name
* + 32 bit number of queries followed by no queries
* = 8 bytes.
*/
what = "optlen < 8";
if (optlen < 8) {
opt_meta_invalid_option_len:
debug ("newstyle negotiation: %s: invalid option length: %s",
optname, what);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
what = "validating export name";
if (check_export_name (option, &data[4], exportnamelen,
optlen - 8) == -1)
goto opt_meta_invalid_option_len;
/* Remember the export name: the NBD spec says that if the client
* later uses NBD_OPT_GO on a different export, then the context
* returned here is not usable.
*/
if (option == NBD_OPT_SET_META_CONTEXT) {
conn->exportname_from_set_meta_context =
strndup (&data[4], exportnamelen);
if (conn->exportname_from_set_meta_context == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
}
opt_index = 4 + exportnamelen;
/* Read the number of queries. */
what = "reading number of queries";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&nr_queries, &data[opt_index], 4);
nr_queries = be32toh (nr_queries);
opt_index += 4;
/* for LIST: nr_queries == 0 means return all meta contexts
* for SET: nr_queries == 0 means reset all contexts
*/
debug ("newstyle negotiation: %s: %s count: %d", optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
nr_queries);
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = false;
if (nr_queries == 0) {
if (option == NBD_OPT_LIST_META_CONTEXT) {
if (send_newstyle_option_reply_meta_context (option,
NBD_REP_META_CONTEXT,
0, "base:allocation")
== -1)
return -1;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
}
else {
/* Read and answer each query. */
while (nr_queries > 0) {
what = "reading query string length";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&querylen, &data[opt_index], 4);
querylen = be32toh (querylen);
opt_index += 4;
what = "reading query string";
if (check_string (option, &data[opt_index], querylen,
optlen - opt_index, "meta context query") == -1)
goto opt_meta_invalid_option_len;
debug ("newstyle negotiation: %s: %s %.*s",
optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
(int) querylen, &data[opt_index]);
/* For LIST, "base:" returns all supported contexts in the
* base namespace. We only support "base:allocation".
*/
if (option == NBD_OPT_LIST_META_CONTEXT &&
querylen == 5 &&
strncmp (&data[opt_index], "base:", 5) == 0) {
if (send_newstyle_option_reply_meta_context
(option, NBD_REP_META_CONTEXT,
0, "base:allocation") == -1)
return -1;
}
/* "base:allocation" requested by name. */
else if (querylen == 15 &&
strncmp (&data[opt_index], "base:allocation", 15) == 0) {
if (send_newstyle_option_reply_meta_context
(option, NBD_REP_META_CONTEXT,
option == NBD_OPT_SET_META_CONTEXT
? base_allocation_id : 0,
"base:allocation") == -1)
return -1;
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = true;
}
/* Every other query must be ignored. */
opt_index += querylen;
nr_queries--;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
}
debug ("newstyle negotiation: %s: reply complete", optname);
}
break;
default:
/* Unknown option. */
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)
return -1;
if (conn_recv_full (data, optlen,
"reading unknown option data: conn->recv: %m") == -1)
return -1;
}
/* Note, since it's not very clear from the protocol doc, that the
* client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and
* that ends option negotiation.
*/
if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)
break;
}
if (nr_options == 0) {
nbdkit_error ("client spent too much time negotiating without selecting "
"an export");
return -1;
}
/* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS
* by the time we finish option negotiation. If not, give up.
*/
if (tls == 2 && !conn->using_tls) {
nbdkit_error ("non-TLS client tried to connect in --tls=require mode");
return -1;
}
return 0;
}
|
230092713719482299459555478858076762309
|
protocol-handshake-newstyle.c
|
263209595426945567952192628081217546469
|
CWE-924
|
CVE-2021-3716
|
A flaw was found in nbdkit due to to improperly caching plaintext state across the STARTTLS encryption boundary. A MitM attacker could use this flaw to inject a plaintext NBD_OPT_STRUCTURED_REPLY before proxying everything else a client sends to the server, potentially leading the client to terminate the NBD session. The highest threat from this vulnerability is to system availability.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-3716
|
384,677
|
nbdkit
|
6c5faac6a37077cf2366388a80862bb00616d0d8
|
https://github.com/libguestfs/nbdkit
|
https://gitlab.com/nbdkit/nbdkit/-/commit/6c5faac6a37077cf2366388a80862bb00616d0d8
|
server: reset meta context replies on starttls
Related to CVE-2021-3716, but not as severe. No compliant client will
send NBD_CMD_BLOCK_STATUS unless it first negotiates
NBD_OPT_SET_META_CONTEXT. If an attacker injects a premature
SET_META_CONTEXT, either the client will never notice (because it
never uses BLOCK_STATUS), or the client will overwrite the attacker's
attempt with the client's own SET_META_CONTEXT request after
encryption is enabled. So I don't class this as having the potential
to trigger denial-of-service due to any protocol mismatch between
compliant client and server (I don't care what happens with
non-compliant clients).
Fixes: 26455d45 (server: protocol: Implement Block Status "base:allocation".)
| 0
|
negotiate_handshake_newstyle_options (void)
{
GET_CONN;
struct nbd_new_option new_option;
size_t nr_options;
bool list_seen = false;
uint64_t version;
uint32_t option;
uint32_t optlen;
struct nbd_export_name_option_reply handshake_finish;
const char *optname;
uint64_t exportsize;
struct backend *b;
for (nr_options = MAX_NR_OPTIONS; nr_options > 0; --nr_options) {
CLEANUP_FREE char *data = NULL;
if (conn_recv_full (&new_option, sizeof new_option,
"reading option: conn->recv: %m") == -1)
return -1;
version = be64toh (new_option.version);
if (version != NBD_NEW_VERSION) {
nbdkit_error ("unknown option version %" PRIx64
", expecting %" PRIx64,
version, NBD_NEW_VERSION);
return -1;
}
/* There is a maximum option length we will accept, regardless
* of the option type.
*/
optlen = be32toh (new_option.optlen);
if (optlen > MAX_REQUEST_SIZE) {
nbdkit_error ("client option data too long (%" PRIu32 ")", optlen);
return -1;
}
data = malloc (optlen + 1); /* Allowing a trailing NUL helps some uses */
if (data == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
option = be32toh (new_option.option);
optname = name_of_nbd_opt (option);
/* If the client lacks fixed newstyle support, it should only send
* NBD_OPT_EXPORT_NAME.
*/
if (!(conn->cflags & NBD_FLAG_FIXED_NEWSTYLE) &&
option != NBD_OPT_EXPORT_NAME) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID))
return -1;
continue;
}
/* In --tls=require / FORCEDTLS mode the only options allowed
* before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.
*/
if (tls == 2 && !conn->using_tls &&
!(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_TLS_REQD))
return -1;
continue;
}
switch (option) {
case NBD_OPT_EXPORT_NAME:
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
if (check_export_name (option, data, optlen, optlen) == -1)
return -1;
/* We have to finish the handshake by sending handshake_finish.
* On failure, we have to disconnect.
*/
if (finish_newstyle_options (&exportsize, data, optlen) == -1)
return -1;
memset (&handshake_finish, 0, sizeof handshake_finish);
handshake_finish.exportsize = htobe64 (exportsize);
handshake_finish.eflags = htobe16 (conn->eflags);
if (conn->send (&handshake_finish,
(conn->cflags & NBD_FLAG_NO_ZEROES)
? offsetof (struct nbd_export_name_option_reply, zeroes)
: sizeof handshake_finish, 0) == -1) {
nbdkit_error ("write: %s: %m", optname);
return -1;
}
break;
case NBD_OPT_ABORT:
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
debug ("client sent %s to abort the connection",
name_of_nbd_opt (option));
return -1;
case NBD_OPT_LIST:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (list_seen) {
debug ("newstyle negotiation: %s: export list already advertised",
name_of_nbd_opt (option));
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
else {
/* Send back the exportname list. */
debug ("newstyle negotiation: %s: advertising exports",
name_of_nbd_opt (option));
if (send_newstyle_option_reply_exportnames (option, &nr_options) == -1)
return -1;
list_seen = true;
}
break;
case NBD_OPT_STARTTLS:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (tls == 0) { /* --tls=off (NOTLS mode). */
#ifdef HAVE_GNUTLS
#define NO_TLS_REPLY NBD_REP_ERR_POLICY
#else
#define NO_TLS_REPLY NBD_REP_ERR_UNSUP
#endif
if (send_newstyle_option_reply (option, NO_TLS_REPLY) == -1)
return -1;
}
else /* --tls=on or --tls=require */ {
/* We can't upgrade to TLS twice on the same connection. */
if (conn->using_tls) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
/* We have to send the (unencrypted) reply before starting
* the handshake.
*/
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
/* Upgrade the connection to TLS. Also performs access control. */
if (crypto_negotiate_tls (conn->sockin, conn->sockout) == -1)
return -1;
conn->using_tls = true;
debug ("using TLS on this connection");
/* Wipe out any cached state. */
conn->structured_replies = false;
free (conn->exportname_from_set_meta_context);
conn->exportname_from_set_meta_context = NULL;
conn->meta_context_base_allocation = false;
for_each_backend (b) {
free (conn->default_exportname[b->i]);
conn->default_exportname[b->i] = NULL;
}
}
break;
case NBD_OPT_INFO:
case NBD_OPT_GO:
if (conn_recv_full (data, optlen, "read: %s: %m", optname) == -1)
return -1;
if (optlen < 6) { /* 32 bit export length + 16 bit nr info */
debug ("newstyle negotiation: %s option length < 6", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
{
uint32_t exportnamelen;
uint16_t nrinfos;
uint16_t info;
size_t i;
/* Validate the name length and number of INFO requests. */
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {
debug ("newstyle negotiation: %s: export name too long", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&nrinfos, &data[exportnamelen+4], 2);
nrinfos = be16toh (nrinfos);
if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {
debug ("newstyle negotiation: %s: "
"number of information requests incorrect", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* As with NBD_OPT_EXPORT_NAME we print the export name and
* save it in the connection. If an earlier
* NBD_OPT_SET_META_CONTEXT used an export name, it must match
* or else we drop the support for that context.
*/
if (check_export_name (option, &data[4], exportnamelen,
optlen - 6) == -1) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* The spec is confusing, but it is required that we send back
* NBD_INFO_EXPORT, even if the client did not request it!
* qemu client in particular does not request this, but will
* fail if we don't send it. Note that if .open fails, but we
* succeed at .close, then we merely return an error to the
* client and let them try another NBD_OPT, rather than
* disconnecting.
*/
if (finish_newstyle_options (&exportsize,
&data[4], exportnamelen) == -1) {
if (conn->top_context) {
if (backend_finalize (conn->top_context) == -1)
return -1;
backend_close (conn->top_context);
conn->top_context = NULL;
}
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNKNOWN) == -1)
return -1;
continue;
}
if (send_newstyle_option_reply_info_export (option,
NBD_REP_INFO,
NBD_INFO_EXPORT,
exportsize) == -1)
return -1;
/* For now we send NBD_INFO_NAME and NBD_INFO_DESCRIPTION if
* requested, and ignore all other info requests (including
* NBD_INFO_EXPORT if it was requested, because we replied
* already above).
*/
for (i = 0; i < nrinfos; ++i) {
memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);
info = be16toh (info);
switch (info) {
case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;
case NBD_INFO_NAME:
{
const char *name = &data[4];
size_t namelen = exportnamelen;
if (exportnamelen == 0) {
name = backend_default_export (top, read_only);
if (!name) {
debug ("newstyle negotiation: %s: "
"NBD_INFO_NAME: no name to send", optname);
break;
}
namelen = -1;
}
if (send_newstyle_option_reply_info_str (option,
NBD_REP_INFO,
NBD_INFO_NAME,
name, namelen) == -1)
return -1;
}
break;
case NBD_INFO_DESCRIPTION:
{
const char *desc = backend_export_description (conn->top_context);
if (!desc) {
debug ("newstyle negotiation: %s: "
"NBD_INFO_DESCRIPTION: no description to send",
optname);
break;
}
if (send_newstyle_option_reply_info_str (option,
NBD_REP_INFO,
NBD_INFO_DESCRIPTION,
desc, -1) == -1)
return -1;
}
break;
default:
debug ("newstyle negotiation: %s: "
"ignoring NBD_INFO_* request %u (%s)",
optname, (unsigned) info, name_of_nbd_info (info));
break;
}
}
}
/* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK
* or ERROR packet. If this was NBD_OPT_LIST, call .close.
*/
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
if (option == NBD_OPT_INFO) {
if (backend_finalize (conn->top_context) == -1)
return -1;
backend_close (conn->top_context);
conn->top_context = NULL;
}
break;
case NBD_OPT_STRUCTURED_REPLY:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
debug ("newstyle negotiation: %s: client requested structured replies",
name_of_nbd_opt (option));
if (no_sr) {
/* Must fail with ERR_UNSUP for qemu 4.2 to remain happy;
* but failing with ERR_POLICY would have been nicer.
*/
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)
return -1;
debug ("newstyle negotiation: %s: structured replies are disabled",
name_of_nbd_opt (option));
break;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
conn->structured_replies = true;
break;
case NBD_OPT_LIST_META_CONTEXT:
case NBD_OPT_SET_META_CONTEXT:
{
uint32_t opt_index;
uint32_t exportnamelen;
uint32_t nr_queries;
uint32_t querylen;
const char *what;
if (conn_recv_full (data, optlen, "read: %s: %m", optname) == -1)
return -1;
/* Note that we support base:allocation whether or not the plugin
* supports can_extents.
*/
if (!conn->structured_replies) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* Minimum length of the option payload is:
* 32 bit export name length followed by empty export name
* + 32 bit number of queries followed by no queries
* = 8 bytes.
*/
what = "optlen < 8";
if (optlen < 8) {
opt_meta_invalid_option_len:
debug ("newstyle negotiation: %s: invalid option length: %s",
optname, what);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
what = "validating export name";
if (check_export_name (option, &data[4], exportnamelen,
optlen - 8) == -1)
goto opt_meta_invalid_option_len;
/* Remember the export name: the NBD spec says that if the client
* later uses NBD_OPT_GO on a different export, then the context
* returned here is not usable.
*/
if (option == NBD_OPT_SET_META_CONTEXT) {
conn->exportname_from_set_meta_context =
strndup (&data[4], exportnamelen);
if (conn->exportname_from_set_meta_context == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
}
opt_index = 4 + exportnamelen;
/* Read the number of queries. */
what = "reading number of queries";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&nr_queries, &data[opt_index], 4);
nr_queries = be32toh (nr_queries);
opt_index += 4;
/* for LIST: nr_queries == 0 means return all meta contexts
* for SET: nr_queries == 0 means reset all contexts
*/
debug ("newstyle negotiation: %s: %s count: %d", optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
nr_queries);
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = false;
if (nr_queries == 0) {
if (option == NBD_OPT_LIST_META_CONTEXT) {
if (send_newstyle_option_reply_meta_context (option,
NBD_REP_META_CONTEXT,
0, "base:allocation")
== -1)
return -1;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
}
else {
/* Read and answer each query. */
while (nr_queries > 0) {
what = "reading query string length";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&querylen, &data[opt_index], 4);
querylen = be32toh (querylen);
opt_index += 4;
what = "reading query string";
if (check_string (option, &data[opt_index], querylen,
optlen - opt_index, "meta context query") == -1)
goto opt_meta_invalid_option_len;
debug ("newstyle negotiation: %s: %s %.*s",
optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
(int) querylen, &data[opt_index]);
/* For LIST, "base:" returns all supported contexts in the
* base namespace. We only support "base:allocation".
*/
if (option == NBD_OPT_LIST_META_CONTEXT &&
querylen == 5 &&
strncmp (&data[opt_index], "base:", 5) == 0) {
if (send_newstyle_option_reply_meta_context
(option, NBD_REP_META_CONTEXT,
0, "base:allocation") == -1)
return -1;
}
/* "base:allocation" requested by name. */
else if (querylen == 15 &&
strncmp (&data[opt_index], "base:allocation", 15) == 0) {
if (send_newstyle_option_reply_meta_context
(option, NBD_REP_META_CONTEXT,
option == NBD_OPT_SET_META_CONTEXT
? base_allocation_id : 0,
"base:allocation") == -1)
return -1;
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = true;
}
/* Every other query must be ignored. */
opt_index += querylen;
nr_queries--;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
}
debug ("newstyle negotiation: %s: reply complete", optname);
}
break;
default:
/* Unknown option. */
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)
return -1;
if (conn_recv_full (data, optlen,
"reading unknown option data: conn->recv: %m") == -1)
return -1;
}
/* Note, since it's not very clear from the protocol doc, that the
* client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and
* that ends option negotiation.
*/
if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)
break;
}
if (nr_options == 0) {
nbdkit_error ("client spent too much time negotiating without selecting "
"an export");
return -1;
}
/* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS
* by the time we finish option negotiation. If not, give up.
*/
if (tls == 2 && !conn->using_tls) {
nbdkit_error ("non-TLS client tried to connect in --tls=require mode");
return -1;
}
return 0;
}
|
13793654971535202622888110493636437287
|
protocol-handshake-newstyle.c
|
210643238405506282504328455056206224474
|
CWE-924
|
CVE-2021-3716
|
A flaw was found in nbdkit due to to improperly caching plaintext state across the STARTTLS encryption boundary. A MitM attacker could use this flaw to inject a plaintext NBD_OPT_STRUCTURED_REPLY before proxying everything else a client sends to the server, potentially leading the client to terminate the NBD session. The highest threat from this vulnerability is to system availability.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-3716
|
206,676
|
vim
|
777e7c21b7627be80961848ac560cb0a9978ff43
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/777e7c21b7627be80961848ac560cb0a9978ff43
|
patch 8.2.3564: invalid memory access when scrolling without valid screen
Problem: Invalid memory access when scrolling without a valid screen.
Solution: Do not set VALID_BOTLINE in w_valid.
| 1
|
update_topline(void)
{
long line_count;
int halfheight;
int n;
linenr_T old_topline;
#ifdef FEAT_DIFF
int old_topfill;
#endif
#ifdef FEAT_FOLDING
linenr_T lnum;
#endif
int check_topline = FALSE;
int check_botline = FALSE;
long *so_ptr = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so;
int save_so = *so_ptr;
// If there is no valid screen and when the window height is zero just use
// the cursor line.
if (!screen_valid(TRUE) || curwin->w_height == 0)
{
check_cursor_lnum();
curwin->w_topline = curwin->w_cursor.lnum;
curwin->w_botline = curwin->w_topline;
curwin->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;
curwin->w_scbind_pos = 1;
return;
}
check_cursor_moved(curwin);
if (curwin->w_valid & VALID_TOPLINE)
return;
// When dragging with the mouse, don't scroll that quickly
if (mouse_dragging > 0)
*so_ptr = mouse_dragging - 1;
old_topline = curwin->w_topline;
#ifdef FEAT_DIFF
old_topfill = curwin->w_topfill;
#endif
/*
* If the buffer is empty, always set topline to 1.
*/
if (BUFEMPTY()) // special case - file is empty
{
if (curwin->w_topline != 1)
redraw_later(NOT_VALID);
curwin->w_topline = 1;
curwin->w_botline = 2;
curwin->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;
curwin->w_scbind_pos = 1;
}
/*
* If the cursor is above or near the top of the window, scroll the window
* to show the line the cursor is in, with 'scrolloff' context.
*/
else
{
if (curwin->w_topline > 1)
{
// If the cursor is above topline, scrolling is always needed.
// If the cursor is far below topline and there is no folding,
// scrolling down is never needed.
if (curwin->w_cursor.lnum < curwin->w_topline)
check_topline = TRUE;
else if (check_top_offset())
check_topline = TRUE;
}
#ifdef FEAT_DIFF
// Check if there are more filler lines than allowed.
if (!check_topline && curwin->w_topfill > diff_check_fill(curwin,
curwin->w_topline))
check_topline = TRUE;
#endif
if (check_topline)
{
halfheight = curwin->w_height / 2 - 1;
if (halfheight < 2)
halfheight = 2;
#ifdef FEAT_FOLDING
if (hasAnyFolding(curwin))
{
// Count the number of logical lines between the cursor and
// topline + scrolloff (approximation of how much will be
// scrolled).
n = 0;
for (lnum = curwin->w_cursor.lnum;
lnum < curwin->w_topline + *so_ptr; ++lnum)
{
++n;
// stop at end of file or when we know we are far off
if (lnum >= curbuf->b_ml.ml_line_count || n >= halfheight)
break;
(void)hasFolding(lnum, NULL, &lnum);
}
}
else
#endif
n = curwin->w_topline + *so_ptr - curwin->w_cursor.lnum;
// If we weren't very close to begin with, we scroll to put the
// cursor in the middle of the window. Otherwise put the cursor
// near the top of the window.
if (n >= halfheight)
scroll_cursor_halfway(FALSE);
else
{
scroll_cursor_top(scrolljump_value(), FALSE);
check_botline = TRUE;
}
}
else
{
#ifdef FEAT_FOLDING
// Make sure topline is the first line of a fold.
(void)hasFolding(curwin->w_topline, &curwin->w_topline, NULL);
#endif
check_botline = TRUE;
}
}
/*
* If the cursor is below the bottom of the window, scroll the window
* to put the cursor on the window.
* When w_botline is invalid, recompute it first, to avoid a redraw later.
* If w_botline was approximated, we might need a redraw later in a few
* cases, but we don't want to spend (a lot of) time recomputing w_botline
* for every small change.
*/
if (check_botline)
{
if (!(curwin->w_valid & VALID_BOTLINE_AP))
validate_botline();
if (curwin->w_botline <= curbuf->b_ml.ml_line_count)
{
if (curwin->w_cursor.lnum < curwin->w_botline)
{
if (((long)curwin->w_cursor.lnum
>= (long)curwin->w_botline - *so_ptr
#ifdef FEAT_FOLDING
|| hasAnyFolding(curwin)
#endif
))
{
lineoff_T loff;
// Cursor is (a few lines) above botline, check if there are
// 'scrolloff' window lines below the cursor. If not, need to
// scroll.
n = curwin->w_empty_rows;
loff.lnum = curwin->w_cursor.lnum;
#ifdef FEAT_FOLDING
// In a fold go to its last line.
(void)hasFolding(loff.lnum, NULL, &loff.lnum);
#endif
#ifdef FEAT_DIFF
loff.fill = 0;
n += curwin->w_filler_rows;
#endif
loff.height = 0;
while (loff.lnum < curwin->w_botline
#ifdef FEAT_DIFF
&& (loff.lnum + 1 < curwin->w_botline || loff.fill == 0)
#endif
)
{
n += loff.height;
if (n >= *so_ptr)
break;
botline_forw(&loff);
}
if (n >= *so_ptr)
// sufficient context, no need to scroll
check_botline = FALSE;
}
else
// sufficient context, no need to scroll
check_botline = FALSE;
}
if (check_botline)
{
#ifdef FEAT_FOLDING
if (hasAnyFolding(curwin))
{
// Count the number of logical lines between the cursor and
// botline - scrolloff (approximation of how much will be
// scrolled).
line_count = 0;
for (lnum = curwin->w_cursor.lnum;
lnum >= curwin->w_botline - *so_ptr; --lnum)
{
++line_count;
// stop at end of file or when we know we are far off
if (lnum <= 0 || line_count > curwin->w_height + 1)
break;
(void)hasFolding(lnum, &lnum, NULL);
}
}
else
#endif
line_count = curwin->w_cursor.lnum - curwin->w_botline
+ 1 + *so_ptr;
if (line_count <= curwin->w_height + 1)
scroll_cursor_bot(scrolljump_value(), FALSE);
else
scroll_cursor_halfway(FALSE);
}
}
}
curwin->w_valid |= VALID_TOPLINE;
/*
* Need to redraw when topline changed.
*/
if (curwin->w_topline != old_topline
#ifdef FEAT_DIFF
|| curwin->w_topfill != old_topfill
#endif
)
{
dollar_vcol = -1;
if (curwin->w_skipcol != 0)
{
curwin->w_skipcol = 0;
redraw_later(NOT_VALID);
}
else
redraw_later(VALID);
// May need to set w_skipcol when cursor in w_topline.
if (curwin->w_cursor.lnum == curwin->w_topline)
validate_cursor();
}
*so_ptr = save_so;
}
|
228543629723963000813717359055705778977
|
move.c
|
235877722919937919149866597040080656666
|
CWE-122
|
CVE-2021-3903
|
vim is vulnerable to Heap-based Buffer Overflow
|
https://nvd.nist.gov/vuln/detail/CVE-2021-3903
|
384,767
|
vim
|
777e7c21b7627be80961848ac560cb0a9978ff43
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/777e7c21b7627be80961848ac560cb0a9978ff43
|
patch 8.2.3564: invalid memory access when scrolling without valid screen
Problem: Invalid memory access when scrolling without a valid screen.
Solution: Do not set VALID_BOTLINE in w_valid.
| 0
|
update_topline(void)
{
long line_count;
int halfheight;
int n;
linenr_T old_topline;
#ifdef FEAT_DIFF
int old_topfill;
#endif
#ifdef FEAT_FOLDING
linenr_T lnum;
#endif
int check_topline = FALSE;
int check_botline = FALSE;
long *so_ptr = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so;
int save_so = *so_ptr;
// If there is no valid screen and when the window height is zero just use
// the cursor line.
if (!screen_valid(TRUE) || curwin->w_height == 0)
{
check_cursor_lnum();
curwin->w_topline = curwin->w_cursor.lnum;
curwin->w_botline = curwin->w_topline;
curwin->w_scbind_pos = 1;
return;
}
check_cursor_moved(curwin);
if (curwin->w_valid & VALID_TOPLINE)
return;
// When dragging with the mouse, don't scroll that quickly
if (mouse_dragging > 0)
*so_ptr = mouse_dragging - 1;
old_topline = curwin->w_topline;
#ifdef FEAT_DIFF
old_topfill = curwin->w_topfill;
#endif
/*
* If the buffer is empty, always set topline to 1.
*/
if (BUFEMPTY()) // special case - file is empty
{
if (curwin->w_topline != 1)
redraw_later(NOT_VALID);
curwin->w_topline = 1;
curwin->w_botline = 2;
curwin->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;
curwin->w_scbind_pos = 1;
}
/*
* If the cursor is above or near the top of the window, scroll the window
* to show the line the cursor is in, with 'scrolloff' context.
*/
else
{
if (curwin->w_topline > 1)
{
// If the cursor is above topline, scrolling is always needed.
// If the cursor is far below topline and there is no folding,
// scrolling down is never needed.
if (curwin->w_cursor.lnum < curwin->w_topline)
check_topline = TRUE;
else if (check_top_offset())
check_topline = TRUE;
}
#ifdef FEAT_DIFF
// Check if there are more filler lines than allowed.
if (!check_topline && curwin->w_topfill > diff_check_fill(curwin,
curwin->w_topline))
check_topline = TRUE;
#endif
if (check_topline)
{
halfheight = curwin->w_height / 2 - 1;
if (halfheight < 2)
halfheight = 2;
#ifdef FEAT_FOLDING
if (hasAnyFolding(curwin))
{
// Count the number of logical lines between the cursor and
// topline + scrolloff (approximation of how much will be
// scrolled).
n = 0;
for (lnum = curwin->w_cursor.lnum;
lnum < curwin->w_topline + *so_ptr; ++lnum)
{
++n;
// stop at end of file or when we know we are far off
if (lnum >= curbuf->b_ml.ml_line_count || n >= halfheight)
break;
(void)hasFolding(lnum, NULL, &lnum);
}
}
else
#endif
n = curwin->w_topline + *so_ptr - curwin->w_cursor.lnum;
// If we weren't very close to begin with, we scroll to put the
// cursor in the middle of the window. Otherwise put the cursor
// near the top of the window.
if (n >= halfheight)
scroll_cursor_halfway(FALSE);
else
{
scroll_cursor_top(scrolljump_value(), FALSE);
check_botline = TRUE;
}
}
else
{
#ifdef FEAT_FOLDING
// Make sure topline is the first line of a fold.
(void)hasFolding(curwin->w_topline, &curwin->w_topline, NULL);
#endif
check_botline = TRUE;
}
}
/*
* If the cursor is below the bottom of the window, scroll the window
* to put the cursor on the window.
* When w_botline is invalid, recompute it first, to avoid a redraw later.
* If w_botline was approximated, we might need a redraw later in a few
* cases, but we don't want to spend (a lot of) time recomputing w_botline
* for every small change.
*/
if (check_botline)
{
if (!(curwin->w_valid & VALID_BOTLINE_AP))
validate_botline();
if (curwin->w_botline <= curbuf->b_ml.ml_line_count)
{
if (curwin->w_cursor.lnum < curwin->w_botline)
{
if (((long)curwin->w_cursor.lnum
>= (long)curwin->w_botline - *so_ptr
#ifdef FEAT_FOLDING
|| hasAnyFolding(curwin)
#endif
))
{
lineoff_T loff;
// Cursor is (a few lines) above botline, check if there are
// 'scrolloff' window lines below the cursor. If not, need to
// scroll.
n = curwin->w_empty_rows;
loff.lnum = curwin->w_cursor.lnum;
#ifdef FEAT_FOLDING
// In a fold go to its last line.
(void)hasFolding(loff.lnum, NULL, &loff.lnum);
#endif
#ifdef FEAT_DIFF
loff.fill = 0;
n += curwin->w_filler_rows;
#endif
loff.height = 0;
while (loff.lnum < curwin->w_botline
#ifdef FEAT_DIFF
&& (loff.lnum + 1 < curwin->w_botline || loff.fill == 0)
#endif
)
{
n += loff.height;
if (n >= *so_ptr)
break;
botline_forw(&loff);
}
if (n >= *so_ptr)
// sufficient context, no need to scroll
check_botline = FALSE;
}
else
// sufficient context, no need to scroll
check_botline = FALSE;
}
if (check_botline)
{
#ifdef FEAT_FOLDING
if (hasAnyFolding(curwin))
{
// Count the number of logical lines between the cursor and
// botline - scrolloff (approximation of how much will be
// scrolled).
line_count = 0;
for (lnum = curwin->w_cursor.lnum;
lnum >= curwin->w_botline - *so_ptr; --lnum)
{
++line_count;
// stop at end of file or when we know we are far off
if (lnum <= 0 || line_count > curwin->w_height + 1)
break;
(void)hasFolding(lnum, &lnum, NULL);
}
}
else
#endif
line_count = curwin->w_cursor.lnum - curwin->w_botline
+ 1 + *so_ptr;
if (line_count <= curwin->w_height + 1)
scroll_cursor_bot(scrolljump_value(), FALSE);
else
scroll_cursor_halfway(FALSE);
}
}
}
curwin->w_valid |= VALID_TOPLINE;
/*
* Need to redraw when topline changed.
*/
if (curwin->w_topline != old_topline
#ifdef FEAT_DIFF
|| curwin->w_topfill != old_topfill
#endif
)
{
dollar_vcol = -1;
if (curwin->w_skipcol != 0)
{
curwin->w_skipcol = 0;
redraw_later(NOT_VALID);
}
else
redraw_later(VALID);
// May need to set w_skipcol when cursor in w_topline.
if (curwin->w_cursor.lnum == curwin->w_topline)
validate_cursor();
}
*so_ptr = save_so;
}
|
318695242827135485367008238388311307871
|
move.c
|
216110417083492209479100354226379064539
|
CWE-122
|
CVE-2021-3903
|
vim is vulnerable to Heap-based Buffer Overflow
|
https://nvd.nist.gov/vuln/detail/CVE-2021-3903
|
206,677
|
vim
|
5921aeb5741fc6e84c870d68c7c35b93ad0c9f87
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/5921aeb5741fc6e84c870d68c7c35b93ad0c9f87
|
patch 8.2.4418: crash when using special multi-byte character
Problem: Crash when using special multi-byte character.
Solution: Don't use isalpha() for an arbitrary character.
| 1
|
unix_expandpath(
garray_T *gap,
char_u *path,
int wildoff,
int flags, // EW_* flags
int didstar) // expanded "**" once already
{
char_u *buf;
char_u *path_end;
char_u *p, *s, *e;
int start_len = gap->ga_len;
char_u *pat;
regmatch_T regmatch;
int starts_with_dot;
int matches;
int len;
int starstar = FALSE;
static int stardepth = 0; // depth for "**" expansion
DIR *dirp;
struct dirent *dp;
// Expanding "**" may take a long time, check for CTRL-C.
if (stardepth > 0)
{
ui_breakcheck();
if (got_int)
return 0;
}
// make room for file name
buf = alloc(STRLEN(path) + BASENAMELEN + 5);
if (buf == NULL)
return 0;
/*
* Find the first part in the path name that contains a wildcard.
* When EW_ICASE is set every letter is considered to be a wildcard.
* Copy it into "buf", including the preceding characters.
*/
p = buf;
s = buf;
e = NULL;
path_end = path;
while (*path_end != NUL)
{
// May ignore a wildcard that has a backslash before it; it will
// be removed by rem_backslash() or file_pat_to_reg_pat() below.
if (path_end >= path + wildoff && rem_backslash(path_end))
*p++ = *path_end++;
else if (*path_end == '/')
{
if (e != NULL)
break;
s = p + 1;
}
else if (path_end >= path + wildoff
&& (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
|| (!p_fic && (flags & EW_ICASE)
&& isalpha(PTR2CHAR(path_end)))))
e = p;
if (has_mbyte)
{
len = (*mb_ptr2len)(path_end);
STRNCPY(p, path_end, len);
p += len;
path_end += len;
}
else
*p++ = *path_end++;
}
e = p;
*e = NUL;
// Now we have one wildcard component between "s" and "e".
// Remove backslashes between "wildoff" and the start of the wildcard
// component.
for (p = buf + wildoff; p < s; ++p)
if (rem_backslash(p))
{
STRMOVE(p, p + 1);
--e;
--s;
}
// Check for "**" between "s" and "e".
for (p = s; p < e; ++p)
if (p[0] == '*' && p[1] == '*')
starstar = TRUE;
// convert the file pattern to a regexp pattern
starts_with_dot = *s == '.';
pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
if (pat == NULL)
{
vim_free(buf);
return 0;
}
// compile the regexp into a program
if (flags & EW_ICASE)
regmatch.rm_ic = TRUE; // 'wildignorecase' set
else
regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
if (flags & (EW_NOERROR | EW_NOTWILD))
++emsg_silent;
regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
if (flags & (EW_NOERROR | EW_NOTWILD))
--emsg_silent;
vim_free(pat);
if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
{
vim_free(buf);
return 0;
}
// If "**" is by itself, this is the first time we encounter it and more
// is following then find matches without any directory.
if (!didstar && stardepth < 100 && starstar && e - s == 2
&& *path_end == '/')
{
STRCPY(s, path_end + 1);
++stardepth;
(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
--stardepth;
}
// open the directory for scanning
*s = NUL;
dirp = opendir(*buf == NUL ? "." : (char *)buf);
// Find all matching entries
if (dirp != NULL)
{
for (;;)
{
dp = readdir(dirp);
if (dp == NULL)
break;
if ((dp->d_name[0] != '.' || starts_with_dot
|| ((flags & EW_DODOT)
&& dp->d_name[1] != NUL
&& (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
&& ((regmatch.regprog != NULL && vim_regexec(®match,
(char_u *)dp->d_name, (colnr_T)0))
|| ((flags & EW_NOTWILD)
&& fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
{
STRCPY(s, dp->d_name);
len = STRLEN(buf);
if (starstar && stardepth < 100)
{
// For "**" in the pattern first go deeper in the tree to
// find matches.
STRCPY(buf + len, "/**");
STRCPY(buf + len + 3, path_end);
++stardepth;
(void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
--stardepth;
}
STRCPY(buf + len, path_end);
if (mch_has_exp_wildcard(path_end)) // handle more wildcards
{
// need to expand another component of the path
// remove backslashes for the remaining components only
(void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
}
else
{
stat_T sb;
// no more wildcards, check if there is a match
// remove backslashes for the remaining components only
if (*path_end != NUL)
backslash_halve(buf + len + 1);
// add existing file or symbolic link
if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
: mch_getperm(buf) >= 0)
{
#ifdef MACOS_CONVERT
size_t precomp_len = STRLEN(buf)+1;
char_u *precomp_buf =
mac_precompose_path(buf, precomp_len, &precomp_len);
if (precomp_buf)
{
mch_memmove(buf, precomp_buf, precomp_len);
vim_free(precomp_buf);
}
#endif
addfile(gap, buf, flags);
}
}
}
}
closedir(dirp);
}
vim_free(buf);
vim_regfree(regmatch.regprog);
matches = gap->ga_len - start_len;
if (matches > 0)
qsort(((char_u **)gap->ga_data) + start_len, matches,
sizeof(char_u *), pstrcmp);
return matches;
}
|
312674114892145176500352390912517515307
|
filepath.c
|
229066241137802797352238773426978474827
|
CWE-703
|
CVE-2022-0685
|
Use of Out-of-range Pointer Offset in GitHub repository vim/vim prior to 8.2.4418.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0685
|
384,803
|
vim
|
5921aeb5741fc6e84c870d68c7c35b93ad0c9f87
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/5921aeb5741fc6e84c870d68c7c35b93ad0c9f87
|
patch 8.2.4418: crash when using special multi-byte character
Problem: Crash when using special multi-byte character.
Solution: Don't use isalpha() for an arbitrary character.
| 0
|
unix_expandpath(
garray_T *gap,
char_u *path,
int wildoff,
int flags, // EW_* flags
int didstar) // expanded "**" once already
{
char_u *buf;
char_u *path_end;
char_u *p, *s, *e;
int start_len = gap->ga_len;
char_u *pat;
regmatch_T regmatch;
int starts_with_dot;
int matches;
int len;
int starstar = FALSE;
static int stardepth = 0; // depth for "**" expansion
DIR *dirp;
struct dirent *dp;
// Expanding "**" may take a long time, check for CTRL-C.
if (stardepth > 0)
{
ui_breakcheck();
if (got_int)
return 0;
}
// make room for file name
buf = alloc(STRLEN(path) + BASENAMELEN + 5);
if (buf == NULL)
return 0;
/*
* Find the first part in the path name that contains a wildcard.
* When EW_ICASE is set every letter is considered to be a wildcard.
* Copy it into "buf", including the preceding characters.
*/
p = buf;
s = buf;
e = NULL;
path_end = path;
while (*path_end != NUL)
{
// May ignore a wildcard that has a backslash before it; it will
// be removed by rem_backslash() or file_pat_to_reg_pat() below.
if (path_end >= path + wildoff && rem_backslash(path_end))
*p++ = *path_end++;
else if (*path_end == '/')
{
if (e != NULL)
break;
s = p + 1;
}
else if (path_end >= path + wildoff
&& (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
|| (!p_fic && (flags & EW_ICASE)
&& vim_isalpha(PTR2CHAR(path_end)))))
e = p;
if (has_mbyte)
{
len = (*mb_ptr2len)(path_end);
STRNCPY(p, path_end, len);
p += len;
path_end += len;
}
else
*p++ = *path_end++;
}
e = p;
*e = NUL;
// Now we have one wildcard component between "s" and "e".
// Remove backslashes between "wildoff" and the start of the wildcard
// component.
for (p = buf + wildoff; p < s; ++p)
if (rem_backslash(p))
{
STRMOVE(p, p + 1);
--e;
--s;
}
// Check for "**" between "s" and "e".
for (p = s; p < e; ++p)
if (p[0] == '*' && p[1] == '*')
starstar = TRUE;
// convert the file pattern to a regexp pattern
starts_with_dot = *s == '.';
pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
if (pat == NULL)
{
vim_free(buf);
return 0;
}
// compile the regexp into a program
if (flags & EW_ICASE)
regmatch.rm_ic = TRUE; // 'wildignorecase' set
else
regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
if (flags & (EW_NOERROR | EW_NOTWILD))
++emsg_silent;
regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
if (flags & (EW_NOERROR | EW_NOTWILD))
--emsg_silent;
vim_free(pat);
if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
{
vim_free(buf);
return 0;
}
// If "**" is by itself, this is the first time we encounter it and more
// is following then find matches without any directory.
if (!didstar && stardepth < 100 && starstar && e - s == 2
&& *path_end == '/')
{
STRCPY(s, path_end + 1);
++stardepth;
(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
--stardepth;
}
// open the directory for scanning
*s = NUL;
dirp = opendir(*buf == NUL ? "." : (char *)buf);
// Find all matching entries
if (dirp != NULL)
{
for (;;)
{
dp = readdir(dirp);
if (dp == NULL)
break;
if ((dp->d_name[0] != '.' || starts_with_dot
|| ((flags & EW_DODOT)
&& dp->d_name[1] != NUL
&& (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
&& ((regmatch.regprog != NULL && vim_regexec(®match,
(char_u *)dp->d_name, (colnr_T)0))
|| ((flags & EW_NOTWILD)
&& fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
{
STRCPY(s, dp->d_name);
len = STRLEN(buf);
if (starstar && stardepth < 100)
{
// For "**" in the pattern first go deeper in the tree to
// find matches.
STRCPY(buf + len, "/**");
STRCPY(buf + len + 3, path_end);
++stardepth;
(void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
--stardepth;
}
STRCPY(buf + len, path_end);
if (mch_has_exp_wildcard(path_end)) // handle more wildcards
{
// need to expand another component of the path
// remove backslashes for the remaining components only
(void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
}
else
{
stat_T sb;
// no more wildcards, check if there is a match
// remove backslashes for the remaining components only
if (*path_end != NUL)
backslash_halve(buf + len + 1);
// add existing file or symbolic link
if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
: mch_getperm(buf) >= 0)
{
#ifdef MACOS_CONVERT
size_t precomp_len = STRLEN(buf)+1;
char_u *precomp_buf =
mac_precompose_path(buf, precomp_len, &precomp_len);
if (precomp_buf)
{
mch_memmove(buf, precomp_buf, precomp_len);
vim_free(precomp_buf);
}
#endif
addfile(gap, buf, flags);
}
}
}
}
closedir(dirp);
}
vim_free(buf);
vim_regfree(regmatch.regprog);
matches = gap->ga_len - start_len;
if (matches > 0)
qsort(((char_u **)gap->ga_data) + start_len, matches,
sizeof(char_u *), pstrcmp);
return matches;
}
|
314207374277767272342244288300260252688
|
filepath.c
|
268435853121240029622170757643385181583
|
CWE-703
|
CVE-2022-0685
|
Use of Out-of-range Pointer Offset in GitHub repository vim/vim prior to 8.2.4418.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0685
|
206,771
|
qcad
|
1eeffc5daf5a06cf6213ffc19e95923cdebb2eb8
|
https://github.com/qcad/qcad
|
https://github.com/qcad/qcad/commit/1eeffc5daf5a06cf6213ffc19e95923cdebb2eb8
|
check vertexIndex which might be -1 for broken DXF
| 1
|
bool DL_Dxf::handleLWPolylineData(DL_CreationInterface* /*creationInterface*/) {
// Allocate LWPolyline vertices (group code 90):
if (groupCode==90) {
maxVertices = toInt(groupValue);
if (maxVertices>0) {
if (vertices!=NULL) {
delete[] vertices;
}
vertices = new double[4*maxVertices];
for (int i=0; i<maxVertices; ++i) {
vertices[i*4] = 0.0;
vertices[i*4+1] = 0.0;
vertices[i*4+2] = 0.0;
vertices[i*4+3] = 0.0;
}
}
vertexIndex=-1;
return true;
}
// Process LWPolylines vertices (group codes 10/20/30/42):
else if (groupCode==10 || groupCode==20 ||
groupCode==30 || groupCode==42) {
if (vertexIndex<maxVertices-1 && groupCode==10) {
vertexIndex++;
}
if (groupCode<=30) {
if (vertexIndex>=0 && vertexIndex<maxVertices) {
vertices[4*vertexIndex + (groupCode/10-1)] = toReal(groupValue);
}
} else if (groupCode==42 && vertexIndex<maxVertices) {
vertices[4*vertexIndex + 3] = toReal(groupValue);
}
return true;
}
return false;
}
|
109412697930486379897697175336143106380
|
dl_dxf.cpp
|
313944639125792713455398286070640568043
|
CWE-191
|
CVE-2021-21897
|
A code execution vulnerability exists in the DL_Dxf::handleLWPolylineData functionality of Ribbonsoft dxflib 3.17.0. A specially-crafted .dxf file can lead to a heap buffer overflow. An attacker can provide a malicious file to trigger this vulnerability.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-21897
|
386,565
|
qcad
|
1eeffc5daf5a06cf6213ffc19e95923cdebb2eb8
|
https://github.com/qcad/qcad
|
https://github.com/qcad/qcad/commit/1eeffc5daf5a06cf6213ffc19e95923cdebb2eb8
|
check vertexIndex which might be -1 for broken DXF
| 0
|
bool DL_Dxf::handleLWPolylineData(DL_CreationInterface* /*creationInterface*/) {
// Allocate LWPolyline vertices (group code 90):
if (groupCode==90) {
maxVertices = toInt(groupValue);
if (maxVertices>0) {
if (vertices!=NULL) {
delete[] vertices;
}
vertices = new double[4*maxVertices];
for (int i=0; i<maxVertices; ++i) {
vertices[i*4] = 0.0;
vertices[i*4+1] = 0.0;
vertices[i*4+2] = 0.0;
vertices[i*4+3] = 0.0;
}
}
vertexIndex=-1;
return true;
}
// Process LWPolylines vertices (group codes 10/20/30/42):
else if (groupCode==10 || groupCode==20 ||
groupCode==30 || groupCode==42) {
if (vertexIndex<maxVertices-1 && groupCode==10) {
vertexIndex++;
}
if (groupCode<=30) {
if (vertexIndex>=0 && vertexIndex<maxVertices && vertexIndex>=0) {
vertices[4*vertexIndex + (groupCode/10-1)] = toReal(groupValue);
}
} else if (groupCode==42 && vertexIndex<maxVertices && vertexIndex>=0) {
vertices[4*vertexIndex + 3] = toReal(groupValue);
}
return true;
}
return false;
}
|
66825183138389317029314964036422106221
|
dl_dxf.cpp
|
181081005270076491555487324786328968837
|
CWE-191
|
CVE-2021-21897
|
A code execution vulnerability exists in the DL_Dxf::handleLWPolylineData functionality of Ribbonsoft dxflib 3.17.0. A specially-crafted .dxf file can lead to a heap buffer overflow. An attacker can provide a malicious file to trigger this vulnerability.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-21897
|
206,781
|
linux
|
ea8569194b43f0f01f0a84c689388542c7254a1f
|
https://github.com/torvalds/linux
|
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ea8569194b43f0f01f0a84c689388542c7254a1f
|
udf: Restore i_lenAlloc when inode expansion fails
When we fail to expand inode from inline format to a normal format, we
restore inode to contain the original inline formatting but we forgot to
set i_lenAlloc back. The mismatch between i_lenAlloc and i_size was then
causing further problems such as warnings and lost data down the line.
Reported-by: butt3rflyh4ck <[email protected]>
CC: [email protected]
Fixes: 7e49b6f2480c ("udf: Convert UDF to new truncate calling sequence")
Reviewed-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
| 1
|
int udf_expand_file_adinicb(struct inode *inode)
{
struct page *page;
char *kaddr;
struct udf_inode_info *iinfo = UDF_I(inode);
int err;
WARN_ON_ONCE(!inode_is_locked(inode));
if (!iinfo->i_lenAlloc) {
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
up_write(&iinfo->i_data_sem);
mark_inode_dirty(inode);
return 0;
}
/*
* Release i_data_sem so that we can lock a page - page lock ranks
* above i_data_sem. i_mutex still protects us against file changes.
*/
up_write(&iinfo->i_data_sem);
page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS);
if (!page)
return -ENOMEM;
if (!PageUptodate(page)) {
kaddr = kmap_atomic(page);
memset(kaddr + iinfo->i_lenAlloc, 0x00,
PAGE_SIZE - iinfo->i_lenAlloc);
memcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr,
iinfo->i_lenAlloc);
flush_dcache_page(page);
SetPageUptodate(page);
kunmap_atomic(kaddr);
}
down_write(&iinfo->i_data_sem);
memset(iinfo->i_data + iinfo->i_lenEAttr, 0x00,
iinfo->i_lenAlloc);
iinfo->i_lenAlloc = 0;
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
set_page_dirty(page);
unlock_page(page);
up_write(&iinfo->i_data_sem);
err = filemap_fdatawrite(inode->i_mapping);
if (err) {
/* Restore everything back so that we don't lose data... */
lock_page(page);
down_write(&iinfo->i_data_sem);
kaddr = kmap_atomic(page);
memcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size);
kunmap_atomic(kaddr);
unlock_page(page);
iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;
inode->i_data.a_ops = &udf_adinicb_aops;
up_write(&iinfo->i_data_sem);
}
put_page(page);
mark_inode_dirty(inode);
return err;
}
|
151977926301006306483685572008692883310
|
inode.c
|
299509065903875732825474013259696803505
|
CWE-476
|
CVE-2022-0617
|
A flaw null pointer dereference in the Linux kernel UDF file system functionality was found in the way user triggers udf_file_write_iter function for the malicious UDF image. A local user could use this flaw to crash the system. Actual from Linux kernel 4.2-rc1 till 5.17-rc2.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0617
|
386,750
|
linux
|
ea8569194b43f0f01f0a84c689388542c7254a1f
|
https://github.com/torvalds/linux
|
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ea8569194b43f0f01f0a84c689388542c7254a1f
|
udf: Restore i_lenAlloc when inode expansion fails
When we fail to expand inode from inline format to a normal format, we
restore inode to contain the original inline formatting but we forgot to
set i_lenAlloc back. The mismatch between i_lenAlloc and i_size was then
causing further problems such as warnings and lost data down the line.
Reported-by: butt3rflyh4ck <[email protected]>
CC: [email protected]
Fixes: 7e49b6f2480c ("udf: Convert UDF to new truncate calling sequence")
Reviewed-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
| 0
|
int udf_expand_file_adinicb(struct inode *inode)
{
struct page *page;
char *kaddr;
struct udf_inode_info *iinfo = UDF_I(inode);
int err;
WARN_ON_ONCE(!inode_is_locked(inode));
if (!iinfo->i_lenAlloc) {
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
up_write(&iinfo->i_data_sem);
mark_inode_dirty(inode);
return 0;
}
/*
* Release i_data_sem so that we can lock a page - page lock ranks
* above i_data_sem. i_mutex still protects us against file changes.
*/
up_write(&iinfo->i_data_sem);
page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS);
if (!page)
return -ENOMEM;
if (!PageUptodate(page)) {
kaddr = kmap_atomic(page);
memset(kaddr + iinfo->i_lenAlloc, 0x00,
PAGE_SIZE - iinfo->i_lenAlloc);
memcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr,
iinfo->i_lenAlloc);
flush_dcache_page(page);
SetPageUptodate(page);
kunmap_atomic(kaddr);
}
down_write(&iinfo->i_data_sem);
memset(iinfo->i_data + iinfo->i_lenEAttr, 0x00,
iinfo->i_lenAlloc);
iinfo->i_lenAlloc = 0;
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
set_page_dirty(page);
unlock_page(page);
up_write(&iinfo->i_data_sem);
err = filemap_fdatawrite(inode->i_mapping);
if (err) {
/* Restore everything back so that we don't lose data... */
lock_page(page);
down_write(&iinfo->i_data_sem);
kaddr = kmap_atomic(page);
memcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size);
kunmap_atomic(kaddr);
unlock_page(page);
iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;
inode->i_data.a_ops = &udf_adinicb_aops;
iinfo->i_lenAlloc = inode->i_size;
up_write(&iinfo->i_data_sem);
}
put_page(page);
mark_inode_dirty(inode);
return err;
}
|
191954099261759057406602593964899861240
|
inode.c
|
50770462585650222153062698584720679665
|
CWE-476
|
CVE-2022-0617
|
A flaw null pointer dereference in the Linux kernel UDF file system functionality was found in the way user triggers udf_file_write_iter function for the malicious UDF image. A local user could use this flaw to crash the system. Actual from Linux kernel 4.2-rc1 till 5.17-rc2.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0617
|
206,815
|
ImageMagick
|
c111ed9b035532c2c81ea569f2d22fded9517287
|
https://github.com/ImageMagick/ImageMagick
|
https://github.com/ImageMagick/ImageMagick/commit/c111ed9b035532c2c81ea569f2d22fded9517287
|
https://github.com/ImageMagick/ImageMagick/issues/1540
| 1
|
static MagickBooleanType SetGrayscaleImage(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
*colormap;
register ssize_t
i;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace,exception);
if (image->storage_class == PseudoClass)
colormap_index=(ssize_t *) AcquireQuantumMemory(image->colors+1,
sizeof(*colormap_index));
else
colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize+1,
sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
(void) memset(colormap_index,(-1),MaxColormapSize*
sizeof(*colormap_index));
if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
image->colors=0;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(image,q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=(double)
GetPixelRed(image,q);
image->colormap[image->colors].green=(double)
GetPixelGreen(image,q);
image->colormap[image->colors].blue=(double)
GetPixelBlue(image,q);
image->colors++;
}
}
SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].alpha=(double) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
IntensityCompare);
colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
if (colormap == (PixelInfo *) NULL)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].alpha]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
GetPixelIndex(image,q))],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (SetImageMonochrome(image,exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
|
31139316036408574839827699821440311605
|
quantize.c
|
6776316156649379334956322163459365152
|
CWE-125
|
CVE-2019-11598
|
In ImageMagick 7.0.8-40 Q16, there is a heap-based buffer over-read in the function WritePNMImage of coders/pnm.c, which allows an attacker to cause a denial of service or possibly information disclosure via a crafted image file. This is related to SetGrayscaleImage in MagickCore/quantize.c.
|
https://nvd.nist.gov/vuln/detail/CVE-2019-11598
|
387,149
|
ImageMagick
|
c111ed9b035532c2c81ea569f2d22fded9517287
|
https://github.com/ImageMagick/ImageMagick
|
https://github.com/ImageMagick/ImageMagick/commit/c111ed9b035532c2c81ea569f2d22fded9517287
|
https://github.com/ImageMagick/ImageMagick/issues/1540
| 0
|
static MagickBooleanType SetGrayscaleImage(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
*colormap;
register ssize_t
i;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace,exception);
if (image->storage_class == PseudoClass)
colormap_index=(ssize_t *) AcquireQuantumMemory(MagickMax(image->colors+1,
MaxMap),sizeof(*colormap_index));
else
colormap_index=(ssize_t *) AcquireQuantumMemory(MagickMax(MaxColormapSize+1,
MaxMap),sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
(void) memset(colormap_index,(-1),MaxColormapSize*
sizeof(*colormap_index));
if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
image->colors=0;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(image,q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=(double)
GetPixelRed(image,q);
image->colormap[image->colors].green=(double)
GetPixelGreen(image,q);
image->colormap[image->colors].blue=(double)
GetPixelBlue(image,q);
image->colors++;
}
}
SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].alpha=(double) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
IntensityCompare);
colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
if (colormap == (PixelInfo *) NULL)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].alpha]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
GetPixelIndex(image,q))],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (SetImageMonochrome(image,exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
|
185597478640915810926254287356895046975
|
quantize.c
|
90832018031567136939378750944649283392
|
CWE-125
|
CVE-2019-11598
|
In ImageMagick 7.0.8-40 Q16, there is a heap-based buffer over-read in the function WritePNMImage of coders/pnm.c, which allows an attacker to cause a denial of service or possibly information disclosure via a crafted image file. This is related to SetGrayscaleImage in MagickCore/quantize.c.
|
https://nvd.nist.gov/vuln/detail/CVE-2019-11598
|
206,845
|
linux
|
5934d9a0383619c14df91af8fd76261dc3de2f5f
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/5934d9a0383619c14df91af8fd76261dc3de2f5f
|
ALSA: control: Re-order bounds checking in get_ctl_id_hash()
These two checks are in the reverse order so it might read one element
beyond the end of the array. First check if the "i" is within bounds
before using it.
Fixes: 6ab55ec0a938 ("ALSA: control: Fix an out-of-bounds bug in get_ctl_id_hash()")
Signed-off-by: Dan Carpenter <[email protected]>
Link: https://lore.kernel.org/r/YwjgNh/gkG1hH7po@kili
Signed-off-by: Takashi Iwai <[email protected]>
| 1
|
static unsigned long get_ctl_id_hash(const struct snd_ctl_elem_id *id)
{
int i;
unsigned long h;
h = id->iface;
h = MULTIPLIER * h + id->device;
h = MULTIPLIER * h + id->subdevice;
for (i = 0; id->name[i] && i < SNDRV_CTL_ELEM_ID_NAME_MAXLEN; i++)
h = MULTIPLIER * h + id->name[i];
h = MULTIPLIER * h + id->index;
h &= LONG_MAX;
return h;
}
|
131319443934908040237061712028017051028
|
control.c
|
255950300769870224716949641453203743368
|
CWE-125
|
CVE-2022-3170
|
An out-of-bounds access issue was found in the Linux kernel sound subsystem. It could occur when the 'id->name' provided by the user did not end with '\0'. A privileged local user could pass a specially crafted name through ioctl() interface and crash the system or potentially escalate their privileges on the system.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-3170
|
387,593
|
linux
|
5934d9a0383619c14df91af8fd76261dc3de2f5f
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/5934d9a0383619c14df91af8fd76261dc3de2f5f
|
ALSA: control: Re-order bounds checking in get_ctl_id_hash()
These two checks are in the reverse order so it might read one element
beyond the end of the array. First check if the "i" is within bounds
before using it.
Fixes: 6ab55ec0a938 ("ALSA: control: Fix an out-of-bounds bug in get_ctl_id_hash()")
Signed-off-by: Dan Carpenter <[email protected]>
Link: https://lore.kernel.org/r/YwjgNh/gkG1hH7po@kili
Signed-off-by: Takashi Iwai <[email protected]>
| 0
|
static unsigned long get_ctl_id_hash(const struct snd_ctl_elem_id *id)
{
int i;
unsigned long h;
h = id->iface;
h = MULTIPLIER * h + id->device;
h = MULTIPLIER * h + id->subdevice;
for (i = 0; i < SNDRV_CTL_ELEM_ID_NAME_MAXLEN && id->name[i]; i++)
h = MULTIPLIER * h + id->name[i];
h = MULTIPLIER * h + id->index;
h &= LONG_MAX;
return h;
}
|
34537843047622620480136251678937271731
|
control.c
|
333017582912688268799367809880673073354
|
CWE-125
|
CVE-2022-3170
|
An out-of-bounds access issue was found in the Linux kernel sound subsystem. It could occur when the 'id->name' provided by the user did not end with '\0'. A privileged local user could pass a specially crafted name through ioctl() interface and crash the system or potentially escalate their privileges on the system.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-3170
|
206,942
|
vim
|
1e56bda9048a9625bce6e660938c834c5c15b07d
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/1e56bda9048a9625bce6e660938c834c5c15b07d
|
patch 9.0.0104: going beyond allocated memory when evaluating string constant
Problem: Going beyond allocated memory when evaluating string constant.
Solution: Properly skip over <Key> form.
| 1
|
eval_string(char_u **arg, typval_T *rettv, int evaluate, int interpolate)
{
char_u *p;
char_u *end;
int extra = interpolate ? 1 : 0;
int off = interpolate ? 0 : 1;
int len;
// Find the end of the string, skipping backslashed characters.
for (p = *arg + off; *p != NUL && *p != '"'; MB_PTR_ADV(p))
{
if (*p == '\\' && p[1] != NUL)
{
++p;
// A "\<x>" form occupies at least 4 characters, and produces up
// to 9 characters (6 for the char and 3 for a modifier):
// reserve space for 5 extra.
if (*p == '<')
extra += 5;
}
else if (interpolate && (*p == '{' || *p == '}'))
{
if (*p == '{' && p[1] != '{') // start of expression
break;
++p;
if (p[-1] == '}' && *p != '}') // single '}' is an error
{
semsg(_(e_stray_closing_curly_str), *arg);
return FAIL;
}
--extra; // "{{" becomes "{", "}}" becomes "}"
}
}
if (*p != '"' && !(interpolate && *p == '{'))
{
semsg(_(e_missing_double_quote_str), *arg);
return FAIL;
}
// If only parsing, set *arg and return here
if (!evaluate)
{
*arg = p + off;
return OK;
}
// Copy the string into allocated memory, handling backslashed
// characters.
rettv->v_type = VAR_STRING;
len = (int)(p - *arg + extra);
rettv->vval.v_string = alloc(len);
if (rettv->vval.v_string == NULL)
return FAIL;
end = rettv->vval.v_string;
for (p = *arg + off; *p != NUL && *p != '"'; )
{
if (*p == '\\')
{
switch (*++p)
{
case 'b': *end++ = BS; ++p; break;
case 'e': *end++ = ESC; ++p; break;
case 'f': *end++ = FF; ++p; break;
case 'n': *end++ = NL; ++p; break;
case 'r': *end++ = CAR; ++p; break;
case 't': *end++ = TAB; ++p; break;
case 'X': // hex: "\x1", "\x12"
case 'x':
case 'u': // Unicode: "\u0023"
case 'U':
if (vim_isxdigit(p[1]))
{
int n, nr;
int c = toupper(*p);
if (c == 'X')
n = 2;
else if (*p == 'u')
n = 4;
else
n = 8;
nr = 0;
while (--n >= 0 && vim_isxdigit(p[1]))
{
++p;
nr = (nr << 4) + hex2nr(*p);
}
++p;
// For "\u" store the number according to
// 'encoding'.
if (c != 'X')
end += (*mb_char2bytes)(nr, end);
else
*end++ = nr;
}
break;
// octal: "\1", "\12", "\123"
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': *end = *p++ - '0';
if (*p >= '0' && *p <= '7')
{
*end = (*end << 3) + *p++ - '0';
if (*p >= '0' && *p <= '7')
*end = (*end << 3) + *p++ - '0';
}
++end;
break;
// Special key, e.g.: "\<C-W>"
case '<':
{
int flags = FSK_KEYCODE | FSK_IN_STRING;
if (p[1] != '*')
flags |= FSK_SIMPLIFY;
extra = trans_special(&p, end, flags, FALSE, NULL);
if (extra != 0)
{
end += extra;
if (end >= rettv->vval.v_string + len)
iemsg("eval_string() used more space than allocated");
break;
}
}
// FALLTHROUGH
default: MB_COPY_CHAR(p, end);
break;
}
}
else
{
if (interpolate && (*p == '{' || *p == '}'))
{
if (*p == '{' && p[1] != '{') // start of expression
break;
++p; // reduce "{{" to "{" and "}}" to "}"
}
MB_COPY_CHAR(p, end);
}
}
*end = NUL;
if (*p == '"' && !interpolate)
++p;
*arg = p;
return OK;
}
|
338220226163490913152834959718974208239
|
typval.c
|
328531951922388475683903891036611129511
|
CWE-125
|
CVE-2022-2580
|
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0102.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2580
|
389,676
|
vim
|
1e56bda9048a9625bce6e660938c834c5c15b07d
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/1e56bda9048a9625bce6e660938c834c5c15b07d
|
patch 9.0.0104: going beyond allocated memory when evaluating string constant
Problem: Going beyond allocated memory when evaluating string constant.
Solution: Properly skip over <Key> form.
| 0
|
eval_string(char_u **arg, typval_T *rettv, int evaluate, int interpolate)
{
char_u *p;
char_u *end;
int extra = interpolate ? 1 : 0;
int off = interpolate ? 0 : 1;
int len;
// Find the end of the string, skipping backslashed characters.
for (p = *arg + off; *p != NUL && *p != '"'; MB_PTR_ADV(p))
{
if (*p == '\\' && p[1] != NUL)
{
++p;
// A "\<x>" form occupies at least 4 characters, and produces up
// to 9 characters (6 for the char and 3 for a modifier):
// reserve space for 5 extra.
if (*p == '<')
{
int modifiers = 0;
int flags = FSK_KEYCODE | FSK_IN_STRING;
extra += 5;
// Skip to the '>' to avoid using '{' inside for string
// interpolation.
if (p[1] != '*')
flags |= FSK_SIMPLIFY;
if (find_special_key(&p, &modifiers, flags, NULL) != 0)
--p; // leave "p" on the ">"
}
}
else if (interpolate && (*p == '{' || *p == '}'))
{
if (*p == '{' && p[1] != '{') // start of expression
break;
++p;
if (p[-1] == '}' && *p != '}') // single '}' is an error
{
semsg(_(e_stray_closing_curly_str), *arg);
return FAIL;
}
--extra; // "{{" becomes "{", "}}" becomes "}"
}
}
if (*p != '"' && !(interpolate && *p == '{'))
{
semsg(_(e_missing_double_quote_str), *arg);
return FAIL;
}
// If only parsing, set *arg and return here
if (!evaluate)
{
*arg = p + off;
return OK;
}
// Copy the string into allocated memory, handling backslashed
// characters.
rettv->v_type = VAR_STRING;
len = (int)(p - *arg + extra);
rettv->vval.v_string = alloc(len);
if (rettv->vval.v_string == NULL)
return FAIL;
end = rettv->vval.v_string;
for (p = *arg + off; *p != NUL && *p != '"'; )
{
if (*p == '\\')
{
switch (*++p)
{
case 'b': *end++ = BS; ++p; break;
case 'e': *end++ = ESC; ++p; break;
case 'f': *end++ = FF; ++p; break;
case 'n': *end++ = NL; ++p; break;
case 'r': *end++ = CAR; ++p; break;
case 't': *end++ = TAB; ++p; break;
case 'X': // hex: "\x1", "\x12"
case 'x':
case 'u': // Unicode: "\u0023"
case 'U':
if (vim_isxdigit(p[1]))
{
int n, nr;
int c = toupper(*p);
if (c == 'X')
n = 2;
else if (*p == 'u')
n = 4;
else
n = 8;
nr = 0;
while (--n >= 0 && vim_isxdigit(p[1]))
{
++p;
nr = (nr << 4) + hex2nr(*p);
}
++p;
// For "\u" store the number according to
// 'encoding'.
if (c != 'X')
end += (*mb_char2bytes)(nr, end);
else
*end++ = nr;
}
break;
// octal: "\1", "\12", "\123"
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': *end = *p++ - '0';
if (*p >= '0' && *p <= '7')
{
*end = (*end << 3) + *p++ - '0';
if (*p >= '0' && *p <= '7')
*end = (*end << 3) + *p++ - '0';
}
++end;
break;
// Special key, e.g.: "\<C-W>"
case '<':
{
int flags = FSK_KEYCODE | FSK_IN_STRING;
if (p[1] != '*')
flags |= FSK_SIMPLIFY;
extra = trans_special(&p, end, flags, FALSE, NULL);
if (extra != 0)
{
end += extra;
if (end >= rettv->vval.v_string + len)
iemsg("eval_string() used more space than allocated");
break;
}
}
// FALLTHROUGH
default: MB_COPY_CHAR(p, end);
break;
}
}
else
{
if (interpolate && (*p == '{' || *p == '}'))
{
if (*p == '{' && p[1] != '{') // start of expression
break;
++p; // reduce "{{" to "{" and "}}" to "}"
}
MB_COPY_CHAR(p, end);
}
}
*end = NUL;
if (*p == '"' && !interpolate)
++p;
*arg = p;
return OK;
}
|
300144927032379821054071112406007573706
|
typval.c
|
264686639878036499427248365468285871356
|
CWE-125
|
CVE-2022-2580
|
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0102.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2580
|
206,946
|
jasper
|
d99636fad60629785efd1ef72da772a8ef68f54c
|
https://github.com/mdadams/jasper
|
https://github.com/jasper-software/jasper/commit/d99636fad60629785efd1ef72da772a8ef68f54c
|
fix memory leaks in function cmdopts_parse
| 1
|
cmdopts_t *cmdopts_parse(int argc, char **argv)
{
enum {
CMDOPT_HELP = 0,
CMDOPT_VERBOSE,
CMDOPT_QUIET,
CMDOPT_INFILE,
CMDOPT_INFMT,
CMDOPT_INOPT,
CMDOPT_OUTFILE,
CMDOPT_OUTFMT,
CMDOPT_OUTOPT,
CMDOPT_VERSION,
CMDOPT_DEBUG,
CMDOPT_CMPTNO,
CMDOPT_SRGB,
CMDOPT_MAXMEM,
CMDOPT_LIST_ENABLED_CODECS,
CMDOPT_LIST_ALL_CODECS,
CMDOPT_ENABLE_FORMAT,
CMDOPT_ENABLE_ALL_FORMATS,
};
static const jas_opt_t cmdoptions[] = {
{CMDOPT_HELP, "help", 0},
{CMDOPT_VERBOSE, "verbose", 0},
{CMDOPT_QUIET, "quiet", 0},
{CMDOPT_QUIET, "q", 0},
{CMDOPT_INFILE, "input", JAS_OPT_HASARG},
{CMDOPT_INFILE, "f", JAS_OPT_HASARG},
{CMDOPT_INFMT, "input-format", JAS_OPT_HASARG},
{CMDOPT_INFMT, "t", JAS_OPT_HASARG},
{CMDOPT_INOPT, "input-option", JAS_OPT_HASARG},
{CMDOPT_INOPT, "o", JAS_OPT_HASARG},
{CMDOPT_OUTFILE, "output", JAS_OPT_HASARG},
{CMDOPT_OUTFILE, "F", JAS_OPT_HASARG},
{CMDOPT_OUTFMT, "output-format", JAS_OPT_HASARG},
{CMDOPT_OUTFMT, "T", JAS_OPT_HASARG},
{CMDOPT_OUTOPT, "output-option", JAS_OPT_HASARG},
{CMDOPT_OUTOPT, "O", JAS_OPT_HASARG},
{CMDOPT_VERSION, "version", 0},
{CMDOPT_DEBUG, "debug-level", JAS_OPT_HASARG},
{CMDOPT_CMPTNO, "cmptno", JAS_OPT_HASARG},
{CMDOPT_SRGB, "force-srgb", 0},
{CMDOPT_SRGB, "S", 0},
{CMDOPT_MAXMEM, "memory-limit", JAS_OPT_HASARG},
{CMDOPT_LIST_ENABLED_CODECS, "list-enabled-formats", 0},
{CMDOPT_LIST_ALL_CODECS, "list-all-formats", 0},
{CMDOPT_ENABLE_FORMAT, "enable-format", JAS_OPT_HASARG},
{CMDOPT_ENABLE_ALL_FORMATS, "enable-all-formats", 0},
{-1, 0, 0}
};
cmdopts_t *cmdopts;
int c;
if (!(cmdopts = malloc(sizeof(cmdopts_t)))) {
fprintf(stderr, "error: insufficient memory\n");
exit(EXIT_FAILURE);
}
cmdopts->infile = 0;
cmdopts->infmt = -1;
cmdopts->infmt_str = 0;
cmdopts->inopts = 0;
cmdopts->inoptsbuf[0] = '\0';
cmdopts->outfile = 0;
cmdopts->outfmt = -1;
cmdopts->outfmt_str = 0;
cmdopts->outopts = 0;
cmdopts->outoptsbuf[0] = '\0';
cmdopts->verbose = 0;
cmdopts->version = 0;
cmdopts->cmptno = -1;
cmdopts->debug = 0;
cmdopts->srgb = 0;
cmdopts->list_codecs = 0;
cmdopts->list_codecs_all = 0;
cmdopts->help = 0;
cmdopts->max_mem = get_default_max_mem_usage();
cmdopts->enable_format = 0;
cmdopts->enable_all_formats = 0;
while ((c = jas_getopt(argc, argv, cmdoptions)) != EOF) {
switch (c) {
case CMDOPT_HELP:
cmdopts->help = 1;
break;
case CMDOPT_VERBOSE:
cmdopts->verbose = 1;
break;
case CMDOPT_QUIET:
cmdopts->verbose = -1;
break;
case CMDOPT_VERSION:
cmdopts->version = 1;
break;
case CMDOPT_LIST_ENABLED_CODECS:
cmdopts->list_codecs = 1;
cmdopts->list_codecs_all = 0;
break;
case CMDOPT_LIST_ALL_CODECS:
cmdopts->list_codecs = 1;
cmdopts->list_codecs_all = 1;
break;
case CMDOPT_DEBUG:
cmdopts->debug = atoi(jas_optarg);
break;
case CMDOPT_INFILE:
cmdopts->infile = jas_optarg;
break;
case CMDOPT_INFMT:
cmdopts->infmt_str= jas_optarg;
break;
case CMDOPT_INOPT:
addopt(cmdopts->inoptsbuf, OPTSMAX, jas_optarg);
cmdopts->inopts = cmdopts->inoptsbuf;
break;
case CMDOPT_OUTFILE:
cmdopts->outfile = jas_optarg;
break;
case CMDOPT_OUTFMT:
cmdopts->outfmt_str = jas_optarg;
break;
case CMDOPT_OUTOPT:
addopt(cmdopts->outoptsbuf, OPTSMAX, jas_optarg);
cmdopts->outopts = cmdopts->outoptsbuf;
break;
case CMDOPT_CMPTNO:
cmdopts->cmptno = atoi(jas_optarg);
break;
case CMDOPT_SRGB:
cmdopts->srgb = 1;
break;
case CMDOPT_MAXMEM:
cmdopts->max_mem = strtoull(jas_optarg, 0, 10);
break;
case CMDOPT_ENABLE_FORMAT:
cmdopts->enable_format = jas_optarg;
break;
case CMDOPT_ENABLE_ALL_FORMATS:
cmdopts->enable_all_formats = 1;
break;
default:
badusage();
break;
}
}
while (jas_optind < argc) {
fprintf(stderr,
"warning: ignoring bogus command line argument %s\n",
argv[jas_optind]);
++jas_optind;
}
if (cmdopts->version || cmdopts->list_codecs || cmdopts->help) {
goto done;
}
if (!cmdopts->outfmt_str && !cmdopts->outfile) {
fprintf(stderr, "error: cannot determine output format\n");
badusage();
}
done:
return cmdopts;
}
|
93181291511681804073691200897709901657
|
jasper.c
|
221565924886298462326836957771233686713
|
CWE-703
|
CVE-2022-2963
|
A vulnerability found in jasper. This security vulnerability happens because of a memory leak bug in function cmdopts_parse that can cause a crash or segmentation fault.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2963
|
389,760
|
jasper
|
d99636fad60629785efd1ef72da772a8ef68f54c
|
https://github.com/mdadams/jasper
|
https://github.com/jasper-software/jasper/commit/d99636fad60629785efd1ef72da772a8ef68f54c
|
fix memory leaks in function cmdopts_parse
| 0
|
cmdopts_t *cmdopts_parse(int argc, char **argv)
{
enum {
CMDOPT_HELP = 0,
CMDOPT_VERBOSE,
CMDOPT_QUIET,
CMDOPT_INFILE,
CMDOPT_INFMT,
CMDOPT_INOPT,
CMDOPT_OUTFILE,
CMDOPT_OUTFMT,
CMDOPT_OUTOPT,
CMDOPT_VERSION,
CMDOPT_DEBUG,
CMDOPT_CMPTNO,
CMDOPT_SRGB,
CMDOPT_MAXMEM,
CMDOPT_LIST_ENABLED_CODECS,
CMDOPT_LIST_ALL_CODECS,
CMDOPT_ENABLE_FORMAT,
CMDOPT_ENABLE_ALL_FORMATS,
};
static const jas_opt_t cmdoptions[] = {
{CMDOPT_HELP, "help", 0},
{CMDOPT_VERBOSE, "verbose", 0},
{CMDOPT_QUIET, "quiet", 0},
{CMDOPT_QUIET, "q", 0},
{CMDOPT_INFILE, "input", JAS_OPT_HASARG},
{CMDOPT_INFILE, "f", JAS_OPT_HASARG},
{CMDOPT_INFMT, "input-format", JAS_OPT_HASARG},
{CMDOPT_INFMT, "t", JAS_OPT_HASARG},
{CMDOPT_INOPT, "input-option", JAS_OPT_HASARG},
{CMDOPT_INOPT, "o", JAS_OPT_HASARG},
{CMDOPT_OUTFILE, "output", JAS_OPT_HASARG},
{CMDOPT_OUTFILE, "F", JAS_OPT_HASARG},
{CMDOPT_OUTFMT, "output-format", JAS_OPT_HASARG},
{CMDOPT_OUTFMT, "T", JAS_OPT_HASARG},
{CMDOPT_OUTOPT, "output-option", JAS_OPT_HASARG},
{CMDOPT_OUTOPT, "O", JAS_OPT_HASARG},
{CMDOPT_VERSION, "version", 0},
{CMDOPT_DEBUG, "debug-level", JAS_OPT_HASARG},
{CMDOPT_CMPTNO, "cmptno", JAS_OPT_HASARG},
{CMDOPT_SRGB, "force-srgb", 0},
{CMDOPT_SRGB, "S", 0},
{CMDOPT_MAXMEM, "memory-limit", JAS_OPT_HASARG},
{CMDOPT_LIST_ENABLED_CODECS, "list-enabled-formats", 0},
{CMDOPT_LIST_ALL_CODECS, "list-all-formats", 0},
{CMDOPT_ENABLE_FORMAT, "enable-format", JAS_OPT_HASARG},
{CMDOPT_ENABLE_ALL_FORMATS, "enable-all-formats", 0},
{-1, 0, 0}
};
cmdopts_t *cmdopts;
int c;
if (!(cmdopts = malloc(sizeof(cmdopts_t)))) {
fprintf(stderr, "error: insufficient memory\n");
exit(EXIT_FAILURE);
}
cmdopts->infile = 0;
cmdopts->infmt = -1;
cmdopts->infmt_str = 0;
cmdopts->inopts = 0;
cmdopts->inoptsbuf[0] = '\0';
cmdopts->outfile = 0;
cmdopts->outfmt = -1;
cmdopts->outfmt_str = 0;
cmdopts->outopts = 0;
cmdopts->outoptsbuf[0] = '\0';
cmdopts->verbose = 0;
cmdopts->version = 0;
cmdopts->cmptno = -1;
cmdopts->debug = 0;
cmdopts->srgb = 0;
cmdopts->list_codecs = 0;
cmdopts->list_codecs_all = 0;
cmdopts->help = 0;
cmdopts->max_mem = get_default_max_mem_usage();
cmdopts->enable_format = 0;
cmdopts->enable_all_formats = 0;
while ((c = jas_getopt(argc, argv, cmdoptions)) != EOF) {
switch (c) {
case CMDOPT_HELP:
cmdopts->help = 1;
break;
case CMDOPT_VERBOSE:
cmdopts->verbose = 1;
break;
case CMDOPT_QUIET:
cmdopts->verbose = -1;
break;
case CMDOPT_VERSION:
cmdopts->version = 1;
break;
case CMDOPT_LIST_ENABLED_CODECS:
cmdopts->list_codecs = 1;
cmdopts->list_codecs_all = 0;
break;
case CMDOPT_LIST_ALL_CODECS:
cmdopts->list_codecs = 1;
cmdopts->list_codecs_all = 1;
break;
case CMDOPT_DEBUG:
cmdopts->debug = atoi(jas_optarg);
break;
case CMDOPT_INFILE:
cmdopts->infile = jas_optarg;
break;
case CMDOPT_INFMT:
cmdopts->infmt_str= jas_optarg;
break;
case CMDOPT_INOPT:
addopt(cmdopts->inoptsbuf, OPTSMAX, jas_optarg);
cmdopts->inopts = cmdopts->inoptsbuf;
break;
case CMDOPT_OUTFILE:
cmdopts->outfile = jas_optarg;
break;
case CMDOPT_OUTFMT:
cmdopts->outfmt_str = jas_optarg;
break;
case CMDOPT_OUTOPT:
addopt(cmdopts->outoptsbuf, OPTSMAX, jas_optarg);
cmdopts->outopts = cmdopts->outoptsbuf;
break;
case CMDOPT_CMPTNO:
cmdopts->cmptno = atoi(jas_optarg);
break;
case CMDOPT_SRGB:
cmdopts->srgb = 1;
break;
case CMDOPT_MAXMEM:
cmdopts->max_mem = strtoull(jas_optarg, 0, 10);
break;
case CMDOPT_ENABLE_FORMAT:
cmdopts->enable_format = jas_optarg;
break;
case CMDOPT_ENABLE_ALL_FORMATS:
cmdopts->enable_all_formats = 1;
break;
default:
cmdopts_destroy(cmdopts);
badusage();
break;
}
}
while (jas_optind < argc) {
fprintf(stderr,
"warning: ignoring bogus command line argument %s\n",
argv[jas_optind]);
++jas_optind;
}
if (cmdopts->version || cmdopts->list_codecs || cmdopts->help) {
goto done;
}
if (!cmdopts->outfmt_str && !cmdopts->outfile) {
fprintf(stderr, "error: cannot determine output format\n");
cmdopts_destroy(cmdopts);
badusage();
}
done:
return cmdopts;
}
|
102932853856682606703676466444383538610
|
jasper.c
|
43318189901043805005058339060588403940
|
CWE-703
|
CVE-2022-2963
|
A vulnerability found in jasper. This security vulnerability happens because of a memory leak bug in function cmdopts_parse that can cause a crash or segmentation fault.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2963
|
207,068
|
linux
|
cc7a0bb058b85ea03db87169c60c7cfdd5d34678
|
https://github.com/torvalds/linux
|
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc7a0bb058b85ea03db87169c60c7cfdd5d34678
|
PCI: rpadlpar: Fix potential drc_name corruption in store functions
Both add_slot_store() and remove_slot_store() try to fix up the
drc_name copied from the store buffer by placing a NUL terminator at
nbyte + 1 or in place of a '\n' if present. However, the static buffer
that we copy the drc_name data into is not zeroed and can contain
anything past the n-th byte.
This is problematic if a '\n' byte appears in that buffer after nbytes
and the string copied into the store buffer was not NUL terminated to
start with as the strchr() search for a '\n' byte will mark this
incorrectly as the end of the drc_name string resulting in a drc_name
string that contains garbage data after the n-th byte.
Additionally it will cause us to overwrite that '\n' byte on the stack
with NUL, potentially corrupting data on the stack.
The following debugging shows an example of the drmgr utility writing
"PHB 4543" to the add_slot sysfs attribute, but add_slot_store()
logging a corrupted string value.
drmgr: drmgr: -c phb -a -s PHB 4543 -d 1
add_slot_store: drc_name = PHB 4543°|<82>!, rc = -19
Fix this by using strscpy() instead of memcpy() to ensure the string
is NUL terminated when copied into the static drc_name buffer.
Further, since the string is now NUL terminated the code only needs to
change '\n' to '\0' when present.
Cc: [email protected]
Signed-off-by: Tyrel Datwyler <[email protected]>
[mpe: Reformat change log and add mention of possible stack corruption]
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
| 1
|
static ssize_t remove_slot_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t nbytes)
{
char drc_name[MAX_DRC_NAME_LEN];
int rc;
char *end;
if (nbytes >= MAX_DRC_NAME_LEN)
return 0;
memcpy(drc_name, buf, nbytes);
end = strchr(drc_name, '\n');
if (!end)
end = &drc_name[nbytes];
*end = '\0';
rc = dlpar_remove_slot(drc_name);
if (rc)
return rc;
return nbytes;
}
|
237293762490436147707541740545065202667
|
rpadlpar_sysfs.c
|
143265511624763705093739678134289779335
|
CWE-120
|
CVE-2021-28972
|
In drivers/pci/hotplug/rpadlpar_sysfs.c in the Linux kernel through 5.11.8, the RPA PCI Hotplug driver has a user-tolerable buffer overflow when writing a new device name to the driver from userspace, allowing userspace to write data to the kernel stack frame directly. This occurs because add_slot_store and remove_slot_store mishandle drc_name '\0' termination, aka CID-cc7a0bb058b8.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-28972
|
391,627
|
linux
|
cc7a0bb058b85ea03db87169c60c7cfdd5d34678
|
https://github.com/torvalds/linux
|
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc7a0bb058b85ea03db87169c60c7cfdd5d34678
|
PCI: rpadlpar: Fix potential drc_name corruption in store functions
Both add_slot_store() and remove_slot_store() try to fix up the
drc_name copied from the store buffer by placing a NUL terminator at
nbyte + 1 or in place of a '\n' if present. However, the static buffer
that we copy the drc_name data into is not zeroed and can contain
anything past the n-th byte.
This is problematic if a '\n' byte appears in that buffer after nbytes
and the string copied into the store buffer was not NUL terminated to
start with as the strchr() search for a '\n' byte will mark this
incorrectly as the end of the drc_name string resulting in a drc_name
string that contains garbage data after the n-th byte.
Additionally it will cause us to overwrite that '\n' byte on the stack
with NUL, potentially corrupting data on the stack.
The following debugging shows an example of the drmgr utility writing
"PHB 4543" to the add_slot sysfs attribute, but add_slot_store()
logging a corrupted string value.
drmgr: drmgr: -c phb -a -s PHB 4543 -d 1
add_slot_store: drc_name = PHB 4543°|<82>!, rc = -19
Fix this by using strscpy() instead of memcpy() to ensure the string
is NUL terminated when copied into the static drc_name buffer.
Further, since the string is now NUL terminated the code only needs to
change '\n' to '\0' when present.
Cc: [email protected]
Signed-off-by: Tyrel Datwyler <[email protected]>
[mpe: Reformat change log and add mention of possible stack corruption]
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
| 0
|
static ssize_t remove_slot_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t nbytes)
{
char drc_name[MAX_DRC_NAME_LEN];
int rc;
char *end;
if (nbytes >= MAX_DRC_NAME_LEN)
return 0;
strscpy(drc_name, buf, nbytes + 1);
end = strchr(drc_name, '\n');
if (end)
*end = '\0';
rc = dlpar_remove_slot(drc_name);
if (rc)
return rc;
return nbytes;
}
|
228561592734793467772177551896912743936
|
rpadlpar_sysfs.c
|
21668029196687947173345261458760783896
|
CWE-120
|
CVE-2021-28972
|
In drivers/pci/hotplug/rpadlpar_sysfs.c in the Linux kernel through 5.11.8, the RPA PCI Hotplug driver has a user-tolerable buffer overflow when writing a new device name to the driver from userspace, allowing userspace to write data to the kernel stack frame directly. This occurs because add_slot_store and remove_slot_store mishandle drc_name '\0' termination, aka CID-cc7a0bb058b8.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-28972
|
207,069
|
linux
|
cc7a0bb058b85ea03db87169c60c7cfdd5d34678
|
https://github.com/torvalds/linux
|
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc7a0bb058b85ea03db87169c60c7cfdd5d34678
|
PCI: rpadlpar: Fix potential drc_name corruption in store functions
Both add_slot_store() and remove_slot_store() try to fix up the
drc_name copied from the store buffer by placing a NUL terminator at
nbyte + 1 or in place of a '\n' if present. However, the static buffer
that we copy the drc_name data into is not zeroed and can contain
anything past the n-th byte.
This is problematic if a '\n' byte appears in that buffer after nbytes
and the string copied into the store buffer was not NUL terminated to
start with as the strchr() search for a '\n' byte will mark this
incorrectly as the end of the drc_name string resulting in a drc_name
string that contains garbage data after the n-th byte.
Additionally it will cause us to overwrite that '\n' byte on the stack
with NUL, potentially corrupting data on the stack.
The following debugging shows an example of the drmgr utility writing
"PHB 4543" to the add_slot sysfs attribute, but add_slot_store()
logging a corrupted string value.
drmgr: drmgr: -c phb -a -s PHB 4543 -d 1
add_slot_store: drc_name = PHB 4543°|<82>!, rc = -19
Fix this by using strscpy() instead of memcpy() to ensure the string
is NUL terminated when copied into the static drc_name buffer.
Further, since the string is now NUL terminated the code only needs to
change '\n' to '\0' when present.
Cc: [email protected]
Signed-off-by: Tyrel Datwyler <[email protected]>
[mpe: Reformat change log and add mention of possible stack corruption]
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
| 1
|
static ssize_t add_slot_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t nbytes)
{
char drc_name[MAX_DRC_NAME_LEN];
char *end;
int rc;
if (nbytes >= MAX_DRC_NAME_LEN)
return 0;
memcpy(drc_name, buf, nbytes);
end = strchr(drc_name, '\n');
if (!end)
end = &drc_name[nbytes];
*end = '\0';
rc = dlpar_add_slot(drc_name);
if (rc)
return rc;
return nbytes;
}
|
262261814389997886159936729256803084500
|
rpadlpar_sysfs.c
|
143265511624763705093739678134289779335
|
CWE-120
|
CVE-2021-28972
|
In drivers/pci/hotplug/rpadlpar_sysfs.c in the Linux kernel through 5.11.8, the RPA PCI Hotplug driver has a user-tolerable buffer overflow when writing a new device name to the driver from userspace, allowing userspace to write data to the kernel stack frame directly. This occurs because add_slot_store and remove_slot_store mishandle drc_name '\0' termination, aka CID-cc7a0bb058b8.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-28972
|
391,628
|
linux
|
cc7a0bb058b85ea03db87169c60c7cfdd5d34678
|
https://github.com/torvalds/linux
|
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc7a0bb058b85ea03db87169c60c7cfdd5d34678
|
PCI: rpadlpar: Fix potential drc_name corruption in store functions
Both add_slot_store() and remove_slot_store() try to fix up the
drc_name copied from the store buffer by placing a NUL terminator at
nbyte + 1 or in place of a '\n' if present. However, the static buffer
that we copy the drc_name data into is not zeroed and can contain
anything past the n-th byte.
This is problematic if a '\n' byte appears in that buffer after nbytes
and the string copied into the store buffer was not NUL terminated to
start with as the strchr() search for a '\n' byte will mark this
incorrectly as the end of the drc_name string resulting in a drc_name
string that contains garbage data after the n-th byte.
Additionally it will cause us to overwrite that '\n' byte on the stack
with NUL, potentially corrupting data on the stack.
The following debugging shows an example of the drmgr utility writing
"PHB 4543" to the add_slot sysfs attribute, but add_slot_store()
logging a corrupted string value.
drmgr: drmgr: -c phb -a -s PHB 4543 -d 1
add_slot_store: drc_name = PHB 4543°|<82>!, rc = -19
Fix this by using strscpy() instead of memcpy() to ensure the string
is NUL terminated when copied into the static drc_name buffer.
Further, since the string is now NUL terminated the code only needs to
change '\n' to '\0' when present.
Cc: [email protected]
Signed-off-by: Tyrel Datwyler <[email protected]>
[mpe: Reformat change log and add mention of possible stack corruption]
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
| 0
|
static ssize_t add_slot_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t nbytes)
{
char drc_name[MAX_DRC_NAME_LEN];
char *end;
int rc;
if (nbytes >= MAX_DRC_NAME_LEN)
return 0;
strscpy(drc_name, buf, nbytes + 1);
end = strchr(drc_name, '\n');
if (end)
*end = '\0';
rc = dlpar_add_slot(drc_name);
if (rc)
return rc;
return nbytes;
}
|
228230730882908285016023798985921663046
|
rpadlpar_sysfs.c
|
21668029196687947173345261458760783896
|
CWE-120
|
CVE-2021-28972
|
In drivers/pci/hotplug/rpadlpar_sysfs.c in the Linux kernel through 5.11.8, the RPA PCI Hotplug driver has a user-tolerable buffer overflow when writing a new device name to the driver from userspace, allowing userspace to write data to the kernel stack frame directly. This occurs because add_slot_store and remove_slot_store mishandle drc_name '\0' termination, aka CID-cc7a0bb058b8.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-28972
|
207,150
|
squirrel
|
a6413aa690e0bdfef648c68693349a7b878fe60d
|
https://github.com/albertodemichelis/squirrel
|
https://github.com/albertodemichelis/squirrel/commit/a6413aa690e0bdfef648c68693349a7b878fe60d
|
fix in thread.call
| 1
|
static SQInteger thread_call(HSQUIRRELVM v)
{
SQObjectPtr o = stack_get(v,1);
if(sq_type(o) == OT_THREAD) {
SQInteger nparams = sq_gettop(v);
_thread(o)->Push(_thread(o)->_roottable);
for(SQInteger i = 2; i<(nparams+1); i++)
sq_move(_thread(o),v,i);
if(SQ_SUCCEEDED(sq_call(_thread(o),nparams,SQTrue,SQTrue))) {
sq_move(v,_thread(o),-1);
sq_pop(_thread(o),1);
return 1;
}
v->_lasterror = _thread(o)->_lasterror;
return SQ_ERROR;
}
return sq_throwerror(v,_SC("wrong parameter"));
}
|
39783972208477930534182111058478291044
|
sqbaselib.cpp
|
22214130882110251892898581176850711195
|
CWE-703
|
CVE-2022-30292
|
Heap-based buffer overflow in sqbaselib.cpp in SQUIRREL 3.2 due to lack of a certain sq_reservestack call.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-30292
|
393,528
|
squirrel
|
a6413aa690e0bdfef648c68693349a7b878fe60d
|
https://github.com/albertodemichelis/squirrel
|
https://github.com/albertodemichelis/squirrel/commit/a6413aa690e0bdfef648c68693349a7b878fe60d
|
fix in thread.call
| 0
|
static SQInteger thread_call(HSQUIRRELVM v)
{
SQObjectPtr o = stack_get(v,1);
if(sq_type(o) == OT_THREAD) {
SQInteger nparams = sq_gettop(v);
sq_reservestack(_thread(o), nparams + 3);
_thread(o)->Push(_thread(o)->_roottable);
for(SQInteger i = 2; i<(nparams+1); i++)
sq_move(_thread(o),v,i);
if(SQ_SUCCEEDED(sq_call(_thread(o),nparams,SQTrue,SQTrue))) {
sq_move(v,_thread(o),-1);
sq_pop(_thread(o),1);
return 1;
}
v->_lasterror = _thread(o)->_lasterror;
return SQ_ERROR;
}
return sq_throwerror(v,_SC("wrong parameter"));
}
|
185870701968227218426869749475686341047
|
sqbaselib.cpp
|
167918424394936848193603192917033144376
|
CWE-703
|
CVE-2022-30292
|
Heap-based buffer overflow in sqbaselib.cpp in SQUIRREL 3.2 due to lack of a certain sq_reservestack call.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-30292
|
207,461
|
autotrace
|
e96bffadc25ff0ba0e10745f8012efcc5f920ea9
|
https://github.com/autotrace/autotrace
|
https://github.com/autotrace/autotrace/commit/e96bffadc25ff0ba0e10745f8012efcc5f920ea9
|
input-bmp: Increase header buffer in some cases
Signed-off-by: Peter Lemenkov <[email protected]>
| 1
|
at_bitmap input_bmp_reader(gchar * filename, at_input_opts_type * opts, at_msg_func msg_func, gpointer msg_data, gpointer user_data)
{
FILE *fd;
unsigned char buffer[64];
int ColormapSize, rowbytes, Maps;
gboolean Grey = FALSE;
unsigned char ColorMap[256][3];
at_bitmap image = at_bitmap_init(0, 0, 0, 1);
unsigned char *image_storage;
at_exception_type exp = at_exception_new(msg_func, msg_data);
char magick[2];
Bitmap_Channel masks[4];
fd = fopen(filename, "rb");
if (!fd) {
LOG("Can't open \"%s\"\n", filename);
at_exception_fatal(&exp, "bmp: cannot open input file");
goto cleanup;
}
/* It is a File. Now is it a Bitmap? Read the shortest possible header. */
if (!ReadOK(fd, magick, 2) ||
!(!strncmp(magick, "BA", 2) ||
!strncmp(magick, "BM", 2) ||
!strncmp(magick, "IC", 2) ||
!strncmp(magick, "PT", 2) ||
!strncmp(magick, "CI", 2) ||
!strncmp(magick, "CP", 2)))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
while (!strncmp(magick, "BA", 2))
{
if (!ReadOK(fd, buffer, 12))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (!ReadOK(fd, magick, 2))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
}
if (!ReadOK(fd, buffer, 12))////
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* bring them to the right byteorder. Not too nice, but it should work */
Bitmap_File_Head.bfSize = ToL(&buffer[0x00]);
Bitmap_File_Head.zzHotX = ToS(&buffer[0x04]);
Bitmap_File_Head.zzHotY = ToS(&buffer[0x06]);
Bitmap_File_Head.bfOffs = ToL(&buffer[0x08]);
if (!ReadOK(fd, buffer, 4))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
Bitmap_File_Head.biSize = ToL(&buffer[0x00]);
/* What kind of bitmap is it? */
if (Bitmap_File_Head.biSize == 12) { /* OS/2 1.x ? */
if (!ReadOK(fd, buffer, 8)) {
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToS(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToS(&buffer[0x02]); /* 14 */
Bitmap_Head.biPlanes = ToS(&buffer[0x04]); /* 16 */
Bitmap_Head.biBitCnt = ToS(&buffer[0x06]); /* 18 */
Bitmap_Head.biCompr = 0;
Bitmap_Head.biSizeIm = 0;
Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0;
Bitmap_Head.biClrUsed = 0;
Bitmap_Head.biClrImp = 0;
Bitmap_Head.masks[0] = 0;
Bitmap_Head.masks[1] = 0;
Bitmap_Head.masks[2] = 0;
Bitmap_Head.masks[3] = 0;
memset(masks, 0, sizeof(masks));
Maps = 3;
} else if (Bitmap_File_Head.biSize == 40) { /* Windows 3.x */
if (!ReadOK(fd, buffer, 36))
{
LOG ("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToL(&buffer[0x04]); /* 16 */
Bitmap_Head.biPlanes = ToS(&buffer[0x08]); /* 1A */
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]); /* 1C */
Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]); /* 22 */
Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */
Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */
Bitmap_Head.biClrImp = ToL(&buffer[0x20]); /* 32 */
Bitmap_Head.masks[0] = 0;
Bitmap_Head.masks[1] = 0;
Bitmap_Head.masks[2] = 0;
Bitmap_Head.masks[3] = 0;
Maps = 4;
memset(masks, 0, sizeof(masks));
if (Bitmap_Head.biCompr == BI_BITFIELDS)
{
if (!ReadOK(fd, buffer, 3 * sizeof(unsigned long)))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.masks[0] = ToL(&buffer[0x00]);
Bitmap_Head.masks[1] = ToL(&buffer[0x04]);
Bitmap_Head.masks[2] = ToL(&buffer[0x08]);
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 3);
}
else if (Bitmap_Head.biCompr == BI_RGB)
{
setMasksDefault(Bitmap_Head.biBitCnt, masks);
}
else if ((Bitmap_Head.biCompr != BI_RLE4) &&
(Bitmap_Head.biCompr != BI_RLE8))
{
/* BI_ALPHABITFIELDS, etc. */
LOG("Unsupported compression in BMP file\n");
at_exception_fatal(&exp, "Unsupported compression in BMP file");
goto cleanup;
}
}
else if (Bitmap_File_Head.biSize >= 56 &&
Bitmap_File_Head.biSize <= 64)
{
/* enhanced Windows format with bit masks */
if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToL(&buffer[0x04]); /* 16 */
Bitmap_Head.biPlanes = ToS(&buffer[0x08]); /* 1A */
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]); /* 1C */
Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]); /* 22 */
Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */
Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */
Bitmap_Head.biClrImp = ToL(&buffer[0x20]); /* 32 */
Bitmap_Head.masks[0] = ToL(&buffer[0x24]); /* 36 */
Bitmap_Head.masks[1] = ToL(&buffer[0x28]); /* 3A */
Bitmap_Head.masks[2] = ToL(&buffer[0x2C]); /* 3E */
Bitmap_Head.masks[3] = ToL(&buffer[0x30]); /* 42 */
Maps = 4;
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);
}
else if (Bitmap_File_Head.biSize == 108 ||
Bitmap_File_Head.biSize == 124)
{
/* BMP Version 4 or 5 */
if (!ReadOK(fd, buffer, Bitmap_File_Head.biSize - 4))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]);
Bitmap_Head.biHeight = ToL(&buffer[0x04]);
Bitmap_Head.biPlanes = ToS(&buffer[0x08]);
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);
Bitmap_Head.biCompr = ToL(&buffer[0x0C]);
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);
Bitmap_Head.biXPels = ToL(&buffer[0x14]);
Bitmap_Head.biYPels = ToL(&buffer[0x18]);
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]);
Bitmap_Head.biClrImp = ToL(&buffer[0x20]);
Bitmap_Head.masks[0] = ToL(&buffer[0x24]);
Bitmap_Head.masks[1] = ToL(&buffer[0x28]);
Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);
Bitmap_Head.masks[3] = ToL(&buffer[0x30]);
Maps = 4;
if (Bitmap_Head.biCompr == BI_BITFIELDS)
{
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);
}
else if (Bitmap_Head.biCompr == BI_RGB)
{
setMasksDefault(Bitmap_Head.biBitCnt, masks);
}
} else {
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
/* Valid options 1, 4, 8, 16, 24, 32 */
/* 16 is awful, we should probably shoot whoever invented it */
switch (Bitmap_Head.biBitCnt)
{
case 1:
case 2:
case 4:
case 8:
case 16:
case 24:
case 32:
break;
default:
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* There should be some colors used! */
ColormapSize = (Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps;
if ((Bitmap_Head.biClrUsed == 0) &&
(Bitmap_Head.biBitCnt <= 8))
{
ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt;
}
if (ColormapSize > 256)
ColormapSize = 256;
/* Sanity checks */
if (Bitmap_Head.biHeight == 0 ||
Bitmap_Head.biWidth == 0)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* biHeight may be negative, but -2147483648 is dangerous because:
-2147483648 == -(-2147483648) */
if (Bitmap_Head.biWidth < 0 ||
Bitmap_Head.biHeight == -2147483648)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (Bitmap_Head.biPlanes != 1)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (Bitmap_Head.biClrUsed > 256 &&
Bitmap_Head.biBitCnt <= 8)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* protect against integer overflows caused by malicious BMPs */
/* use divisions in comparisons to avoid type overflows */
if (((unsigned long)Bitmap_Head.biWidth) > (unsigned int)0x7fffffff / Bitmap_Head.biBitCnt ||
((unsigned long)Bitmap_Head.biWidth) > ((unsigned int)0x7fffffff /abs(Bitmap_Head.biHeight)) / 4)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* Windows and OS/2 declare filler so that rows are a multiple of
* word length (32 bits == 4 bytes)
*/
unsigned long overflowTest = Bitmap_Head.biWidth * Bitmap_Head.biBitCnt;
if (overflowTest / Bitmap_Head.biWidth != Bitmap_Head.biBitCnt) {
LOG("Error reading BMP file header. Width is too large\n");
at_exception_fatal(&exp, "Error reading BMP file header. Width is too large");
goto cleanup;
}
rowbytes = ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4;
#ifdef DEBUG
printf("\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, Comp: %u, Zeile: %u\n", Bitmap_File_Head.bfSize, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biWidth, Bitmap_Head.biHeight, Bitmap_Head.biCompr, rowbytes);
#endif
if (Bitmap_Head.biBitCnt <= 8)
{
#ifdef DEBUG
printf("Colormap read\n");
#endif
/* Get the Colormap */
if (!ReadColorMap(fd, ColorMap, ColormapSize, Maps, &Grey, &exp))
goto cleanup;
}
fseek(fd, Bitmap_File_Head.bfOffs, SEEK_SET);
/* Get the Image and return the ID or -1 on error */
image_storage = ReadImage(fd,
Bitmap_Head.biWidth, Bitmap_Head.biHeight,
ColorMap,
Bitmap_Head.biClrUsed,
Bitmap_Head.biBitCnt, Bitmap_Head.biCompr, rowbytes,
Grey,
masks,
&exp);
image = at_bitmap_init(image_storage, (unsigned short)Bitmap_Head.biWidth, (unsigned short)Bitmap_Head.biHeight, Grey ? 1 : 3);
cleanup:
fclose(fd);
return (image);
}
|
217805098145205715295086602544452101199
|
input-bmp.c
|
38605146891124325135879659140059354528
|
CWE-787
|
CVE-2022-32323
|
AutoTrace v0.40.0 was discovered to contain a heap overflow via the ReadImage function at input-bmp.c:660.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-32323
|
397,644
|
autotrace
|
e96bffadc25ff0ba0e10745f8012efcc5f920ea9
|
https://github.com/autotrace/autotrace
|
https://github.com/autotrace/autotrace/commit/e96bffadc25ff0ba0e10745f8012efcc5f920ea9
|
input-bmp: Increase header buffer in some cases
Signed-off-by: Peter Lemenkov <[email protected]>
| 0
|
at_bitmap input_bmp_reader(gchar * filename, at_input_opts_type * opts, at_msg_func msg_func, gpointer msg_data, gpointer user_data)
{
FILE *fd;
unsigned char buffer[128];
int ColormapSize, rowbytes, Maps;
gboolean Grey = FALSE;
unsigned char ColorMap[256][3];
at_bitmap image = at_bitmap_init(0, 0, 0, 1);
unsigned char *image_storage;
at_exception_type exp = at_exception_new(msg_func, msg_data);
char magick[2];
Bitmap_Channel masks[4];
fd = fopen(filename, "rb");
if (!fd) {
LOG("Can't open \"%s\"\n", filename);
at_exception_fatal(&exp, "bmp: cannot open input file");
goto cleanup;
}
/* It is a File. Now is it a Bitmap? Read the shortest possible header. */
if (!ReadOK(fd, magick, 2) ||
!(!strncmp(magick, "BA", 2) ||
!strncmp(magick, "BM", 2) ||
!strncmp(magick, "IC", 2) ||
!strncmp(magick, "PT", 2) ||
!strncmp(magick, "CI", 2) ||
!strncmp(magick, "CP", 2)))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
while (!strncmp(magick, "BA", 2))
{
if (!ReadOK(fd, buffer, 12))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (!ReadOK(fd, magick, 2))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
}
if (!ReadOK(fd, buffer, 12))////
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* bring them to the right byteorder. Not too nice, but it should work */
Bitmap_File_Head.bfSize = ToL(&buffer[0x00]);
Bitmap_File_Head.zzHotX = ToS(&buffer[0x04]);
Bitmap_File_Head.zzHotY = ToS(&buffer[0x06]);
Bitmap_File_Head.bfOffs = ToL(&buffer[0x08]);
if (!ReadOK(fd, buffer, 4))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
Bitmap_File_Head.biSize = ToL(&buffer[0x00]);
/* What kind of bitmap is it? */
if (Bitmap_File_Head.biSize == 12) { /* OS/2 1.x ? */
if (!ReadOK(fd, buffer, 8)) {
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToS(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToS(&buffer[0x02]); /* 14 */
Bitmap_Head.biPlanes = ToS(&buffer[0x04]); /* 16 */
Bitmap_Head.biBitCnt = ToS(&buffer[0x06]); /* 18 */
Bitmap_Head.biCompr = 0;
Bitmap_Head.biSizeIm = 0;
Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0;
Bitmap_Head.biClrUsed = 0;
Bitmap_Head.biClrImp = 0;
Bitmap_Head.masks[0] = 0;
Bitmap_Head.masks[1] = 0;
Bitmap_Head.masks[2] = 0;
Bitmap_Head.masks[3] = 0;
memset(masks, 0, sizeof(masks));
Maps = 3;
} else if (Bitmap_File_Head.biSize == 40) { /* Windows 3.x */
if (!ReadOK(fd, buffer, 36))
{
LOG ("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToL(&buffer[0x04]); /* 16 */
Bitmap_Head.biPlanes = ToS(&buffer[0x08]); /* 1A */
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]); /* 1C */
Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]); /* 22 */
Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */
Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */
Bitmap_Head.biClrImp = ToL(&buffer[0x20]); /* 32 */
Bitmap_Head.masks[0] = 0;
Bitmap_Head.masks[1] = 0;
Bitmap_Head.masks[2] = 0;
Bitmap_Head.masks[3] = 0;
Maps = 4;
memset(masks, 0, sizeof(masks));
if (Bitmap_Head.biCompr == BI_BITFIELDS)
{
if (!ReadOK(fd, buffer, 3 * sizeof(unsigned long)))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.masks[0] = ToL(&buffer[0x00]);
Bitmap_Head.masks[1] = ToL(&buffer[0x04]);
Bitmap_Head.masks[2] = ToL(&buffer[0x08]);
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 3);
}
else if (Bitmap_Head.biCompr == BI_RGB)
{
setMasksDefault(Bitmap_Head.biBitCnt, masks);
}
else if ((Bitmap_Head.biCompr != BI_RLE4) &&
(Bitmap_Head.biCompr != BI_RLE8))
{
/* BI_ALPHABITFIELDS, etc. */
LOG("Unsupported compression in BMP file\n");
at_exception_fatal(&exp, "Unsupported compression in BMP file");
goto cleanup;
}
}
else if (Bitmap_File_Head.biSize >= 56 &&
Bitmap_File_Head.biSize <= 64)
{
/* enhanced Windows format with bit masks */
if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToL(&buffer[0x04]); /* 16 */
Bitmap_Head.biPlanes = ToS(&buffer[0x08]); /* 1A */
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]); /* 1C */
Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]); /* 22 */
Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */
Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */
Bitmap_Head.biClrImp = ToL(&buffer[0x20]); /* 32 */
Bitmap_Head.masks[0] = ToL(&buffer[0x24]); /* 36 */
Bitmap_Head.masks[1] = ToL(&buffer[0x28]); /* 3A */
Bitmap_Head.masks[2] = ToL(&buffer[0x2C]); /* 3E */
Bitmap_Head.masks[3] = ToL(&buffer[0x30]); /* 42 */
Maps = 4;
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);
}
else if (Bitmap_File_Head.biSize == 108 ||
Bitmap_File_Head.biSize == 124)
{
/* BMP Version 4 or 5 */
if (!ReadOK(fd, buffer, Bitmap_File_Head.biSize - 4))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]);
Bitmap_Head.biHeight = ToL(&buffer[0x04]);
Bitmap_Head.biPlanes = ToS(&buffer[0x08]);
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);
Bitmap_Head.biCompr = ToL(&buffer[0x0C]);
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);
Bitmap_Head.biXPels = ToL(&buffer[0x14]);
Bitmap_Head.biYPels = ToL(&buffer[0x18]);
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]);
Bitmap_Head.biClrImp = ToL(&buffer[0x20]);
Bitmap_Head.masks[0] = ToL(&buffer[0x24]);
Bitmap_Head.masks[1] = ToL(&buffer[0x28]);
Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);
Bitmap_Head.masks[3] = ToL(&buffer[0x30]);
Maps = 4;
if (Bitmap_Head.biCompr == BI_BITFIELDS)
{
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);
}
else if (Bitmap_Head.biCompr == BI_RGB)
{
setMasksDefault(Bitmap_Head.biBitCnt, masks);
}
} else {
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
/* Valid options 1, 4, 8, 16, 24, 32 */
/* 16 is awful, we should probably shoot whoever invented it */
switch (Bitmap_Head.biBitCnt)
{
case 1:
case 2:
case 4:
case 8:
case 16:
case 24:
case 32:
break;
default:
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* There should be some colors used! */
ColormapSize = (Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps;
if ((Bitmap_Head.biClrUsed == 0) &&
(Bitmap_Head.biBitCnt <= 8))
{
ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt;
}
if (ColormapSize > 256)
ColormapSize = 256;
/* Sanity checks */
if (Bitmap_Head.biHeight == 0 ||
Bitmap_Head.biWidth == 0)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* biHeight may be negative, but -2147483648 is dangerous because:
-2147483648 == -(-2147483648) */
if (Bitmap_Head.biWidth < 0 ||
Bitmap_Head.biHeight == -2147483648)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (Bitmap_Head.biPlanes != 1)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (Bitmap_Head.biClrUsed > 256 &&
Bitmap_Head.biBitCnt <= 8)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* protect against integer overflows caused by malicious BMPs */
/* use divisions in comparisons to avoid type overflows */
if (((unsigned long)Bitmap_Head.biWidth) > (unsigned int)0x7fffffff / Bitmap_Head.biBitCnt ||
((unsigned long)Bitmap_Head.biWidth) > ((unsigned int)0x7fffffff /abs(Bitmap_Head.biHeight)) / 4)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* Windows and OS/2 declare filler so that rows are a multiple of
* word length (32 bits == 4 bytes)
*/
unsigned long overflowTest = Bitmap_Head.biWidth * Bitmap_Head.biBitCnt;
if (overflowTest / Bitmap_Head.biWidth != Bitmap_Head.biBitCnt) {
LOG("Error reading BMP file header. Width is too large\n");
at_exception_fatal(&exp, "Error reading BMP file header. Width is too large");
goto cleanup;
}
rowbytes = ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4;
#ifdef DEBUG
printf("\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, Comp: %u, Zeile: %u\n", Bitmap_File_Head.bfSize, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biWidth, Bitmap_Head.biHeight, Bitmap_Head.biCompr, rowbytes);
#endif
if (Bitmap_Head.biBitCnt <= 8)
{
#ifdef DEBUG
printf("Colormap read\n");
#endif
/* Get the Colormap */
if (!ReadColorMap(fd, ColorMap, ColormapSize, Maps, &Grey, &exp))
goto cleanup;
}
fseek(fd, Bitmap_File_Head.bfOffs, SEEK_SET);
/* Get the Image and return the ID or -1 on error */
image_storage = ReadImage(fd,
Bitmap_Head.biWidth, Bitmap_Head.biHeight,
ColorMap,
Bitmap_Head.biClrUsed,
Bitmap_Head.biBitCnt, Bitmap_Head.biCompr, rowbytes,
Grey,
masks,
&exp);
image = at_bitmap_init(image_storage, (unsigned short)Bitmap_Head.biWidth, (unsigned short)Bitmap_Head.biHeight, Grey ? 1 : 3);
cleanup:
fclose(fd);
return (image);
}
|
18153038985911000449594893666433988306
|
input-bmp.c
|
29852375577809733693857999744439179756
|
CWE-787
|
CVE-2022-32323
|
AutoTrace v0.40.0 was discovered to contain a heap overflow via the ReadImage function at input-bmp.c:660.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-32323
|
207,520
|
rizin
|
aa6917772d2f32e5a7daab25a46c72df0b5ea406
|
https://github.com/rizinorg/rizin
|
https://github.com/rizinorg/rizin/commit/aa6917772d2f32e5a7daab25a46c72df0b5ea406
|
Fix oob write for dwarf with abbrev with count 0 (Fix #2083) (#2086)
| 1
|
static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RzBinDwarfDebugInfo *info, RzBinDwarfAbbrevDecl *abbrev,
RzBinDwarfCompUnitHdr *hdr, RzBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, bool big_endian) {
size_t i;
const char *comp_dir = NULL;
ut64 line_info_offset = UT64_MAX;
for (i = 0; i < abbrev->count - 1; i++) {
memset(&die->attr_values[i], 0, sizeof(die->attr_values[i]));
buf = parse_attr_value(buf, buf_end - buf, &abbrev->defs[i],
&die->attr_values[i], hdr, debug_str, debug_str_len, big_endian);
RzBinDwarfAttrValue *attribute = &die->attr_values[i];
if (attribute->attr_name == DW_AT_comp_dir && (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string) && attribute->string.content) {
comp_dir = attribute->string.content;
}
if (attribute->attr_name == DW_AT_stmt_list) {
if (attribute->kind == DW_AT_KIND_CONSTANT) {
line_info_offset = attribute->uconstant;
} else if (attribute->kind == DW_AT_KIND_REFERENCE) {
line_info_offset = attribute->reference;
}
}
die->count++;
}
// If this is a compilation unit dir attribute, we want to cache it so the line info parsing
// which will need this info can quickly look it up.
if (comp_dir && line_info_offset != UT64_MAX) {
char *name = strdup(comp_dir);
if (name) {
if (!ht_up_insert(info->line_info_offset_comp_dir, line_info_offset, name)) {
free(name);
}
}
}
return buf;
}
|
26636529307671690704479532140631853142
|
dwarf.c
|
327051726619513035208543664099881519843
|
CWE-787
|
CVE-2021-43814
|
Rizin is a UNIX-like reverse engineering framework and command-line toolset. In versions up to and including 0.3.1 there is a heap-based out of bounds write in parse_die() when reversing an AMD64 ELF binary with DWARF debug info. When a malicious AMD64 ELF binary is opened by a victim user, Rizin may crash or execute unintended actions. No workaround are known and users are advised to upgrade.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-43814
|
398,518
|
rizin
|
aa6917772d2f32e5a7daab25a46c72df0b5ea406
|
https://github.com/rizinorg/rizin
|
https://github.com/rizinorg/rizin/commit/aa6917772d2f32e5a7daab25a46c72df0b5ea406
|
Fix oob write for dwarf with abbrev with count 0 (Fix #2083) (#2086)
| 0
|
static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RzBinDwarfDebugInfo *info, RzBinDwarfAbbrevDecl *abbrev,
RzBinDwarfCompUnitHdr *hdr, RzBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, bool big_endian) {
size_t i;
const char *comp_dir = NULL;
ut64 line_info_offset = UT64_MAX;
if (abbrev->count) {
for (i = 0; i < abbrev->count - 1; i++) {
memset(&die->attr_values[i], 0, sizeof(die->attr_values[i]));
buf = parse_attr_value(buf, buf_end - buf, &abbrev->defs[i],
&die->attr_values[i], hdr, debug_str, debug_str_len, big_endian);
RzBinDwarfAttrValue *attribute = &die->attr_values[i];
if (attribute->attr_name == DW_AT_comp_dir && (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string) && attribute->string.content) {
comp_dir = attribute->string.content;
}
if (attribute->attr_name == DW_AT_stmt_list) {
if (attribute->kind == DW_AT_KIND_CONSTANT) {
line_info_offset = attribute->uconstant;
} else if (attribute->kind == DW_AT_KIND_REFERENCE) {
line_info_offset = attribute->reference;
}
}
die->count++;
}
}
// If this is a compilation unit dir attribute, we want to cache it so the line info parsing
// which will need this info can quickly look it up.
if (comp_dir && line_info_offset != UT64_MAX) {
char *name = strdup(comp_dir);
if (name) {
if (!ht_up_insert(info->line_info_offset_comp_dir, line_info_offset, name)) {
free(name);
}
}
}
return buf;
}
|
51977580595649091612975538237343950990
|
dwarf.c
|
92035029709372705681125485016113687180
|
CWE-787
|
CVE-2021-43814
|
Rizin is a UNIX-like reverse engineering framework and command-line toolset. In versions up to and including 0.3.1 there is a heap-based out of bounds write in parse_die() when reversing an AMD64 ELF binary with DWARF debug info. When a malicious AMD64 ELF binary is opened by a victim user, Rizin may crash or execute unintended actions. No workaround are known and users are advised to upgrade.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-43814
|
207,700
|
EternalTerminal
|
900348bb8bc96e1c7ba4888ac8480f643c43d3c3
|
https://github.com/MisterTea/EternalTerminal
|
https://github.com/MisterTea/EternalTerminal/commit/900348bb8bc96e1c7ba4888ac8480f643c43d3c3
|
red fixes (#468)
* red fixes
* remove magic number
| 1
|
TerminalUserInfo UserTerminalRouter::getInfoForId(const string &id) {
auto it = idInfoMap.find(id);
if (it == idInfoMap.end()) {
STFATAL << " Tried to read from an id that no longer exists";
}
return it->second;
}
|
65652485071667159611859578809507103310
|
UserTerminalRouter.cpp
|
95512591738948248593704083286692164926
|
CWE-362
|
CVE-2022-24950
|
A race condition exists in Eternal Terminal prior to version 6.2.0 that allows an authenticated attacker to hijack other users' SSH authorization socket, enabling the attacker to login to other systems as the targeted users. The bug is in UserTerminalRouter::getInfoForId().
|
https://nvd.nist.gov/vuln/detail/CVE-2022-24950
|
400,109
|
EternalTerminal
|
900348bb8bc96e1c7ba4888ac8480f643c43d3c3
|
https://github.com/MisterTea/EternalTerminal
|
https://github.com/MisterTea/EternalTerminal/commit/900348bb8bc96e1c7ba4888ac8480f643c43d3c3
|
red fixes (#468)
* red fixes
* remove magic number
| 0
|
TerminalUserInfo UserTerminalRouter::getInfoForId(const string &id) {
lock_guard<recursive_mutex> guard(routerMutex);
auto it = idInfoMap.find(id);
if (it == idInfoMap.end()) {
STFATAL << " Tried to read from an id that no longer exists";
}
return it->second;
}
|
194538535842091525230611933768280108618
|
UserTerminalRouter.cpp
|
33756077495418666193931642880316711781
|
CWE-362
|
CVE-2022-24950
|
A race condition exists in Eternal Terminal prior to version 6.2.0 that allows an authenticated attacker to hijack other users' SSH authorization socket, enabling the attacker to login to other systems as the targeted users. The bug is in UserTerminalRouter::getInfoForId().
|
https://nvd.nist.gov/vuln/detail/CVE-2022-24950
|
207,703
|
EternalTerminal
|
900348bb8bc96e1c7ba4888ac8480f643c43d3c3
|
https://github.com/MisterTea/EternalTerminal
|
https://github.com/MisterTea/EternalTerminal/commit/900348bb8bc96e1c7ba4888ac8480f643c43d3c3
|
red fixes (#468)
* red fixes
* remove magic number
| 1
|
set<int> PipeSocketHandler::listen(const SocketEndpoint& endpoint) {
lock_guard<std::recursive_mutex> guard(globalMutex);
string pipePath = endpoint.name();
if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {
throw runtime_error("Tried to listen twice on the same path");
}
sockaddr_un local;
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
FATAL_FAIL(fd);
initServerSocket(fd);
local.sun_family = AF_UNIX; /* local is declared before socket() ^ */
strcpy(local.sun_path, pipePath.c_str());
unlink(local.sun_path);
FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));
::listen(fd, 5);
#ifndef WIN32
FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));
#endif
pipeServerSockets[pipePath] = set<int>({fd});
return pipeServerSockets[pipePath];
}
|
148534117660985776148799839801292812152
|
PipeSocketHandler.cpp
|
83158573064577402992437694952965778259
|
CWE-362
|
CVE-2022-24950
|
A race condition exists in Eternal Terminal prior to version 6.2.0 that allows an authenticated attacker to hijack other users' SSH authorization socket, enabling the attacker to login to other systems as the targeted users. The bug is in UserTerminalRouter::getInfoForId().
|
https://nvd.nist.gov/vuln/detail/CVE-2022-24950
|
400,103
|
EternalTerminal
|
900348bb8bc96e1c7ba4888ac8480f643c43d3c3
|
https://github.com/MisterTea/EternalTerminal
|
https://github.com/MisterTea/EternalTerminal/commit/900348bb8bc96e1c7ba4888ac8480f643c43d3c3
|
red fixes (#468)
* red fixes
* remove magic number
| 0
|
set<int> PipeSocketHandler::listen(const SocketEndpoint& endpoint) {
lock_guard<std::recursive_mutex> guard(globalMutex);
string pipePath = endpoint.name();
if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {
throw runtime_error("Tried to listen twice on the same path");
}
sockaddr_un local;
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
FATAL_FAIL(fd);
initServerSocket(fd);
local.sun_family = AF_UNIX; /* local is declared before socket() ^ */
strncpy(local.sun_path, pipePath.c_str(), sizeof(local.sun_path));
unlink(local.sun_path);
FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));
::listen(fd, 5);
#ifndef WIN32
FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));
#endif
pipeServerSockets[pipePath] = set<int>({fd});
return pipeServerSockets[pipePath];
}
|
36125659257824603505725557266857282888
|
PipeSocketHandler.cpp
|
231978839420872719355627255082595640778
|
CWE-362
|
CVE-2022-24950
|
A race condition exists in Eternal Terminal prior to version 6.2.0 that allows an authenticated attacker to hijack other users' SSH authorization socket, enabling the attacker to login to other systems as the targeted users. The bug is in UserTerminalRouter::getInfoForId().
|
https://nvd.nist.gov/vuln/detail/CVE-2022-24950
|
207,719
|
vim
|
e98c88c44c308edaea5994b8ad4363e65030968c
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/e98c88c44c308edaea5994b8ad4363e65030968c
|
patch 9.0.0218: reading before the start of the line
Problem: Reading before the start of the line.
Solution: When displaying "$" check the column is not negative.
| 1
|
display_dollar(colnr_T col)
{
colnr_T save_col;
if (!redrawing())
return;
cursor_off();
save_col = curwin->w_cursor.col;
curwin->w_cursor.col = col;
if (has_mbyte)
{
char_u *p;
// If on the last byte of a multi-byte move to the first byte.
p = ml_get_curline();
curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
}
curs_columns(FALSE); // recompute w_wrow and w_wcol
if (curwin->w_wcol < curwin->w_width)
{
edit_putchar('$', FALSE);
dollar_vcol = curwin->w_virtcol;
}
curwin->w_cursor.col = save_col;
}
|
56781688432244503822784219524894149055
|
edit.c
|
251788010034679613424556948955874474953
|
CWE-787
|
CVE-2022-2845
|
Improper Validation of Specified Quantity in Input in GitHub repository vim/vim prior to 9.0.0218.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2845
|
400,409
|
vim
|
e98c88c44c308edaea5994b8ad4363e65030968c
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/e98c88c44c308edaea5994b8ad4363e65030968c
|
patch 9.0.0218: reading before the start of the line
Problem: Reading before the start of the line.
Solution: When displaying "$" check the column is not negative.
| 0
|
display_dollar(colnr_T col_arg)
{
colnr_T col = col_arg < 0 ? 0 : col_arg;
colnr_T save_col;
if (!redrawing())
return;
cursor_off();
save_col = curwin->w_cursor.col;
curwin->w_cursor.col = col;
if (has_mbyte)
{
char_u *p;
// If on the last byte of a multi-byte move to the first byte.
p = ml_get_curline();
curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
}
curs_columns(FALSE); // recompute w_wrow and w_wcol
if (curwin->w_wcol < curwin->w_width)
{
edit_putchar('$', FALSE);
dollar_vcol = curwin->w_virtcol;
}
curwin->w_cursor.col = save_col;
}
|
125832747032800290670744012264167596321
|
edit.c
|
91657375912486719968624749742093008286
|
CWE-787
|
CVE-2022-2845
|
Improper Validation of Specified Quantity in Input in GitHub repository vim/vim prior to 9.0.0218.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2845
|
207,753
|
linux
|
9d2231c5d74e13b2a0546fee6737ee4446017903
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/9d2231c5d74e13b2a0546fee6737ee4446017903
|
lib/iov_iter: initialize "flags" in new pipe_buffer
The functions copy_page_to_iter_pipe() and push_pipe() can both
allocate a new pipe_buffer, but the "flags" member initializer is
missing.
Fixes: 241699cd72a8 ("new iov_iter flavour: pipe-backed")
To: Alexander Viro <[email protected]>
To: [email protected]
To: [email protected]
Cc: [email protected]
Signed-off-by: Max Kellermann <[email protected]>
Signed-off-by: Al Viro <[email protected]>
| 1
|
static size_t copy_page_to_iter_pipe(struct page *page, size_t offset, size_t bytes,
struct iov_iter *i)
{
struct pipe_inode_info *pipe = i->pipe;
struct pipe_buffer *buf;
unsigned int p_tail = pipe->tail;
unsigned int p_mask = pipe->ring_size - 1;
unsigned int i_head = i->head;
size_t off;
if (unlikely(bytes > i->count))
bytes = i->count;
if (unlikely(!bytes))
return 0;
if (!sanity(i))
return 0;
off = i->iov_offset;
buf = &pipe->bufs[i_head & p_mask];
if (off) {
if (offset == off && buf->page == page) {
/* merge with the last one */
buf->len += bytes;
i->iov_offset += bytes;
goto out;
}
i_head++;
buf = &pipe->bufs[i_head & p_mask];
}
if (pipe_full(i_head, p_tail, pipe->max_usage))
return 0;
buf->ops = &page_cache_pipe_buf_ops;
get_page(page);
buf->page = page;
buf->offset = offset;
buf->len = bytes;
pipe->head = i_head + 1;
i->iov_offset = offset + bytes;
i->head = i_head;
out:
i->count -= bytes;
return bytes;
}
|
167718514506109094299086513897213873936
|
iov_iter.c
|
181499146794090302160100800341530380411
|
CWE-284
|
CVE-2022-0847
|
A flaw was found in the way the "flags" member of the new pipe buffer structure was lacking proper initialization in copy_page_to_iter_pipe and push_pipe functions in the Linux kernel and could thus contain stale values. An unprivileged local user could use this flaw to write to pages in the page cache backed by read only files and as such escalate their privileges on the system.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0847
|
400,735
|
linux
|
9d2231c5d74e13b2a0546fee6737ee4446017903
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/9d2231c5d74e13b2a0546fee6737ee4446017903
|
lib/iov_iter: initialize "flags" in new pipe_buffer
The functions copy_page_to_iter_pipe() and push_pipe() can both
allocate a new pipe_buffer, but the "flags" member initializer is
missing.
Fixes: 241699cd72a8 ("new iov_iter flavour: pipe-backed")
To: Alexander Viro <[email protected]>
To: [email protected]
To: [email protected]
Cc: [email protected]
Signed-off-by: Max Kellermann <[email protected]>
Signed-off-by: Al Viro <[email protected]>
| 0
|
static size_t copy_page_to_iter_pipe(struct page *page, size_t offset, size_t bytes,
struct iov_iter *i)
{
struct pipe_inode_info *pipe = i->pipe;
struct pipe_buffer *buf;
unsigned int p_tail = pipe->tail;
unsigned int p_mask = pipe->ring_size - 1;
unsigned int i_head = i->head;
size_t off;
if (unlikely(bytes > i->count))
bytes = i->count;
if (unlikely(!bytes))
return 0;
if (!sanity(i))
return 0;
off = i->iov_offset;
buf = &pipe->bufs[i_head & p_mask];
if (off) {
if (offset == off && buf->page == page) {
/* merge with the last one */
buf->len += bytes;
i->iov_offset += bytes;
goto out;
}
i_head++;
buf = &pipe->bufs[i_head & p_mask];
}
if (pipe_full(i_head, p_tail, pipe->max_usage))
return 0;
buf->ops = &page_cache_pipe_buf_ops;
buf->flags = 0;
get_page(page);
buf->page = page;
buf->offset = offset;
buf->len = bytes;
pipe->head = i_head + 1;
i->iov_offset = offset + bytes;
i->head = i_head;
out:
i->count -= bytes;
return bytes;
}
|
254624609360113587487306617570895393083
|
iov_iter.c
|
158086795761237639591506235503715650431
|
CWE-284
|
CVE-2022-0847
|
A flaw was found in the way the "flags" member of the new pipe buffer structure was lacking proper initialization in copy_page_to_iter_pipe and push_pipe functions in the Linux kernel and could thus contain stale values. An unprivileged local user could use this flaw to write to pages in the page cache backed by read only files and as such escalate their privileges on the system.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0847
|
207,754
|
linux
|
9d2231c5d74e13b2a0546fee6737ee4446017903
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/9d2231c5d74e13b2a0546fee6737ee4446017903
|
lib/iov_iter: initialize "flags" in new pipe_buffer
The functions copy_page_to_iter_pipe() and push_pipe() can both
allocate a new pipe_buffer, but the "flags" member initializer is
missing.
Fixes: 241699cd72a8 ("new iov_iter flavour: pipe-backed")
To: Alexander Viro <[email protected]>
To: [email protected]
To: [email protected]
Cc: [email protected]
Signed-off-by: Max Kellermann <[email protected]>
Signed-off-by: Al Viro <[email protected]>
| 1
|
static size_t push_pipe(struct iov_iter *i, size_t size,
int *iter_headp, size_t *offp)
{
struct pipe_inode_info *pipe = i->pipe;
unsigned int p_tail = pipe->tail;
unsigned int p_mask = pipe->ring_size - 1;
unsigned int iter_head;
size_t off;
ssize_t left;
if (unlikely(size > i->count))
size = i->count;
if (unlikely(!size))
return 0;
left = size;
data_start(i, &iter_head, &off);
*iter_headp = iter_head;
*offp = off;
if (off) {
left -= PAGE_SIZE - off;
if (left <= 0) {
pipe->bufs[iter_head & p_mask].len += size;
return size;
}
pipe->bufs[iter_head & p_mask].len = PAGE_SIZE;
iter_head++;
}
while (!pipe_full(iter_head, p_tail, pipe->max_usage)) {
struct pipe_buffer *buf = &pipe->bufs[iter_head & p_mask];
struct page *page = alloc_page(GFP_USER);
if (!page)
break;
buf->ops = &default_pipe_buf_ops;
buf->page = page;
buf->offset = 0;
buf->len = min_t(ssize_t, left, PAGE_SIZE);
left -= buf->len;
iter_head++;
pipe->head = iter_head;
if (left == 0)
return size;
}
return size - left;
}
|
298985660493874547228624767727586322810
|
iov_iter.c
|
181499146794090302160100800341530380411
|
CWE-284
|
CVE-2022-0847
|
A flaw was found in the way the "flags" member of the new pipe buffer structure was lacking proper initialization in copy_page_to_iter_pipe and push_pipe functions in the Linux kernel and could thus contain stale values. An unprivileged local user could use this flaw to write to pages in the page cache backed by read only files and as such escalate their privileges on the system.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0847
|
400,743
|
linux
|
9d2231c5d74e13b2a0546fee6737ee4446017903
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/9d2231c5d74e13b2a0546fee6737ee4446017903
|
lib/iov_iter: initialize "flags" in new pipe_buffer
The functions copy_page_to_iter_pipe() and push_pipe() can both
allocate a new pipe_buffer, but the "flags" member initializer is
missing.
Fixes: 241699cd72a8 ("new iov_iter flavour: pipe-backed")
To: Alexander Viro <[email protected]>
To: [email protected]
To: [email protected]
Cc: [email protected]
Signed-off-by: Max Kellermann <[email protected]>
Signed-off-by: Al Viro <[email protected]>
| 0
|
static size_t push_pipe(struct iov_iter *i, size_t size,
int *iter_headp, size_t *offp)
{
struct pipe_inode_info *pipe = i->pipe;
unsigned int p_tail = pipe->tail;
unsigned int p_mask = pipe->ring_size - 1;
unsigned int iter_head;
size_t off;
ssize_t left;
if (unlikely(size > i->count))
size = i->count;
if (unlikely(!size))
return 0;
left = size;
data_start(i, &iter_head, &off);
*iter_headp = iter_head;
*offp = off;
if (off) {
left -= PAGE_SIZE - off;
if (left <= 0) {
pipe->bufs[iter_head & p_mask].len += size;
return size;
}
pipe->bufs[iter_head & p_mask].len = PAGE_SIZE;
iter_head++;
}
while (!pipe_full(iter_head, p_tail, pipe->max_usage)) {
struct pipe_buffer *buf = &pipe->bufs[iter_head & p_mask];
struct page *page = alloc_page(GFP_USER);
if (!page)
break;
buf->ops = &default_pipe_buf_ops;
buf->flags = 0;
buf->page = page;
buf->offset = 0;
buf->len = min_t(ssize_t, left, PAGE_SIZE);
left -= buf->len;
iter_head++;
pipe->head = iter_head;
if (left == 0)
return size;
}
return size - left;
}
|
276660368195834134822998399913502516107
|
iov_iter.c
|
158086795761237639591506235503715650431
|
CWE-284
|
CVE-2022-0847
|
A flaw was found in the way the "flags" member of the new pipe buffer structure was lacking proper initialization in copy_page_to_iter_pipe and push_pipe functions in the Linux kernel and could thus contain stale values. An unprivileged local user could use this flaw to write to pages in the page cache backed by read only files and as such escalate their privileges on the system.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0847
|
207,755
|
php-src
|
095cbc48a8f0090f3b0abc6155f2b61943c9eafb
|
https://github.com/php/php-src
|
http://git.php.net/?p=php-src.git;a=commitdiff;h=095cbc48a8f0090f3b0abc6155f2b61943c9eafb
|
Fix segfault in older versions of OpenSSL (before 0.9.8i)
| 1
|
PHP_FUNCTION(openssl_encrypt)
{
zend_bool raw_output = 0;
char *data, *method, *password, *iv = "";
int data_len, method_len, password_len, iv_len = 0, max_iv_len;
const EVP_CIPHER *cipher_type;
EVP_CIPHER_CTX cipher_ctx;
int i, outlen, keylen;
unsigned char *outbuf, *key;
zend_bool free_iv;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) {
return;
}
cipher_type = EVP_get_cipherbyname(method);
if (!cipher_type) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
keylen = EVP_CIPHER_key_length(cipher_type);
if (keylen > password_len) {
key = emalloc(keylen);
memset(key, 0, keylen);
memcpy(key, password, password_len);
} else {
key = (unsigned char*)password;
}
max_iv_len = EVP_CIPHER_iv_length(cipher_type);
if (iv_len <= 0 && max_iv_len > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended");
}
free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC);
outlen = data_len + EVP_CIPHER_block_size(cipher_type);
outbuf = emalloc(outlen + 1);
EVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL);
if (password_len > keylen) {
EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);
}
EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);
EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
outlen = i;
if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
outlen += i;
if (raw_output) {
outbuf[outlen] = '\0';
RETVAL_STRINGL((char *)outbuf, outlen, 0);
} else {
int base64_str_len;
char *base64_str;
base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);
efree(outbuf);
RETVAL_STRINGL(base64_str, base64_str_len, 0);
}
} else {
efree(outbuf);
RETVAL_FALSE;
}
if (key != (unsigned char*)password) {
efree(key);
}
if (free_iv) {
efree(iv);
}
EVP_CIPHER_CTX_cleanup(&cipher_ctx);
}
|
90779826180799829793304692194705605906
|
openssl.c
|
64204082198714090575154286576472678758
|
CWE-200
|
CVE-2012-6113
|
The openssl_encrypt function in ext/openssl/openssl.c in PHP 5.3.9 through 5.3.13 does not initialize a certain variable, which allows remote attackers to obtain sensitive information from process memory by providing zero bytes of input data.
|
https://nvd.nist.gov/vuln/detail/CVE-2012-6113
|
400,779
|
php-src
|
095cbc48a8f0090f3b0abc6155f2b61943c9eafb
|
https://github.com/php/php-src
|
http://git.php.net/?p=php-src.git;a=commitdiff;h=095cbc48a8f0090f3b0abc6155f2b61943c9eafb
|
Fix segfault in older versions of OpenSSL (before 0.9.8i)
| 0
|
PHP_FUNCTION(openssl_decrypt)
{
zend_bool raw_input = 0;
char *data, *method, *password, *iv = "";
int data_len, method_len, password_len, iv_len = 0;
const EVP_CIPHER *cipher_type;
EVP_CIPHER_CTX cipher_ctx;
int i, outlen, keylen;
unsigned char *outbuf, *key;
int base64_str_len;
char *base64_str = NULL;
zend_bool free_iv;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_input, &iv, &iv_len) == FAILURE) {
return;
}
if (!method_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
cipher_type = EVP_get_cipherbyname(method);
if (!cipher_type) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
if (!raw_input) {
base64_str = (char*)php_base64_decode((unsigned char*)data, data_len, &base64_str_len);
data_len = base64_str_len;
data = base64_str;
}
keylen = EVP_CIPHER_key_length(cipher_type);
if (keylen > password_len) {
key = emalloc(keylen);
memset(key, 0, keylen);
memcpy(key, password, password_len);
} else {
key = (unsigned char*)password;
}
free_iv = php_openssl_validate_iv(&iv, &iv_len, EVP_CIPHER_iv_length(cipher_type) TSRMLS_CC);
outlen = data_len + EVP_CIPHER_block_size(cipher_type);
outbuf = emalloc(outlen + 1);
EVP_DecryptInit(&cipher_ctx, cipher_type, NULL, NULL);
if (password_len > keylen) {
EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);
}
EVP_DecryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);
EVP_DecryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
outlen = i;
if (EVP_DecryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
outlen += i;
outbuf[outlen] = '\0';
RETVAL_STRINGL((char *)outbuf, outlen, 0);
} else {
efree(outbuf);
RETVAL_FALSE;
}
if (key != (unsigned char*)password) {
efree(key);
}
if (free_iv) {
efree(iv);
}
if (base64_str) {
efree(base64_str);
}
EVP_CIPHER_CTX_cleanup(&cipher_ctx);
}
|
39006034581830174999253498846151645941
|
openssl.c
|
57276947425832893910697869677062470849
|
CWE-200
|
CVE-2012-6113
|
The openssl_encrypt function in ext/openssl/openssl.c in PHP 5.3.9 through 5.3.13 does not initialize a certain variable, which allows remote attackers to obtain sensitive information from process memory by providing zero bytes of input data.
|
https://nvd.nist.gov/vuln/detail/CVE-2012-6113
|
207,780
|
radare2
|
2b77b277d67ce061ee6ef839e7139ebc2103c1e3
|
https://github.com/radare/radare2
|
https://github.com/radareorg/radare2/commit/2b77b277d67ce061ee6ef839e7139ebc2103c1e3
|
Fix oobread in dyldcache ##crash
* Reported by @hdthky via huntr.dev
* Reproducers: poc1
* BountyID: 8ae2c61a-2220-47a5-bfe8-fe6d41ab1f82
| 1
|
static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) {
RList *bins = r_list_newf ((RListFree)free_bin);
ut16 *depArray = NULL;
cache_imgxtr_t *extras = NULL;
if (!bins) {
return NULL;
}
char *target_libs = NULL;
RList *target_lib_names = NULL;
int *deps = NULL;
target_libs = r_sys_getenv ("R_DYLDCACHE_FILTER");
if (target_libs) {
target_lib_names = r_str_split_list (target_libs, ":", 0);
if (!target_lib_names) {
r_list_free (bins);
return NULL;
}
deps = R_NEWS0 (int, cache->hdr->imagesCount);
if (!deps) {
r_list_free (bins);
r_list_free (target_lib_names);
return NULL;
}
}
ut32 i;
for (i = 0; i < cache->n_hdr; i++) {
cache_hdr_t *hdr = &cache->hdr[i];
ut64 hdr_offset = cache->hdr_offset[i];
ut32 maps_index = cache->maps_index[i];
cache_img_t *img = read_cache_images (cache->buf, hdr, hdr_offset);
if (!img) {
goto next;
}
ut32 j;
if (target_libs) {
HtPU *path_to_idx = NULL;
if (cache->accel) {
depArray = R_NEWS0 (ut16, cache->accel->depListCount);
if (!depArray) {
goto next;
}
if (r_buf_fread_at (cache->buf, cache->accel->depListOffset, (ut8*) depArray, "s", cache->accel->depListCount) != cache->accel->depListCount * 2) {
goto next;
}
extras = read_cache_imgextra (cache->buf, hdr, cache->accel);
if (!extras) {
goto next;
}
} else {
path_to_idx = create_path_to_index (cache->buf, img, hdr);
}
for (j = 0; j < hdr->imagesCount; j++) {
bool printing = !deps[j];
char *lib_name = get_lib_name (cache->buf, &img[j]);
if (!lib_name) {
break;
}
if (strstr (lib_name, "libobjc.A.dylib")) {
deps[j]++;
}
if (!r_list_find (target_lib_names, lib_name, string_contains)) {
R_FREE (lib_name);
continue;
}
if (printing) {
eprintf ("FILTER: %s\n", lib_name);
}
R_FREE (lib_name);
deps[j]++;
if (extras && depArray) {
ut32 k;
for (k = extras[j].dependentsStartArrayIndex; depArray[k] != 0xffff; k++) {
ut16 dep_index = depArray[k] & 0x7fff;
deps[dep_index]++;
char *dep_name = get_lib_name (cache->buf, &img[dep_index]);
if (!dep_name) {
break;
}
if (printing) {
eprintf ("-> %s\n", dep_name);
}
free (dep_name);
}
} else if (path_to_idx) {
carve_deps_at_address (cache, img, path_to_idx, img[j].address, deps, printing);
}
}
ht_pu_free (path_to_idx);
R_FREE (depArray);
R_FREE (extras);
}
for (j = 0; j < hdr->imagesCount; j++) {
if (deps && !deps[j]) {
continue;
}
ut64 pa = va2pa (img[j].address, hdr->mappingCount, &cache->maps[maps_index], cache->buf, 0, NULL, NULL);
if (pa == UT64_MAX) {
continue;
}
ut8 magicbytes[4];
r_buf_read_at (cache->buf, pa, magicbytes, 4);
int magic = r_read_le32 (magicbytes);
switch (magic) {
case MH_MAGIC_64:
{
char file[256];
RDyldBinImage *bin = R_NEW0 (RDyldBinImage);
if (!bin) {
goto next;
}
bin->header_at = pa;
bin->hdr_offset = hdr_offset;
bin->symbols_off = resolve_symbols_off (cache, pa);
bin->va = img[j].address;
if (r_buf_read_at (cache->buf, img[j].pathFileOffset, (ut8*) &file, sizeof (file)) == sizeof (file)) {
file[255] = 0;
char *last_slash = strrchr (file, '/');
if (last_slash && *last_slash) {
if (last_slash > file) {
char *scan = last_slash - 1;
while (scan > file && *scan != '/') {
scan--;
}
if (*scan == '/') {
bin->file = strdup (scan + 1);
} else {
bin->file = strdup (last_slash + 1);
}
} else {
bin->file = strdup (last_slash + 1);
}
} else {
bin->file = strdup (file);
}
}
r_list_append (bins, bin);
break;
}
default:
eprintf ("Unknown sub-bin\n");
break;
}
}
next:
R_FREE (depArray);
R_FREE (extras);
R_FREE (img);
}
if (r_list_empty (bins)) {
r_list_free (bins);
bins = NULL;
}
R_FREE (deps);
R_FREE (target_libs);
r_list_free (target_lib_names);
return bins;
}
|
174827048480806807337685920262304563052
|
None
|
CWE-703
|
CVE-2022-1244
|
heap-buffer-overflow in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability is capable of inducing denial of service.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-1244
|
|
401,034
|
radare2
|
2b77b277d67ce061ee6ef839e7139ebc2103c1e3
|
https://github.com/radare/radare2
|
https://github.com/radareorg/radare2/commit/2b77b277d67ce061ee6ef839e7139ebc2103c1e3
|
Fix oobread in dyldcache ##crash
* Reported by @hdthky via huntr.dev
* Reproducers: poc1
* BountyID: 8ae2c61a-2220-47a5-bfe8-fe6d41ab1f82
| 0
|
static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) {
RList *bins = r_list_newf ((RListFree)free_bin);
ut16 *depArray = NULL;
cache_imgxtr_t *extras = NULL;
if (!bins) {
return NULL;
}
char *target_libs = NULL;
RList *target_lib_names = NULL;
int *deps = NULL;
target_libs = r_sys_getenv ("R_DYLDCACHE_FILTER");
if (target_libs) {
target_lib_names = r_str_split_list (target_libs, ":", 0);
if (!target_lib_names) {
r_list_free (bins);
return NULL;
}
deps = R_NEWS0 (int, cache->hdr->imagesCount);
if (!deps) {
r_list_free (bins);
r_list_free (target_lib_names);
return NULL;
}
}
ut32 i;
for (i = 0; i < cache->n_hdr; i++) {
cache_hdr_t *hdr = &cache->hdr[i];
ut64 hdr_offset = cache->hdr_offset[i];
ut32 maps_index = cache->maps_index[i];
cache_img_t *img = read_cache_images (cache->buf, hdr, hdr_offset);
if (!img) {
goto next;
}
ut32 j;
if (target_libs) {
HtPU *path_to_idx = NULL;
if (cache->accel) {
depArray = R_NEWS0 (ut16, cache->accel->depListCount);
if (!depArray) {
goto next;
}
if (r_buf_fread_at (cache->buf, cache->accel->depListOffset, (ut8*) depArray, "s", cache->accel->depListCount) != cache->accel->depListCount * 2) {
goto next;
}
extras = read_cache_imgextra (cache->buf, hdr, cache->accel);
if (!extras) {
goto next;
}
} else {
path_to_idx = create_path_to_index (cache->buf, img, hdr);
}
for (j = 0; j < hdr->imagesCount; j++) {
bool printing = !deps[j];
char *lib_name = get_lib_name (cache->buf, &img[j]);
if (!lib_name) {
break;
}
if (strstr (lib_name, "libobjc.A.dylib")) {
deps[j]++;
}
if (!r_list_find (target_lib_names, lib_name, string_contains)) {
R_FREE (lib_name);
continue;
}
if (printing) {
eprintf ("FILTER: %s\n", lib_name);
}
R_FREE (lib_name);
deps[j]++;
if (extras && depArray) {
ut32 k;
for (k = extras[j].dependentsStartArrayIndex; depArray[k] != 0xffff; k++) {
ut16 dep_index = depArray[k] & 0x7fff;
deps[dep_index]++;
char *dep_name = get_lib_name (cache->buf, &img[dep_index]);
if (!dep_name) {
break;
}
if (printing) {
eprintf ("-> %s\n", dep_name);
}
free (dep_name);
}
} else if (path_to_idx) {
carve_deps_at_address (cache, img, path_to_idx, img[j].address, deps, printing);
}
}
ht_pu_free (path_to_idx);
R_FREE (depArray);
R_FREE (extras);
}
for (j = 0; j < hdr->imagesCount; j++) {
if (deps && !deps[j]) {
continue;
}
// ut64 pa = va2pa (img[j].address, hdr->mappingCount, &cache->maps[maps_index], cache->buf, 0, NULL, NULL);
ut64 pa = va2pa (img[j].address, cache->n_maps, &cache->maps[maps_index], cache->buf, 0, NULL, NULL);
if (pa == UT64_MAX) {
continue;
}
ut8 magicbytes[4];
r_buf_read_at (cache->buf, pa, magicbytes, 4);
int magic = r_read_le32 (magicbytes);
switch (magic) {
case MH_MAGIC_64:
{
char file[256];
RDyldBinImage *bin = R_NEW0 (RDyldBinImage);
if (!bin) {
goto next;
}
bin->header_at = pa;
bin->hdr_offset = hdr_offset;
bin->symbols_off = resolve_symbols_off (cache, pa);
bin->va = img[j].address;
if (r_buf_read_at (cache->buf, img[j].pathFileOffset, (ut8*) &file, sizeof (file)) == sizeof (file)) {
file[255] = 0;
char *last_slash = strrchr (file, '/');
if (last_slash && *last_slash) {
if (last_slash > file) {
char *scan = last_slash - 1;
while (scan > file && *scan != '/') {
scan--;
}
if (*scan == '/') {
bin->file = strdup (scan + 1);
} else {
bin->file = strdup (last_slash + 1);
}
} else {
bin->file = strdup (last_slash + 1);
}
} else {
bin->file = strdup (file);
}
}
r_list_append (bins, bin);
break;
}
default:
eprintf ("Unknown sub-bin\n");
break;
}
}
next:
R_FREE (depArray);
R_FREE (extras);
R_FREE (img);
}
if (r_list_empty (bins)) {
r_list_free (bins);
bins = NULL;
}
R_FREE (deps);
R_FREE (target_libs);
r_list_free (target_lib_names);
return bins;
}
|
125973238096905171890400385176953298313
|
None
|
CWE-703
|
CVE-2022-1244
|
heap-buffer-overflow in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability is capable of inducing denial of service.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-1244
|
|
207,803
|
linux
|
f227e3ec3b5cad859ad15666874405e8c1bbc1d4
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/f227e3ec3b5cad859ad15666874405e8c1bbc1d4
|
random32: update the net random state on interrupt and activity
This modifies the first 32 bits out of the 128 bits of a random CPU's
net_rand_state on interrupt or CPU activity to complicate remote
observations that could lead to guessing the network RNG's internal
state.
Note that depending on some network devices' interrupt rate moderation
or binding, this re-seeding might happen on every packet or even almost
never.
In addition, with NOHZ some CPUs might not even get timer interrupts,
leaving their local state rarely updated, while they are running
networked processes making use of the random state. For this reason, we
also perform this update in update_process_times() in order to at least
update the state when there is user or system activity, since it's the
only case we care about.
Reported-by: Amit Klein <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: "Jason A. Donenfeld" <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
| 1
|
void add_interrupt_randomness(int irq, int irq_flags)
{
struct entropy_store *r;
struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
struct pt_regs *regs = get_irq_regs();
unsigned long now = jiffies;
cycles_t cycles = random_get_entropy();
__u32 c_high, j_high;
__u64 ip;
unsigned long seed;
int credit = 0;
if (cycles == 0)
cycles = get_reg(fast_pool, regs);
c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
j_high = (sizeof(now) > 4) ? now >> 32 : 0;
fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
fast_pool->pool[1] ^= now ^ c_high;
ip = regs ? instruction_pointer(regs) : _RET_IP_;
fast_pool->pool[2] ^= ip;
fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
get_reg(fast_pool, regs);
fast_mix(fast_pool);
add_interrupt_bench(cycles);
if (unlikely(crng_init == 0)) {
if ((fast_pool->count >= 64) &&
crng_fast_load((char *) fast_pool->pool,
sizeof(fast_pool->pool))) {
fast_pool->count = 0;
fast_pool->last = now;
}
return;
}
if ((fast_pool->count < 64) &&
!time_after(now, fast_pool->last + HZ))
return;
r = &input_pool;
if (!spin_trylock(&r->lock))
return;
fast_pool->last = now;
__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
/*
* If we have architectural seed generator, produce a seed and
* add it to the pool. For the sake of paranoia don't let the
* architectural seed generator dominate the input from the
* interrupt noise.
*/
if (arch_get_random_seed_long(&seed)) {
__mix_pool_bytes(r, &seed, sizeof(seed));
credit = 1;
}
spin_unlock(&r->lock);
fast_pool->count = 0;
/* award one bit for the contents of the fast pool */
credit_entropy_bits(r, credit + 1);
}
|
72986691588442626387015743278968252767
|
random.c
|
239066926887312120799410704296303486044
|
CWE-200
|
CVE-2020-16166
|
The Linux kernel through 5.7.11 allows remote attackers to make observations that help to obtain sensitive information about the internal state of the network RNG, aka CID-f227e3ec3b5c. This is related to drivers/char/random.c and kernel/time/timer.c.
|
https://nvd.nist.gov/vuln/detail/CVE-2020-16166
|
401,579
|
linux
|
f227e3ec3b5cad859ad15666874405e8c1bbc1d4
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/f227e3ec3b5cad859ad15666874405e8c1bbc1d4
|
random32: update the net random state on interrupt and activity
This modifies the first 32 bits out of the 128 bits of a random CPU's
net_rand_state on interrupt or CPU activity to complicate remote
observations that could lead to guessing the network RNG's internal
state.
Note that depending on some network devices' interrupt rate moderation
or binding, this re-seeding might happen on every packet or even almost
never.
In addition, with NOHZ some CPUs might not even get timer interrupts,
leaving their local state rarely updated, while they are running
networked processes making use of the random state. For this reason, we
also perform this update in update_process_times() in order to at least
update the state when there is user or system activity, since it's the
only case we care about.
Reported-by: Amit Klein <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: "Jason A. Donenfeld" <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
| 0
|
void add_interrupt_randomness(int irq, int irq_flags)
{
struct entropy_store *r;
struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
struct pt_regs *regs = get_irq_regs();
unsigned long now = jiffies;
cycles_t cycles = random_get_entropy();
__u32 c_high, j_high;
__u64 ip;
unsigned long seed;
int credit = 0;
if (cycles == 0)
cycles = get_reg(fast_pool, regs);
c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
j_high = (sizeof(now) > 4) ? now >> 32 : 0;
fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
fast_pool->pool[1] ^= now ^ c_high;
ip = regs ? instruction_pointer(regs) : _RET_IP_;
fast_pool->pool[2] ^= ip;
fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
get_reg(fast_pool, regs);
fast_mix(fast_pool);
add_interrupt_bench(cycles);
this_cpu_add(net_rand_state.s1, fast_pool->pool[cycles & 3]);
if (unlikely(crng_init == 0)) {
if ((fast_pool->count >= 64) &&
crng_fast_load((char *) fast_pool->pool,
sizeof(fast_pool->pool))) {
fast_pool->count = 0;
fast_pool->last = now;
}
return;
}
if ((fast_pool->count < 64) &&
!time_after(now, fast_pool->last + HZ))
return;
r = &input_pool;
if (!spin_trylock(&r->lock))
return;
fast_pool->last = now;
__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
/*
* If we have architectural seed generator, produce a seed and
* add it to the pool. For the sake of paranoia don't let the
* architectural seed generator dominate the input from the
* interrupt noise.
*/
if (arch_get_random_seed_long(&seed)) {
__mix_pool_bytes(r, &seed, sizeof(seed));
credit = 1;
}
spin_unlock(&r->lock);
fast_pool->count = 0;
/* award one bit for the contents of the fast pool */
credit_entropy_bits(r, credit + 1);
}
|
84995966578306698565240139293878155372
|
random.c
|
208560159054698027072406931437153087485
|
CWE-200
|
CVE-2020-16166
|
The Linux kernel through 5.7.11 allows remote attackers to make observations that help to obtain sensitive information about the internal state of the network RNG, aka CID-f227e3ec3b5c. This is related to drivers/char/random.c and kernel/time/timer.c.
|
https://nvd.nist.gov/vuln/detail/CVE-2020-16166
|
207,804
|
linux
|
f227e3ec3b5cad859ad15666874405e8c1bbc1d4
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/f227e3ec3b5cad859ad15666874405e8c1bbc1d4
|
random32: update the net random state on interrupt and activity
This modifies the first 32 bits out of the 128 bits of a random CPU's
net_rand_state on interrupt or CPU activity to complicate remote
observations that could lead to guessing the network RNG's internal
state.
Note that depending on some network devices' interrupt rate moderation
or binding, this re-seeding might happen on every packet or even almost
never.
In addition, with NOHZ some CPUs might not even get timer interrupts,
leaving their local state rarely updated, while they are running
networked processes making use of the random state. For this reason, we
also perform this update in update_process_times() in order to at least
update the state when there is user or system activity, since it's the
only case we care about.
Reported-by: Amit Klein <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: "Jason A. Donenfeld" <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
| 1
|
void update_process_times(int user_tick)
{
struct task_struct *p = current;
/* Note: this timer irq context must be accounted for as well. */
account_process_tick(p, user_tick);
run_local_timers();
rcu_sched_clock_irq(user_tick);
#ifdef CONFIG_IRQ_WORK
if (in_irq())
irq_work_tick();
#endif
scheduler_tick();
if (IS_ENABLED(CONFIG_POSIX_TIMERS))
run_posix_cpu_timers();
}
|
82612237012862358865324786376664956349
|
timer.c
|
271218236065045560355591111071365801019
|
CWE-200
|
CVE-2020-16166
|
The Linux kernel through 5.7.11 allows remote attackers to make observations that help to obtain sensitive information about the internal state of the network RNG, aka CID-f227e3ec3b5c. This is related to drivers/char/random.c and kernel/time/timer.c.
|
https://nvd.nist.gov/vuln/detail/CVE-2020-16166
|
401,525
|
linux
|
f227e3ec3b5cad859ad15666874405e8c1bbc1d4
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/f227e3ec3b5cad859ad15666874405e8c1bbc1d4
|
random32: update the net random state on interrupt and activity
This modifies the first 32 bits out of the 128 bits of a random CPU's
net_rand_state on interrupt or CPU activity to complicate remote
observations that could lead to guessing the network RNG's internal
state.
Note that depending on some network devices' interrupt rate moderation
or binding, this re-seeding might happen on every packet or even almost
never.
In addition, with NOHZ some CPUs might not even get timer interrupts,
leaving their local state rarely updated, while they are running
networked processes making use of the random state. For this reason, we
also perform this update in update_process_times() in order to at least
update the state when there is user or system activity, since it's the
only case we care about.
Reported-by: Amit Klein <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: "Jason A. Donenfeld" <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
| 0
|
void update_process_times(int user_tick)
{
struct task_struct *p = current;
/* Note: this timer irq context must be accounted for as well. */
account_process_tick(p, user_tick);
run_local_timers();
rcu_sched_clock_irq(user_tick);
#ifdef CONFIG_IRQ_WORK
if (in_irq())
irq_work_tick();
#endif
scheduler_tick();
if (IS_ENABLED(CONFIG_POSIX_TIMERS))
run_posix_cpu_timers();
/* The current CPU might make use of net randoms without receiving IRQs
* to renew them often enough. Let's update the net_rand_state from a
* non-constant value that's not affine to the number of calls to make
* sure it's updated when there's some activity (we don't care in idle).
*/
this_cpu_add(net_rand_state.s1, rol32(jiffies, 24) + user_tick);
}
|
311686403025993845778050249928014943417
|
timer.c
|
222103336435375278106670191376448375228
|
CWE-200
|
CVE-2020-16166
|
The Linux kernel through 5.7.11 allows remote attackers to make observations that help to obtain sensitive information about the internal state of the network RNG, aka CID-f227e3ec3b5c. This is related to drivers/char/random.c and kernel/time/timer.c.
|
https://nvd.nist.gov/vuln/detail/CVE-2020-16166
|
207,990
|
pcre2
|
03654e751e7f0700693526b67dfcadda6b42c9d0
|
https://github.com/PCRE2Project/pcre2
|
https://github.com/PCRE2Project/pcre2/commit/03654e751e7f0700693526b67dfcadda6b42c9d0
|
Fixed an issue affecting recursions in JIT
| 1
|
static int get_recurse_data_length(compiler_common *common, PCRE2_SPTR cc, PCRE2_SPTR ccend,
BOOL *needs_control_head, BOOL *has_quit, BOOL *has_accept)
{
int length = 1;
int size;
PCRE2_SPTR alternative;
BOOL quit_found = FALSE;
BOOL accept_found = FALSE;
BOOL setsom_found = FALSE;
BOOL setmark_found = FALSE;
BOOL capture_last_found = FALSE;
BOOL control_head_found = FALSE;
#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD
SLJIT_ASSERT(common->control_head_ptr != 0);
control_head_found = TRUE;
#endif
/* Calculate the sum of the private machine words. */
while (cc < ccend)
{
size = 0;
switch(*cc)
{
case OP_SET_SOM:
SLJIT_ASSERT(common->has_set_som);
setsom_found = TRUE;
cc += 1;
break;
case OP_RECURSE:
if (common->has_set_som)
setsom_found = TRUE;
if (common->mark_ptr != 0)
setmark_found = TRUE;
if (common->capture_last_ptr != 0)
capture_last_found = TRUE;
cc += 1 + LINK_SIZE;
break;
case OP_KET:
if (PRIVATE_DATA(cc) != 0)
{
length++;
SLJIT_ASSERT(PRIVATE_DATA(cc + 1) != 0);
cc += PRIVATE_DATA(cc + 1);
}
cc += 1 + LINK_SIZE;
break;
case OP_ASSERT:
case OP_ASSERT_NOT:
case OP_ASSERTBACK:
case OP_ASSERTBACK_NOT:
case OP_ASSERT_NA:
case OP_ASSERTBACK_NA:
case OP_ONCE:
case OP_SCRIPT_RUN:
case OP_BRAPOS:
case OP_SBRA:
case OP_SBRAPOS:
case OP_SCOND:
length++;
SLJIT_ASSERT(PRIVATE_DATA(cc) != 0);
cc += 1 + LINK_SIZE;
break;
case OP_CBRA:
case OP_SCBRA:
length += 2;
if (common->capture_last_ptr != 0)
capture_last_found = TRUE;
if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0)
length++;
cc += 1 + LINK_SIZE + IMM2_SIZE;
break;
case OP_CBRAPOS:
case OP_SCBRAPOS:
length += 2 + 2;
if (common->capture_last_ptr != 0)
capture_last_found = TRUE;
cc += 1 + LINK_SIZE + IMM2_SIZE;
break;
case OP_COND:
/* Might be a hidden SCOND. */
alternative = cc + GET(cc, 1);
if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN)
length++;
cc += 1 + LINK_SIZE;
break;
CASE_ITERATOR_PRIVATE_DATA_1
if (PRIVATE_DATA(cc) != 0)
length++;
cc += 2;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_PRIVATE_DATA_2A
if (PRIVATE_DATA(cc) != 0)
length += 2;
cc += 2;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_PRIVATE_DATA_2B
if (PRIVATE_DATA(cc) != 0)
length += 2;
cc += 2 + IMM2_SIZE;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_1
if (PRIVATE_DATA(cc) != 0)
length++;
cc += 1;
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_2A
if (PRIVATE_DATA(cc) != 0)
length += 2;
cc += 1;
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_2B
if (PRIVATE_DATA(cc) != 0)
length += 2;
cc += 1 + IMM2_SIZE;
break;
case OP_CLASS:
case OP_NCLASS:
#if defined SUPPORT_UNICODE || PCRE2_CODE_UNIT_WIDTH != 8
case OP_XCLASS:
size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(PCRE2_UCHAR);
#else
size = 1 + 32 / (int)sizeof(PCRE2_UCHAR);
#endif
if (PRIVATE_DATA(cc) != 0)
length += get_class_iterator_size(cc + size);
cc += size;
break;
case OP_MARK:
case OP_COMMIT_ARG:
case OP_PRUNE_ARG:
case OP_THEN_ARG:
SLJIT_ASSERT(common->mark_ptr != 0);
if (!setmark_found)
setmark_found = TRUE;
if (common->control_head_ptr != 0)
control_head_found = TRUE;
if (*cc != OP_MARK)
quit_found = TRUE;
cc += 1 + 2 + cc[1];
break;
case OP_PRUNE:
case OP_SKIP:
case OP_COMMIT:
quit_found = TRUE;
cc++;
break;
case OP_SKIP_ARG:
quit_found = TRUE;
cc += 1 + 2 + cc[1];
break;
case OP_THEN:
SLJIT_ASSERT(common->control_head_ptr != 0);
quit_found = TRUE;
if (!control_head_found)
control_head_found = TRUE;
cc++;
break;
case OP_ACCEPT:
case OP_ASSERT_ACCEPT:
accept_found = TRUE;
cc++;
break;
default:
cc = next_opcode(common, cc);
SLJIT_ASSERT(cc != NULL);
break;
}
}
SLJIT_ASSERT(cc == ccend);
if (control_head_found)
length++;
if (capture_last_found)
length++;
if (quit_found)
{
if (setsom_found)
length++;
if (setmark_found)
length++;
}
*needs_control_head = control_head_found;
*has_quit = quit_found;
*has_accept = accept_found;
return length;
}
|
240126232931244050288328890875640372325
|
pcre2_jit_compile.c
|
105541590302198799083513857874765354258
|
CWE-703
|
CVE-2022-1587
|
An out-of-bounds read vulnerability was discovered in the PCRE2 library in the get_recurse_data_length() function of the pcre2_jit_compile.c file. This issue affects recursions in JIT-compiled regular expressions caused by duplicate data transfers.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-1587
|
404,192
|
pcre2
|
03654e751e7f0700693526b67dfcadda6b42c9d0
|
https://github.com/PCRE2Project/pcre2
|
https://github.com/PCRE2Project/pcre2/commit/03654e751e7f0700693526b67dfcadda6b42c9d0
|
Fixed an issue affecting recursions in JIT
| 0
|
static int get_recurse_data_length(compiler_common *common, PCRE2_SPTR cc, PCRE2_SPTR ccend,
BOOL *needs_control_head, BOOL *has_quit, BOOL *has_accept)
{
int length = 1;
int size, offset;
PCRE2_SPTR alternative;
BOOL quit_found = FALSE;
BOOL accept_found = FALSE;
BOOL setsom_found = FALSE;
BOOL setmark_found = FALSE;
BOOL control_head_found = FALSE;
memset(common->recurse_bitset, 0, common->recurse_bitset_size);
#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD
SLJIT_ASSERT(common->control_head_ptr != 0);
control_head_found = TRUE;
#endif
/* Calculate the sum of the private machine words. */
while (cc < ccend)
{
size = 0;
switch(*cc)
{
case OP_SET_SOM:
SLJIT_ASSERT(common->has_set_som);
setsom_found = TRUE;
cc += 1;
break;
case OP_RECURSE:
if (common->has_set_som)
setsom_found = TRUE;
if (common->mark_ptr != 0)
setmark_found = TRUE;
if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))
length++;
cc += 1 + LINK_SIZE;
break;
case OP_KET:
offset = PRIVATE_DATA(cc);
if (offset != 0)
{
if (recurse_check_bit(common, offset))
length++;
SLJIT_ASSERT(PRIVATE_DATA(cc + 1) != 0);
cc += PRIVATE_DATA(cc + 1);
}
cc += 1 + LINK_SIZE;
break;
case OP_ASSERT:
case OP_ASSERT_NOT:
case OP_ASSERTBACK:
case OP_ASSERTBACK_NOT:
case OP_ASSERT_NA:
case OP_ASSERTBACK_NA:
case OP_ONCE:
case OP_SCRIPT_RUN:
case OP_BRAPOS:
case OP_SBRA:
case OP_SBRAPOS:
case OP_SCOND:
SLJIT_ASSERT(PRIVATE_DATA(cc) != 0);
if (recurse_check_bit(common, PRIVATE_DATA(cc)))
length++;
cc += 1 + LINK_SIZE;
break;
case OP_CBRA:
case OP_SCBRA:
offset = GET2(cc, 1 + LINK_SIZE);
if (recurse_check_bit(common, OVECTOR(offset << 1)))
{
SLJIT_ASSERT(recurse_check_bit(common, OVECTOR((offset << 1) + 1)));
length += 2;
}
if (common->optimized_cbracket[offset] == 0 && recurse_check_bit(common, OVECTOR_PRIV(offset)))
length++;
if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))
length++;
cc += 1 + LINK_SIZE + IMM2_SIZE;
break;
case OP_CBRAPOS:
case OP_SCBRAPOS:
offset = GET2(cc, 1 + LINK_SIZE);
if (recurse_check_bit(common, OVECTOR(offset << 1)))
{
SLJIT_ASSERT(recurse_check_bit(common, OVECTOR((offset << 1) + 1)));
length += 2;
}
if (recurse_check_bit(common, OVECTOR_PRIV(offset)))
length++;
if (recurse_check_bit(common, PRIVATE_DATA(cc)))
length++;
if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))
length++;
cc += 1 + LINK_SIZE + IMM2_SIZE;
break;
case OP_COND:
/* Might be a hidden SCOND. */
alternative = cc + GET(cc, 1);
if ((*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) && recurse_check_bit(common, PRIVATE_DATA(cc)))
length++;
cc += 1 + LINK_SIZE;
break;
CASE_ITERATOR_PRIVATE_DATA_1
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
length++;
cc += 2;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_PRIVATE_DATA_2A
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
{
SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));
length += 2;
}
cc += 2;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_PRIVATE_DATA_2B
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
{
SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));
length += 2;
}
cc += 2 + IMM2_SIZE;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_1
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
length++;
cc += 1;
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_2A
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
{
SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));
length += 2;
}
cc += 1;
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_2B
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
{
SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));
length += 2;
}
cc += 1 + IMM2_SIZE;
break;
case OP_CLASS:
case OP_NCLASS:
#if defined SUPPORT_UNICODE || PCRE2_CODE_UNIT_WIDTH != 8
case OP_XCLASS:
size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(PCRE2_UCHAR);
#else
size = 1 + 32 / (int)sizeof(PCRE2_UCHAR);
#endif
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
length += get_class_iterator_size(cc + size);
cc += size;
break;
case OP_MARK:
case OP_COMMIT_ARG:
case OP_PRUNE_ARG:
case OP_THEN_ARG:
SLJIT_ASSERT(common->mark_ptr != 0);
if (!setmark_found)
setmark_found = TRUE;
if (common->control_head_ptr != 0)
control_head_found = TRUE;
if (*cc != OP_MARK)
quit_found = TRUE;
cc += 1 + 2 + cc[1];
break;
case OP_PRUNE:
case OP_SKIP:
case OP_COMMIT:
quit_found = TRUE;
cc++;
break;
case OP_SKIP_ARG:
quit_found = TRUE;
cc += 1 + 2 + cc[1];
break;
case OP_THEN:
SLJIT_ASSERT(common->control_head_ptr != 0);
quit_found = TRUE;
control_head_found = TRUE;
cc++;
break;
case OP_ACCEPT:
case OP_ASSERT_ACCEPT:
accept_found = TRUE;
cc++;
break;
default:
cc = next_opcode(common, cc);
SLJIT_ASSERT(cc != NULL);
break;
}
}
SLJIT_ASSERT(cc == ccend);
if (control_head_found)
length++;
if (quit_found)
{
if (setsom_found)
length++;
if (setmark_found)
length++;
}
*needs_control_head = control_head_found;
*has_quit = quit_found;
*has_accept = accept_found;
return length;
}
|
173942933444712771516446324481674462692
|
pcre2_jit_compile.c
|
52374969195278947710795935639555031915
|
CWE-703
|
CVE-2022-1587
|
An out-of-bounds read vulnerability was discovered in the PCRE2 library in the get_recurse_data_length() function of the pcre2_jit_compile.c file. This issue affects recursions in JIT-compiled regular expressions caused by duplicate data transfers.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-1587
|
208,107
|
linux
|
f85daf0e725358be78dfd208dea5fd665d8cb901
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/f85daf0e725358be78dfd208dea5fd665d8cb901
|
xfrm: xfrm_policy: fix a possible double xfrm_pols_put() in xfrm_bundle_lookup()
xfrm_policy_lookup() will call xfrm_pol_hold_rcu() to get a refcount of
pols[0]. This refcount can be dropped in xfrm_expand_policies() when
xfrm_expand_policies() return error. pols[0]'s refcount is balanced in
here. But xfrm_bundle_lookup() will also call xfrm_pols_put() with
num_pols == 1 to drop this refcount when xfrm_expand_policies() return
error.
This patch also fix an illegal address access. pols[0] will save a error
point when xfrm_policy_lookup fails. This lead to xfrm_pols_put to resolve
an illegal address in xfrm_bundle_lookup's error path.
Fix these by setting num_pols = 0 in xfrm_expand_policies()'s error path.
Fixes: 80c802f3073e ("xfrm: cache bundles instead of policies for outgoing flows")
Signed-off-by: Hangyu Hua <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
| 1
|
static int xfrm_expand_policies(const struct flowi *fl, u16 family,
struct xfrm_policy **pols,
int *num_pols, int *num_xfrms)
{
int i;
if (*num_pols == 0 || !pols[0]) {
*num_pols = 0;
*num_xfrms = 0;
return 0;
}
if (IS_ERR(pols[0]))
return PTR_ERR(pols[0]);
*num_xfrms = pols[0]->xfrm_nr;
#ifdef CONFIG_XFRM_SUB_POLICY
if (pols[0]->action == XFRM_POLICY_ALLOW &&
pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
XFRM_POLICY_TYPE_MAIN,
fl, family,
XFRM_POLICY_OUT,
pols[0]->if_id);
if (pols[1]) {
if (IS_ERR(pols[1])) {
xfrm_pols_put(pols, *num_pols);
return PTR_ERR(pols[1]);
}
(*num_pols)++;
(*num_xfrms) += pols[1]->xfrm_nr;
}
}
#endif
for (i = 0; i < *num_pols; i++) {
if (pols[i]->action != XFRM_POLICY_ALLOW) {
*num_xfrms = -1;
break;
}
}
return 0;
}
|
251684023315514826982518858194996142213
|
xfrm_policy.c
|
240690312801703995044299112379503581676
|
CWE-703
|
CVE-2022-36879
|
An issue was discovered in the Linux kernel through 5.18.14. xfrm_expand_policies in net/xfrm/xfrm_policy.c can cause a refcount to be dropped twice.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-36879
|
405,333
|
linux
|
f85daf0e725358be78dfd208dea5fd665d8cb901
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/f85daf0e725358be78dfd208dea5fd665d8cb901
|
xfrm: xfrm_policy: fix a possible double xfrm_pols_put() in xfrm_bundle_lookup()
xfrm_policy_lookup() will call xfrm_pol_hold_rcu() to get a refcount of
pols[0]. This refcount can be dropped in xfrm_expand_policies() when
xfrm_expand_policies() return error. pols[0]'s refcount is balanced in
here. But xfrm_bundle_lookup() will also call xfrm_pols_put() with
num_pols == 1 to drop this refcount when xfrm_expand_policies() return
error.
This patch also fix an illegal address access. pols[0] will save a error
point when xfrm_policy_lookup fails. This lead to xfrm_pols_put to resolve
an illegal address in xfrm_bundle_lookup's error path.
Fix these by setting num_pols = 0 in xfrm_expand_policies()'s error path.
Fixes: 80c802f3073e ("xfrm: cache bundles instead of policies for outgoing flows")
Signed-off-by: Hangyu Hua <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
| 0
|
static int xfrm_expand_policies(const struct flowi *fl, u16 family,
struct xfrm_policy **pols,
int *num_pols, int *num_xfrms)
{
int i;
if (*num_pols == 0 || !pols[0]) {
*num_pols = 0;
*num_xfrms = 0;
return 0;
}
if (IS_ERR(pols[0])) {
*num_pols = 0;
return PTR_ERR(pols[0]);
}
*num_xfrms = pols[0]->xfrm_nr;
#ifdef CONFIG_XFRM_SUB_POLICY
if (pols[0]->action == XFRM_POLICY_ALLOW &&
pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
XFRM_POLICY_TYPE_MAIN,
fl, family,
XFRM_POLICY_OUT,
pols[0]->if_id);
if (pols[1]) {
if (IS_ERR(pols[1])) {
xfrm_pols_put(pols, *num_pols);
*num_pols = 0;
return PTR_ERR(pols[1]);
}
(*num_pols)++;
(*num_xfrms) += pols[1]->xfrm_nr;
}
}
#endif
for (i = 0; i < *num_pols; i++) {
if (pols[i]->action != XFRM_POLICY_ALLOW) {
*num_xfrms = -1;
break;
}
}
return 0;
}
|
29732626654088535700777069321150029090
|
xfrm_policy.c
|
264724924246430289692801756816591917107
|
CWE-703
|
CVE-2022-36879
|
An issue was discovered in the Linux kernel through 5.18.14. xfrm_expand_policies in net/xfrm/xfrm_policy.c can cause a refcount to be dropped twice.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-36879
|
208,115
|
linux
|
d0d62baa7f505bd4c59cd169692ff07ec49dde37
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/d0d62baa7f505bd4c59cd169692ff07ec49dde37
|
net: xilinx_emaclite: Do not print real IOMEM pointer
Printing kernel pointers is discouraged because they might leak kernel
memory layout. This fixes smatch warning:
drivers/net/ethernet/xilinx/xilinx_emaclite.c:1191 xemaclite_of_probe() warn:
argument 4 to %08lX specifier is cast from pointer
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
| 1
|
static int xemaclite_of_probe(struct platform_device *ofdev)
{
struct resource *res;
struct net_device *ndev = NULL;
struct net_local *lp = NULL;
struct device *dev = &ofdev->dev;
int rc = 0;
dev_info(dev, "Device Tree Probing\n");
/* Create an ethernet device instance */
ndev = alloc_etherdev(sizeof(struct net_local));
if (!ndev)
return -ENOMEM;
dev_set_drvdata(dev, ndev);
SET_NETDEV_DEV(ndev, &ofdev->dev);
lp = netdev_priv(ndev);
lp->ndev = ndev;
/* Get IRQ for the device */
res = platform_get_resource(ofdev, IORESOURCE_IRQ, 0);
if (!res) {
dev_err(dev, "no IRQ found\n");
rc = -ENXIO;
goto error;
}
ndev->irq = res->start;
res = platform_get_resource(ofdev, IORESOURCE_MEM, 0);
lp->base_addr = devm_ioremap_resource(&ofdev->dev, res);
if (IS_ERR(lp->base_addr)) {
rc = PTR_ERR(lp->base_addr);
goto error;
}
ndev->mem_start = res->start;
ndev->mem_end = res->end;
spin_lock_init(&lp->reset_lock);
lp->next_tx_buf_to_use = 0x0;
lp->next_rx_buf_to_use = 0x0;
lp->tx_ping_pong = get_bool(ofdev, "xlnx,tx-ping-pong");
lp->rx_ping_pong = get_bool(ofdev, "xlnx,rx-ping-pong");
rc = of_get_mac_address(ofdev->dev.of_node, ndev->dev_addr);
if (rc) {
dev_warn(dev, "No MAC address found, using random\n");
eth_hw_addr_random(ndev);
}
/* Clear the Tx CSR's in case this is a restart */
xemaclite_writel(0, lp->base_addr + XEL_TSR_OFFSET);
xemaclite_writel(0, lp->base_addr + XEL_BUFFER_OFFSET + XEL_TSR_OFFSET);
/* Set the MAC address in the EmacLite device */
xemaclite_update_address(lp, ndev->dev_addr);
lp->phy_node = of_parse_phandle(ofdev->dev.of_node, "phy-handle", 0);
xemaclite_mdio_setup(lp, &ofdev->dev);
dev_info(dev, "MAC address is now %pM\n", ndev->dev_addr);
ndev->netdev_ops = &xemaclite_netdev_ops;
ndev->ethtool_ops = &xemaclite_ethtool_ops;
ndev->flags &= ~IFF_MULTICAST;
ndev->watchdog_timeo = TX_TIMEOUT;
/* Finally, register the device */
rc = register_netdev(ndev);
if (rc) {
dev_err(dev,
"Cannot register network device, aborting\n");
goto error;
}
dev_info(dev,
"Xilinx EmacLite at 0x%08lX mapped to 0x%08lX, irq=%d\n",
(unsigned long __force)ndev->mem_start,
(unsigned long __force)lp->base_addr, ndev->irq);
return 0;
error:
free_netdev(ndev);
return rc;
}
|
7539144956808128275181130217400039273
|
xilinx_emaclite.c
|
195328153780575985681144288401844286686
|
CWE-703
|
CVE-2021-38205
|
drivers/net/ethernet/xilinx/xilinx_emaclite.c in the Linux kernel before 5.13.3 makes it easier for attackers to defeat an ASLR protection mechanism because it prints a kernel pointer (i.e., the real IOMEM pointer).
|
https://nvd.nist.gov/vuln/detail/CVE-2021-38205
|
405,698
|
linux
|
d0d62baa7f505bd4c59cd169692ff07ec49dde37
|
https://github.com/torvalds/linux
|
https://github.com/torvalds/linux/commit/d0d62baa7f505bd4c59cd169692ff07ec49dde37
|
net: xilinx_emaclite: Do not print real IOMEM pointer
Printing kernel pointers is discouraged because they might leak kernel
memory layout. This fixes smatch warning:
drivers/net/ethernet/xilinx/xilinx_emaclite.c:1191 xemaclite_of_probe() warn:
argument 4 to %08lX specifier is cast from pointer
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
| 0
|
static int xemaclite_of_probe(struct platform_device *ofdev)
{
struct resource *res;
struct net_device *ndev = NULL;
struct net_local *lp = NULL;
struct device *dev = &ofdev->dev;
int rc = 0;
dev_info(dev, "Device Tree Probing\n");
/* Create an ethernet device instance */
ndev = alloc_etherdev(sizeof(struct net_local));
if (!ndev)
return -ENOMEM;
dev_set_drvdata(dev, ndev);
SET_NETDEV_DEV(ndev, &ofdev->dev);
lp = netdev_priv(ndev);
lp->ndev = ndev;
/* Get IRQ for the device */
res = platform_get_resource(ofdev, IORESOURCE_IRQ, 0);
if (!res) {
dev_err(dev, "no IRQ found\n");
rc = -ENXIO;
goto error;
}
ndev->irq = res->start;
res = platform_get_resource(ofdev, IORESOURCE_MEM, 0);
lp->base_addr = devm_ioremap_resource(&ofdev->dev, res);
if (IS_ERR(lp->base_addr)) {
rc = PTR_ERR(lp->base_addr);
goto error;
}
ndev->mem_start = res->start;
ndev->mem_end = res->end;
spin_lock_init(&lp->reset_lock);
lp->next_tx_buf_to_use = 0x0;
lp->next_rx_buf_to_use = 0x0;
lp->tx_ping_pong = get_bool(ofdev, "xlnx,tx-ping-pong");
lp->rx_ping_pong = get_bool(ofdev, "xlnx,rx-ping-pong");
rc = of_get_mac_address(ofdev->dev.of_node, ndev->dev_addr);
if (rc) {
dev_warn(dev, "No MAC address found, using random\n");
eth_hw_addr_random(ndev);
}
/* Clear the Tx CSR's in case this is a restart */
xemaclite_writel(0, lp->base_addr + XEL_TSR_OFFSET);
xemaclite_writel(0, lp->base_addr + XEL_BUFFER_OFFSET + XEL_TSR_OFFSET);
/* Set the MAC address in the EmacLite device */
xemaclite_update_address(lp, ndev->dev_addr);
lp->phy_node = of_parse_phandle(ofdev->dev.of_node, "phy-handle", 0);
xemaclite_mdio_setup(lp, &ofdev->dev);
dev_info(dev, "MAC address is now %pM\n", ndev->dev_addr);
ndev->netdev_ops = &xemaclite_netdev_ops;
ndev->ethtool_ops = &xemaclite_ethtool_ops;
ndev->flags &= ~IFF_MULTICAST;
ndev->watchdog_timeo = TX_TIMEOUT;
/* Finally, register the device */
rc = register_netdev(ndev);
if (rc) {
dev_err(dev,
"Cannot register network device, aborting\n");
goto error;
}
dev_info(dev,
"Xilinx EmacLite at 0x%08lX mapped to 0x%p, irq=%d\n",
(unsigned long __force)ndev->mem_start, lp->base_addr, ndev->irq);
return 0;
error:
free_netdev(ndev);
return rc;
}
|
304374419764415204432847844541033449466
|
xilinx_emaclite.c
|
308517377946216969047380117029804691833
|
CWE-703
|
CVE-2021-38205
|
drivers/net/ethernet/xilinx/xilinx_emaclite.c in the Linux kernel before 5.13.3 makes it easier for attackers to defeat an ASLR protection mechanism because it prints a kernel pointer (i.e., the real IOMEM pointer).
|
https://nvd.nist.gov/vuln/detail/CVE-2021-38205
|
208,140
|
util-linux
|
5ebbc3865d1e53ef42e5f121c41faab23dd59075
|
https://github.com/karelzak/util-linux
|
http://git.kernel.org/?p=utils/util-linux/util-linux.git;a=commit;h=5ebbc3865d1e53ef42e5f121c41faab23dd59075
|
mount: sanitize paths from non-root users
$ mount /root/.ssh/../../dev/sda2
mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot
this is too promiscuous. It seems better to ignore on command line
specified paths which are not resolve-able for non-root users.
Fixed version:
$ mount /root/.ssh/../../dev/sda2
mount: /root/.ssh/../../dev/sda2: Permission denied
$ mount /dev/sda2
mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot
Note that this bug has no relation to mount(2) permissions evaluation
in suid mode. The way how non-root user specifies paths on command
line is completely irrelevant for comparison with fstab entries.
Signed-off-by: Karel Zak <[email protected]>
| 1
|
int main(int argc, char **argv)
{
int c, rc = MOUNT_EX_SUCCESS, all = 0, show_labels = 0;
struct libmnt_context *cxt;
struct libmnt_table *fstab = NULL;
char *srcbuf = NULL;
char *types = NULL;
unsigned long oper = 0;
enum {
MOUNT_OPT_SHARED = CHAR_MAX + 1,
MOUNT_OPT_SLAVE,
MOUNT_OPT_PRIVATE,
MOUNT_OPT_UNBINDABLE,
MOUNT_OPT_RSHARED,
MOUNT_OPT_RSLAVE,
MOUNT_OPT_RPRIVATE,
MOUNT_OPT_RUNBINDABLE,
MOUNT_OPT_TARGET,
MOUNT_OPT_SOURCE
};
static const struct option longopts[] = {
{ "all", 0, 0, 'a' },
{ "fake", 0, 0, 'f' },
{ "fstab", 1, 0, 'T' },
{ "fork", 0, 0, 'F' },
{ "help", 0, 0, 'h' },
{ "no-mtab", 0, 0, 'n' },
{ "read-only", 0, 0, 'r' },
{ "ro", 0, 0, 'r' },
{ "verbose", 0, 0, 'v' },
{ "version", 0, 0, 'V' },
{ "read-write", 0, 0, 'w' },
{ "rw", 0, 0, 'w' },
{ "options", 1, 0, 'o' },
{ "test-opts", 1, 0, 'O' },
{ "pass-fd", 1, 0, 'p' },
{ "types", 1, 0, 't' },
{ "uuid", 1, 0, 'U' },
{ "label", 1, 0, 'L'},
{ "bind", 0, 0, 'B' },
{ "move", 0, 0, 'M' },
{ "rbind", 0, 0, 'R' },
{ "make-shared", 0, 0, MOUNT_OPT_SHARED },
{ "make-slave", 0, 0, MOUNT_OPT_SLAVE },
{ "make-private", 0, 0, MOUNT_OPT_PRIVATE },
{ "make-unbindable", 0, 0, MOUNT_OPT_UNBINDABLE },
{ "make-rshared", 0, 0, MOUNT_OPT_RSHARED },
{ "make-rslave", 0, 0, MOUNT_OPT_RSLAVE },
{ "make-rprivate", 0, 0, MOUNT_OPT_RPRIVATE },
{ "make-runbindable", 0, 0, MOUNT_OPT_RUNBINDABLE },
{ "no-canonicalize", 0, 0, 'c' },
{ "internal-only", 0, 0, 'i' },
{ "show-labels", 0, 0, 'l' },
{ "target", 1, 0, MOUNT_OPT_TARGET },
{ "source", 1, 0, MOUNT_OPT_SOURCE },
{ NULL, 0, 0, 0 }
};
static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */
{ 'B','M','R', /* bind,move,rbind */
MOUNT_OPT_SHARED, MOUNT_OPT_SLAVE,
MOUNT_OPT_PRIVATE, MOUNT_OPT_UNBINDABLE,
MOUNT_OPT_RSHARED, MOUNT_OPT_RSLAVE,
MOUNT_OPT_RPRIVATE, MOUNT_OPT_RUNBINDABLE },
{ 'L','U', MOUNT_OPT_SOURCE }, /* label,uuid,source */
{ 0 }
};
int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
sanitize_env();
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
atexit(close_stdout);
mnt_init_debug(0);
cxt = mnt_new_context();
if (!cxt)
err(MOUNT_EX_SYSERR, _("libmount context allocation failed"));
mnt_context_set_tables_errcb(cxt, table_parser_errcb);
while ((c = getopt_long(argc, argv, "aBcfFhilL:Mno:O:p:rRsU:vVwt:T:",
longopts, NULL)) != -1) {
/* only few options are allowed for non-root users */
if (mnt_context_is_restricted(cxt) &&
!strchr("hlLUVvpris", c) &&
c != MOUNT_OPT_TARGET &&
c != MOUNT_OPT_SOURCE)
exit_non_root(option_to_longopt(c, longopts));
err_exclusive_options(c, longopts, excl, excl_st);
switch(c) {
case 'a':
all = 1;
break;
case 'c':
mnt_context_disable_canonicalize(cxt, TRUE);
break;
case 'f':
mnt_context_enable_fake(cxt, TRUE);
break;
case 'F':
mnt_context_enable_fork(cxt, TRUE);
break;
case 'h':
usage(stdout);
break;
case 'i':
mnt_context_disable_helpers(cxt, TRUE);
break;
case 'n':
mnt_context_disable_mtab(cxt, TRUE);
break;
case 'r':
if (mnt_context_append_options(cxt, "ro"))
err(MOUNT_EX_SYSERR, _("failed to append options"));
readwrite = 0;
break;
case 'v':
mnt_context_enable_verbose(cxt, TRUE);
break;
case 'V':
print_version();
break;
case 'w':
if (mnt_context_append_options(cxt, "rw"))
err(MOUNT_EX_SYSERR, _("failed to append options"));
readwrite = 1;
break;
case 'o':
if (mnt_context_append_options(cxt, optarg))
err(MOUNT_EX_SYSERR, _("failed to append options"));
break;
case 'O':
if (mnt_context_set_options_pattern(cxt, optarg))
err(MOUNT_EX_SYSERR, _("failed to set options pattern"));
break;
case 'p':
warnx(_("--pass-fd is no longer supported"));
break;
case 'L':
xasprintf(&srcbuf, "LABEL=\"%s\"", optarg);
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, srcbuf);
free(srcbuf);
break;
case 'U':
xasprintf(&srcbuf, "UUID=\"%s\"", optarg);
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, srcbuf);
free(srcbuf);
break;
case 'l':
show_labels = 1;
break;
case 't':
types = optarg;
break;
case 'T':
fstab = append_fstab(cxt, fstab, optarg);
break;
case 's':
mnt_context_enable_sloppy(cxt, TRUE);
break;
case 'B':
oper |= MS_BIND;
break;
case 'M':
oper |= MS_MOVE;
break;
case 'R':
oper |= (MS_BIND | MS_REC);
break;
case MOUNT_OPT_SHARED:
oper |= MS_SHARED;
break;
case MOUNT_OPT_SLAVE:
oper |= MS_SLAVE;
break;
case MOUNT_OPT_PRIVATE:
oper |= MS_PRIVATE;
break;
case MOUNT_OPT_UNBINDABLE:
oper |= MS_UNBINDABLE;
break;
case MOUNT_OPT_RSHARED:
oper |= (MS_SHARED | MS_REC);
break;
case MOUNT_OPT_RSLAVE:
oper |= (MS_SLAVE | MS_REC);
break;
case MOUNT_OPT_RPRIVATE:
oper |= (MS_PRIVATE | MS_REC);
break;
case MOUNT_OPT_RUNBINDABLE:
oper |= (MS_UNBINDABLE | MS_REC);
break;
case MOUNT_OPT_TARGET:
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_target(cxt, optarg);
break;
case MOUNT_OPT_SOURCE:
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, optarg);
break;
default:
usage(stderr);
break;
}
}
argc -= optind;
argv += optind;
if (fstab && !mnt_context_is_nocanonicalize(cxt)) {
/*
* We have external (context independent) fstab instance, let's
* make a connection between the fstab and the canonicalization
* cache.
*/
struct libmnt_cache *cache = mnt_context_get_cache(cxt);
mnt_table_set_cache(fstab, cache);
}
if (!mnt_context_get_source(cxt) &&
!mnt_context_get_target(cxt) &&
!argc &&
!all) {
if (oper)
usage(stderr);
print_all(cxt, types, show_labels);
goto done;
}
if (oper && (types || all || mnt_context_get_source(cxt)))
usage(stderr);
if (types && (all || strchr(types, ',') ||
strncmp(types, "no", 2) == 0))
mnt_context_set_fstype_pattern(cxt, types);
else if (types)
mnt_context_set_fstype(cxt, types);
if (all) {
/*
* A) Mount all
*/
rc = mount_all(cxt);
goto done;
} else if (argc == 0 && (mnt_context_get_source(cxt) ||
mnt_context_get_target(cxt))) {
/*
* B) mount -L|-U|--source|--target
*/
if (mnt_context_is_restricted(cxt) &&
mnt_context_get_source(cxt) &&
mnt_context_get_target(cxt))
exit_non_root(NULL);
} else if (argc == 1) {
/*
* C) mount [-L|-U|--source] <target>
* mount <source|target>
*
* non-root may specify source *or* target, but not both
*/
if (mnt_context_is_restricted(cxt) &&
mnt_context_get_source(cxt))
exit_non_root(NULL);
mnt_context_set_target(cxt, argv[0]);
} else if (argc == 2 && !mnt_context_get_source(cxt)
&& !mnt_context_get_target(cxt)) {
/*
* D) mount <source> <target>
*/
if (mnt_context_is_restricted(cxt))
exit_non_root(NULL);
mnt_context_set_source(cxt, argv[0]);
mnt_context_set_target(cxt, argv[1]);
} else
usage(stderr);
if (oper) {
/* MS_PROPAGATION operations, let's set the mount flags */
mnt_context_set_mflags(cxt, oper);
/* For -make* or --bind is fstab unnecessary */
mnt_context_set_optsmode(cxt, MNT_OMODE_NOTAB);
}
rc = mnt_context_mount(cxt);
rc = mk_exit_code(cxt, rc);
if (rc == MOUNT_EX_SUCCESS && mnt_context_is_verbose(cxt))
success_message(cxt);
done:
mnt_free_context(cxt);
mnt_free_table(fstab);
return rc;
}
|
219498005792940261578066564094421095366
|
mount.c
|
324534442685972817552003935079520935664
|
CWE-200
|
CVE-2013-0157
|
(a) mount and (b) umount in util-linux 2.14.1, 2.17.2, and probably other versions allow local users to determine the existence of restricted directories by (1) using the --guess-fstype command-line option or (2) attempting to mount a non-existent device, which generates different error messages depending on whether the directory exists.
|
https://nvd.nist.gov/vuln/detail/CVE-2013-0157
|
406,206
|
util-linux
|
5ebbc3865d1e53ef42e5f121c41faab23dd59075
|
https://github.com/karelzak/util-linux
|
http://git.kernel.org/?p=utils/util-linux/util-linux.git;a=commit;h=5ebbc3865d1e53ef42e5f121c41faab23dd59075
|
mount: sanitize paths from non-root users
$ mount /root/.ssh/../../dev/sda2
mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot
this is too promiscuous. It seems better to ignore on command line
specified paths which are not resolve-able for non-root users.
Fixed version:
$ mount /root/.ssh/../../dev/sda2
mount: /root/.ssh/../../dev/sda2: Permission denied
$ mount /dev/sda2
mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot
Note that this bug has no relation to mount(2) permissions evaluation
in suid mode. The way how non-root user specifies paths on command
line is completely irrelevant for comparison with fstab entries.
Signed-off-by: Karel Zak <[email protected]>
| 0
|
int main(int argc, char **argv)
{
int c, rc = MOUNT_EX_SUCCESS, all = 0, show_labels = 0;
struct libmnt_context *cxt;
struct libmnt_table *fstab = NULL;
char *srcbuf = NULL;
char *types = NULL;
unsigned long oper = 0;
enum {
MOUNT_OPT_SHARED = CHAR_MAX + 1,
MOUNT_OPT_SLAVE,
MOUNT_OPT_PRIVATE,
MOUNT_OPT_UNBINDABLE,
MOUNT_OPT_RSHARED,
MOUNT_OPT_RSLAVE,
MOUNT_OPT_RPRIVATE,
MOUNT_OPT_RUNBINDABLE,
MOUNT_OPT_TARGET,
MOUNT_OPT_SOURCE
};
static const struct option longopts[] = {
{ "all", 0, 0, 'a' },
{ "fake", 0, 0, 'f' },
{ "fstab", 1, 0, 'T' },
{ "fork", 0, 0, 'F' },
{ "help", 0, 0, 'h' },
{ "no-mtab", 0, 0, 'n' },
{ "read-only", 0, 0, 'r' },
{ "ro", 0, 0, 'r' },
{ "verbose", 0, 0, 'v' },
{ "version", 0, 0, 'V' },
{ "read-write", 0, 0, 'w' },
{ "rw", 0, 0, 'w' },
{ "options", 1, 0, 'o' },
{ "test-opts", 1, 0, 'O' },
{ "pass-fd", 1, 0, 'p' },
{ "types", 1, 0, 't' },
{ "uuid", 1, 0, 'U' },
{ "label", 1, 0, 'L'},
{ "bind", 0, 0, 'B' },
{ "move", 0, 0, 'M' },
{ "rbind", 0, 0, 'R' },
{ "make-shared", 0, 0, MOUNT_OPT_SHARED },
{ "make-slave", 0, 0, MOUNT_OPT_SLAVE },
{ "make-private", 0, 0, MOUNT_OPT_PRIVATE },
{ "make-unbindable", 0, 0, MOUNT_OPT_UNBINDABLE },
{ "make-rshared", 0, 0, MOUNT_OPT_RSHARED },
{ "make-rslave", 0, 0, MOUNT_OPT_RSLAVE },
{ "make-rprivate", 0, 0, MOUNT_OPT_RPRIVATE },
{ "make-runbindable", 0, 0, MOUNT_OPT_RUNBINDABLE },
{ "no-canonicalize", 0, 0, 'c' },
{ "internal-only", 0, 0, 'i' },
{ "show-labels", 0, 0, 'l' },
{ "target", 1, 0, MOUNT_OPT_TARGET },
{ "source", 1, 0, MOUNT_OPT_SOURCE },
{ NULL, 0, 0, 0 }
};
static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */
{ 'B','M','R', /* bind,move,rbind */
MOUNT_OPT_SHARED, MOUNT_OPT_SLAVE,
MOUNT_OPT_PRIVATE, MOUNT_OPT_UNBINDABLE,
MOUNT_OPT_RSHARED, MOUNT_OPT_RSLAVE,
MOUNT_OPT_RPRIVATE, MOUNT_OPT_RUNBINDABLE },
{ 'L','U', MOUNT_OPT_SOURCE }, /* label,uuid,source */
{ 0 }
};
int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
sanitize_env();
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
atexit(close_stdout);
mnt_init_debug(0);
cxt = mnt_new_context();
if (!cxt)
err(MOUNT_EX_SYSERR, _("libmount context allocation failed"));
mnt_context_set_tables_errcb(cxt, table_parser_errcb);
while ((c = getopt_long(argc, argv, "aBcfFhilL:Mno:O:p:rRsU:vVwt:T:",
longopts, NULL)) != -1) {
/* only few options are allowed for non-root users */
if (mnt_context_is_restricted(cxt) &&
!strchr("hlLUVvpris", c) &&
c != MOUNT_OPT_TARGET &&
c != MOUNT_OPT_SOURCE)
exit_non_root(option_to_longopt(c, longopts));
err_exclusive_options(c, longopts, excl, excl_st);
switch(c) {
case 'a':
all = 1;
break;
case 'c':
mnt_context_disable_canonicalize(cxt, TRUE);
break;
case 'f':
mnt_context_enable_fake(cxt, TRUE);
break;
case 'F':
mnt_context_enable_fork(cxt, TRUE);
break;
case 'h':
usage(stdout);
break;
case 'i':
mnt_context_disable_helpers(cxt, TRUE);
break;
case 'n':
mnt_context_disable_mtab(cxt, TRUE);
break;
case 'r':
if (mnt_context_append_options(cxt, "ro"))
err(MOUNT_EX_SYSERR, _("failed to append options"));
readwrite = 0;
break;
case 'v':
mnt_context_enable_verbose(cxt, TRUE);
break;
case 'V':
print_version();
break;
case 'w':
if (mnt_context_append_options(cxt, "rw"))
err(MOUNT_EX_SYSERR, _("failed to append options"));
readwrite = 1;
break;
case 'o':
if (mnt_context_append_options(cxt, optarg))
err(MOUNT_EX_SYSERR, _("failed to append options"));
break;
case 'O':
if (mnt_context_set_options_pattern(cxt, optarg))
err(MOUNT_EX_SYSERR, _("failed to set options pattern"));
break;
case 'p':
warnx(_("--pass-fd is no longer supported"));
break;
case 'L':
xasprintf(&srcbuf, "LABEL=\"%s\"", optarg);
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, srcbuf);
free(srcbuf);
break;
case 'U':
xasprintf(&srcbuf, "UUID=\"%s\"", optarg);
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, srcbuf);
free(srcbuf);
break;
case 'l':
show_labels = 1;
break;
case 't':
types = optarg;
break;
case 'T':
fstab = append_fstab(cxt, fstab, optarg);
break;
case 's':
mnt_context_enable_sloppy(cxt, TRUE);
break;
case 'B':
oper |= MS_BIND;
break;
case 'M':
oper |= MS_MOVE;
break;
case 'R':
oper |= (MS_BIND | MS_REC);
break;
case MOUNT_OPT_SHARED:
oper |= MS_SHARED;
break;
case MOUNT_OPT_SLAVE:
oper |= MS_SLAVE;
break;
case MOUNT_OPT_PRIVATE:
oper |= MS_PRIVATE;
break;
case MOUNT_OPT_UNBINDABLE:
oper |= MS_UNBINDABLE;
break;
case MOUNT_OPT_RSHARED:
oper |= (MS_SHARED | MS_REC);
break;
case MOUNT_OPT_RSLAVE:
oper |= (MS_SLAVE | MS_REC);
break;
case MOUNT_OPT_RPRIVATE:
oper |= (MS_PRIVATE | MS_REC);
break;
case MOUNT_OPT_RUNBINDABLE:
oper |= (MS_UNBINDABLE | MS_REC);
break;
case MOUNT_OPT_TARGET:
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_target(cxt, optarg);
break;
case MOUNT_OPT_SOURCE:
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, optarg);
break;
default:
usage(stderr);
break;
}
}
argc -= optind;
argv += optind;
if (fstab && !mnt_context_is_nocanonicalize(cxt)) {
/*
* We have external (context independent) fstab instance, let's
* make a connection between the fstab and the canonicalization
* cache.
*/
struct libmnt_cache *cache = mnt_context_get_cache(cxt);
mnt_table_set_cache(fstab, cache);
}
if (!mnt_context_get_source(cxt) &&
!mnt_context_get_target(cxt) &&
!argc &&
!all) {
if (oper)
usage(stderr);
print_all(cxt, types, show_labels);
goto done;
}
if (oper && (types || all || mnt_context_get_source(cxt)))
usage(stderr);
if (types && (all || strchr(types, ',') ||
strncmp(types, "no", 2) == 0))
mnt_context_set_fstype_pattern(cxt, types);
else if (types)
mnt_context_set_fstype(cxt, types);
if (all) {
/*
* A) Mount all
*/
rc = mount_all(cxt);
goto done;
} else if (argc == 0 && (mnt_context_get_source(cxt) ||
mnt_context_get_target(cxt))) {
/*
* B) mount -L|-U|--source|--target
*/
if (mnt_context_is_restricted(cxt) &&
mnt_context_get_source(cxt) &&
mnt_context_get_target(cxt))
exit_non_root(NULL);
} else if (argc == 1) {
/*
* C) mount [-L|-U|--source] <target>
* mount <source|target>
*
* non-root may specify source *or* target, but not both
*/
if (mnt_context_is_restricted(cxt) &&
mnt_context_get_source(cxt))
exit_non_root(NULL);
mnt_context_set_target(cxt, argv[0]);
} else if (argc == 2 && !mnt_context_get_source(cxt)
&& !mnt_context_get_target(cxt)) {
/*
* D) mount <source> <target>
*/
if (mnt_context_is_restricted(cxt))
exit_non_root(NULL);
mnt_context_set_source(cxt, argv[0]);
mnt_context_set_target(cxt, argv[1]);
} else
usage(stderr);
if (mnt_context_is_restricted(cxt))
sanitize_paths(cxt);
if (oper) {
/* MS_PROPAGATION operations, let's set the mount flags */
mnt_context_set_mflags(cxt, oper);
/* For -make* or --bind is fstab unnecessary */
mnt_context_set_optsmode(cxt, MNT_OMODE_NOTAB);
}
rc = mnt_context_mount(cxt);
rc = mk_exit_code(cxt, rc);
if (rc == MOUNT_EX_SUCCESS && mnt_context_is_verbose(cxt))
success_message(cxt);
done:
mnt_free_context(cxt);
mnt_free_table(fstab);
return rc;
}
|
43692452455655783216200177030716124780
|
mount.c
|
7925930289343170386207247806304317495
|
CWE-200
|
CVE-2013-0157
|
(a) mount and (b) umount in util-linux 2.14.1, 2.17.2, and probably other versions allow local users to determine the existence of restricted directories by (1) using the --guess-fstype command-line option or (2) attempting to mount a non-existent device, which generates different error messages depending on whether the directory exists.
|
https://nvd.nist.gov/vuln/detail/CVE-2013-0157
|
208,370
|
vim
|
806d037671e133bd28a7864248763f643967973a
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/806d037671e133bd28a7864248763f643967973a
|
patch 8.2.4218: illegal memory access with bracketed paste in Ex mode
Problem: Illegal memory access with bracketed paste in Ex mode.
Solution: Reserve space for the trailing NUL.
| 1
|
bracketed_paste(paste_mode_T mode, int drop, garray_T *gap)
{
int c;
char_u buf[NUMBUFLEN + MB_MAXBYTES];
int idx = 0;
char_u *end = find_termcode((char_u *)"PE");
int ret_char = -1;
int save_allow_keys = allow_keys;
int save_paste = p_paste;
// If the end code is too long we can't detect it, read everything.
if (end != NULL && STRLEN(end) >= NUMBUFLEN)
end = NULL;
++no_mapping;
allow_keys = 0;
if (!p_paste)
// Also have the side effects of setting 'paste' to make it work much
// faster.
set_option_value((char_u *)"paste", TRUE, NULL, 0);
for (;;)
{
// When the end is not defined read everything there is.
if (end == NULL && vpeekc() == NUL)
break;
do
c = vgetc();
while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
if (c == NUL || got_int || (ex_normal_busy > 0 && c == Ctrl_C))
// When CTRL-C was encountered the typeahead will be flushed and we
// won't get the end sequence. Except when using ":normal".
break;
if (has_mbyte)
idx += (*mb_char2bytes)(c, buf + idx);
else
buf[idx++] = c;
buf[idx] = NUL;
if (end != NULL && STRNCMP(buf, end, idx) == 0)
{
if (end[idx] == NUL)
break; // Found the end of paste code.
continue;
}
if (!drop)
{
switch (mode)
{
case PASTE_CMDLINE:
put_on_cmdline(buf, idx, TRUE);
break;
case PASTE_EX:
if (gap != NULL && ga_grow(gap, idx) == OK)
{
mch_memmove((char *)gap->ga_data + gap->ga_len,
buf, (size_t)idx);
gap->ga_len += idx;
}
break;
case PASTE_INSERT:
if (stop_arrow() == OK)
{
c = buf[0];
if (idx == 1 && (c == CAR || c == K_KENTER || c == NL))
ins_eol(c);
else
{
ins_char_bytes(buf, idx);
AppendToRedobuffLit(buf, idx);
}
}
break;
case PASTE_ONE_CHAR:
if (ret_char == -1)
{
if (has_mbyte)
ret_char = (*mb_ptr2char)(buf);
else
ret_char = buf[0];
}
break;
}
}
idx = 0;
}
--no_mapping;
allow_keys = save_allow_keys;
if (!save_paste)
set_option_value((char_u *)"paste", FALSE, NULL, 0);
return ret_char;
}
|
304493990488783960232843007629982350455
|
edit.c
|
253330379214920739736877102106471261423
|
CWE-787
|
CVE-2022-0392
|
Heap-based Buffer Overflow in GitHub repository vim prior to 8.2.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0392
|
408,968
|
vim
|
806d037671e133bd28a7864248763f643967973a
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/806d037671e133bd28a7864248763f643967973a
|
patch 8.2.4218: illegal memory access with bracketed paste in Ex mode
Problem: Illegal memory access with bracketed paste in Ex mode.
Solution: Reserve space for the trailing NUL.
| 0
|
bracketed_paste(paste_mode_T mode, int drop, garray_T *gap)
{
int c;
char_u buf[NUMBUFLEN + MB_MAXBYTES];
int idx = 0;
char_u *end = find_termcode((char_u *)"PE");
int ret_char = -1;
int save_allow_keys = allow_keys;
int save_paste = p_paste;
// If the end code is too long we can't detect it, read everything.
if (end != NULL && STRLEN(end) >= NUMBUFLEN)
end = NULL;
++no_mapping;
allow_keys = 0;
if (!p_paste)
// Also have the side effects of setting 'paste' to make it work much
// faster.
set_option_value((char_u *)"paste", TRUE, NULL, 0);
for (;;)
{
// When the end is not defined read everything there is.
if (end == NULL && vpeekc() == NUL)
break;
do
c = vgetc();
while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
if (c == NUL || got_int || (ex_normal_busy > 0 && c == Ctrl_C))
// When CTRL-C was encountered the typeahead will be flushed and we
// won't get the end sequence. Except when using ":normal".
break;
if (has_mbyte)
idx += (*mb_char2bytes)(c, buf + idx);
else
buf[idx++] = c;
buf[idx] = NUL;
if (end != NULL && STRNCMP(buf, end, idx) == 0)
{
if (end[idx] == NUL)
break; // Found the end of paste code.
continue;
}
if (!drop)
{
switch (mode)
{
case PASTE_CMDLINE:
put_on_cmdline(buf, idx, TRUE);
break;
case PASTE_EX:
// add one for the NUL that is going to be appended
if (gap != NULL && ga_grow(gap, idx + 1) == OK)
{
mch_memmove((char *)gap->ga_data + gap->ga_len,
buf, (size_t)idx);
gap->ga_len += idx;
}
break;
case PASTE_INSERT:
if (stop_arrow() == OK)
{
c = buf[0];
if (idx == 1 && (c == CAR || c == K_KENTER || c == NL))
ins_eol(c);
else
{
ins_char_bytes(buf, idx);
AppendToRedobuffLit(buf, idx);
}
}
break;
case PASTE_ONE_CHAR:
if (ret_char == -1)
{
if (has_mbyte)
ret_char = (*mb_ptr2char)(buf);
else
ret_char = buf[0];
}
break;
}
}
idx = 0;
}
--no_mapping;
allow_keys = save_allow_keys;
if (!save_paste)
set_option_value((char_u *)"paste", FALSE, NULL, 0);
return ret_char;
}
|
237228533852438658740165650986586610988
|
edit.c
|
72953735620149631855784875265490970900
|
CWE-787
|
CVE-2022-0392
|
Heap-based Buffer Overflow in GitHub repository vim prior to 8.2.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0392
|
208,411
|
vim
|
27efc62f5d86afcb2ecb7565587fe8dea4b036fe
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/27efc62f5d86afcb2ecb7565587fe8dea4b036fe
|
patch 9.0.0018: going over the end of the typahead
Problem: Going over the end of the typahead.
Solution: Put a NUL after the typeahead.
| 1
|
check_termcode(
int max_offset,
char_u *buf,
int bufsize,
int *buflen)
{
char_u *tp;
char_u *p;
int slen = 0; // init for GCC
int modslen;
int len;
int retval = 0;
int offset;
char_u key_name[2];
int modifiers;
char_u *modifiers_start = NULL;
int key;
int new_slen; // Length of what will replace the termcode
char_u string[MAX_KEY_CODE_LEN + 1];
int i, j;
int idx = 0;
int cpo_koffset;
cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL);
/*
* Speed up the checks for terminal codes by gathering all first bytes
* used in termleader[]. Often this is just a single <Esc>.
*/
if (need_gather)
gather_termleader();
/*
* Check at several positions in typebuf.tb_buf[], to catch something like
* "x<Up>" that can be mapped. Stop at max_offset, because characters
* after that cannot be used for mapping, and with @r commands
* typebuf.tb_buf[] can become very long.
* This is used often, KEEP IT FAST!
*/
for (offset = 0; offset < max_offset; ++offset)
{
if (buf == NULL)
{
if (offset >= typebuf.tb_len)
break;
tp = typebuf.tb_buf + typebuf.tb_off + offset;
len = typebuf.tb_len - offset; // length of the input
}
else
{
if (offset >= *buflen)
break;
tp = buf + offset;
len = *buflen - offset;
}
/*
* Don't check characters after K_SPECIAL, those are already
* translated terminal chars (avoid translating ~@^Hx).
*/
if (*tp == K_SPECIAL)
{
offset += 2; // there are always 2 extra characters
continue;
}
/*
* Skip this position if the character does not appear as the first
* character in term_strings. This speeds up a lot, since most
* termcodes start with the same character (ESC or CSI).
*/
i = *tp;
for (p = termleader; *p && *p != i; ++p)
;
if (*p == NUL)
continue;
/*
* Skip this position if p_ek is not set and tp[0] is an ESC and we
* are in Insert mode.
*/
if (*tp == ESC && !p_ek && (State & MODE_INSERT))
continue;
key_name[0] = NUL; // no key name found yet
key_name[1] = NUL; // no key name found yet
modifiers = 0; // no modifiers yet
#ifdef FEAT_GUI
if (gui.in_use)
{
/*
* GUI special key codes are all of the form [CSI xx].
*/
if (*tp == CSI) // Special key from GUI
{
if (len < 3)
return -1; // Shouldn't happen
slen = 3;
key_name[0] = tp[1];
key_name[1] = tp[2];
}
}
else
#endif // FEAT_GUI
{
int mouse_index_found = -1;
for (idx = 0; idx < tc_len; ++idx)
{
/*
* Ignore the entry if we are not at the start of
* typebuf.tb_buf[]
* and there are not enough characters to make a match.
* But only when the 'K' flag is in 'cpoptions'.
*/
slen = termcodes[idx].len;
modifiers_start = NULL;
if (cpo_koffset && offset && len < slen)
continue;
if (STRNCMP(termcodes[idx].code, tp,
(size_t)(slen > len ? len : slen)) == 0)
{
int looks_like_mouse_start = FALSE;
if (len < slen) // got a partial sequence
return -1; // need to get more chars
/*
* When found a keypad key, check if there is another key
* that matches and use that one. This makes <Home> to be
* found instead of <kHome> when they produce the same
* key code.
*/
if (termcodes[idx].name[0] == 'K'
&& VIM_ISDIGIT(termcodes[idx].name[1]))
{
for (j = idx + 1; j < tc_len; ++j)
if (termcodes[j].len == slen &&
STRNCMP(termcodes[idx].code,
termcodes[j].code, slen) == 0)
{
idx = j;
break;
}
}
if (slen == 2 && len > 2
&& termcodes[idx].code[0] == ESC
&& termcodes[idx].code[1] == '[')
{
// The mouse termcode "ESC [" is also the prefix of
// "ESC [ I" (focus gained) and other keys. Check some
// more bytes to find out.
if (!isdigit(tp[2]))
{
// ESC [ without number following: Only use it when
// there is no other match.
looks_like_mouse_start = TRUE;
}
else if (termcodes[idx].name[0] == KS_DEC_MOUSE)
{
char_u *nr = tp + 2;
int count = 0;
// If a digit is following it could be a key with
// modifier, e.g., ESC [ 1;2P. Can be confused
// with DEC_MOUSE, which requires four numbers
// following. If not then it can't be a DEC_MOUSE
// code.
for (;;)
{
++count;
(void)getdigits(&nr);
if (nr >= tp + len)
return -1; // partial sequence
if (*nr != ';')
break;
++nr;
if (nr >= tp + len)
return -1; // partial sequence
}
if (count < 4)
continue; // no match
}
}
if (looks_like_mouse_start)
{
// Only use it when there is no other match.
if (mouse_index_found < 0)
mouse_index_found = idx;
}
else
{
key_name[0] = termcodes[idx].name[0];
key_name[1] = termcodes[idx].name[1];
break;
}
}
/*
* Check for code with modifier, like xterm uses:
* <Esc>[123;*X (modslen == slen - 3)
* <Esc>[@;*X (matches <Esc>[X and <Esc>[1;9X )
* Also <Esc>O*X and <M-O>*X (modslen == slen - 2).
* When there is a modifier the * matches a number.
* When there is no modifier the ;* or * is omitted.
*/
if (termcodes[idx].modlen > 0 && mouse_index_found < 0)
{
int at_code;
modslen = termcodes[idx].modlen;
if (cpo_koffset && offset && len < modslen)
continue;
at_code = termcodes[idx].code[modslen] == '@';
if (STRNCMP(termcodes[idx].code, tp,
(size_t)(modslen > len ? len : modslen)) == 0)
{
int n;
if (len <= modslen) // got a partial sequence
return -1; // need to get more chars
if (tp[modslen] == termcodes[idx].code[slen - 1])
// no modifiers
slen = modslen + 1;
else if (tp[modslen] != ';' && modslen == slen - 3)
// no match for "code;*X" with "code;"
continue;
else if (at_code && tp[modslen] != '1')
// no match for "<Esc>[@" with "<Esc>[1"
continue;
else
{
// Skip over the digits, the final char must
// follow. URXVT can use a negative value, thus
// also accept '-'.
for (j = slen - 2; j < len && (isdigit(tp[j])
|| tp[j] == '-' || tp[j] == ';'); ++j)
;
++j;
if (len < j) // got a partial sequence
return -1; // need to get more chars
if (tp[j - 1] != termcodes[idx].code[slen - 1])
continue; // no match
modifiers_start = tp + slen - 2;
// Match! Convert modifier bits.
n = atoi((char *)modifiers_start);
modifiers |= decode_modifiers(n);
slen = j;
}
key_name[0] = termcodes[idx].name[0];
key_name[1] = termcodes[idx].name[1];
break;
}
}
}
if (idx == tc_len && mouse_index_found >= 0)
{
key_name[0] = termcodes[mouse_index_found].name[0];
key_name[1] = termcodes[mouse_index_found].name[1];
}
}
#ifdef FEAT_TERMRESPONSE
if (key_name[0] == NUL
// Mouse codes of DEC and pterm start with <ESC>[. When
// detecting the start of these mouse codes they might as well be
// another key code or terminal response.
# ifdef FEAT_MOUSE_DEC
|| key_name[0] == KS_DEC_MOUSE
# endif
# ifdef FEAT_MOUSE_PTERM
|| key_name[0] == KS_PTERM_MOUSE
# endif
)
{
char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1;
/*
* Check for responses from the terminal starting with {lead}:
* "<Esc>[" or CSI followed by [0-9>?]
*
* - Xterm version string: {lead}>{x};{vers};{y}c
* Also eat other possible responses to t_RV, rxvt returns
* "{lead}?1;2c".
*
* - Cursor position report: {lead}{row};{col}R
* The final byte must be 'R'. It is used for checking the
* ambiguous-width character state.
*
* - window position reply: {lead}3;{x};{y}t
*
* - key with modifiers when modifyOtherKeys is enabled:
* {lead}27;{modifier};{key}~
* {lead}{key};{modifier}u
*/
if (((tp[0] == ESC && len >= 3 && tp[1] == '[')
|| (tp[0] == CSI && len >= 2))
&& (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?'))
{
int resp = handle_csi(tp, len, argp, offset, buf,
bufsize, buflen, key_name, &slen);
if (resp != 0)
{
# ifdef DEBUG_TERMRESPONSE
if (resp == -1)
LOG_TR(("Not enough characters for CSI sequence"));
# endif
return resp;
}
}
// Check for fore/background color response from the terminal,
// starting} with <Esc>] or OSC
else if ((*T_RBG != NUL || *T_RFG != NUL)
&& ((tp[0] == ESC && len >= 2 && tp[1] == ']')
|| tp[0] == OSC))
{
if (handle_osc(tp, argp, len, key_name, &slen) == FAIL)
return -1;
}
// Check for key code response from xterm,
// starting with <Esc>P or DCS
else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT)
&& ((tp[0] == ESC && len >= 2 && tp[1] == 'P')
|| tp[0] == DCS))
{
if (handle_dcs(tp, argp, len, key_name, &slen) == FAIL)
return -1;
}
}
#endif
if (key_name[0] == NUL)
continue; // No match at this position, try next one
// We only get here when we have a complete termcode match
#ifdef FEAT_GUI
/*
* Only in the GUI: Fetch the pointer coordinates of the scroll event
* so that we know which window to scroll later.
*/
if (gui.in_use
&& key_name[0] == (int)KS_EXTRA
&& (key_name[1] == (int)KE_X1MOUSE
|| key_name[1] == (int)KE_X2MOUSE
|| key_name[1] == (int)KE_MOUSEMOVE_XY
|| key_name[1] == (int)KE_MOUSELEFT
|| key_name[1] == (int)KE_MOUSERIGHT
|| key_name[1] == (int)KE_MOUSEDOWN
|| key_name[1] == (int)KE_MOUSEUP))
{
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 4);
if (num_bytes == -1) // not enough coordinates
return -1;
mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1;
mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1;
slen += num_bytes;
// equal to K_MOUSEMOVE
if (key_name[1] == (int)KE_MOUSEMOVE_XY)
key_name[1] = (int)KE_MOUSEMOVE;
}
else
#endif
/*
* If it is a mouse click, get the coordinates.
*/
if (key_name[0] == KS_MOUSE
#ifdef FEAT_MOUSE_GPM
|| key_name[0] == KS_GPM_MOUSE
#endif
#ifdef FEAT_MOUSE_JSB
|| key_name[0] == KS_JSBTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_NET
|| key_name[0] == KS_NETTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_DEC
|| key_name[0] == KS_DEC_MOUSE
#endif
#ifdef FEAT_MOUSE_PTERM
|| key_name[0] == KS_PTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_URXVT
|| key_name[0] == KS_URXVT_MOUSE
#endif
|| key_name[0] == KS_SGR_MOUSE
|| key_name[0] == KS_SGR_MOUSE_RELEASE)
{
if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx,
&modifiers) == -1)
return -1;
}
#ifdef FEAT_GUI
/*
* If using the GUI, then we get menu and scrollbar events.
*
* A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by
* four bytes which are to be taken as a pointer to the vimmenu_T
* structure.
*
* A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where "nr"
* is one byte with the tab index.
*
* A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed
* by one byte representing the scrollbar number, and then four bytes
* representing a long_u which is the new value of the scrollbar.
*
* A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,
* KE_FILLER followed by four bytes representing a long_u which is the
* new value of the scrollbar.
*/
# ifdef FEAT_MENU
else if (key_name[0] == (int)KS_MENU)
{
long_u val;
int num_bytes = get_long_from_buf(tp + slen, &val);
if (num_bytes == -1)
return -1;
current_menu = (vimmenu_T *)val;
slen += num_bytes;
// The menu may have been deleted right after it was used, check
// for that.
if (check_menu_pointer(root_menu, current_menu) == FAIL)
{
key_name[0] = KS_EXTRA;
key_name[1] = (int)KE_IGNORE;
}
}
# endif
# ifdef FEAT_GUI_TABLINE
else if (key_name[0] == (int)KS_TABLINE)
{
// Selecting tabline tab or using its menu.
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 1);
if (num_bytes == -1)
return -1;
current_tab = (int)bytes[0];
if (current_tab == 255) // -1 in a byte gives 255
current_tab = -1;
slen += num_bytes;
}
else if (key_name[0] == (int)KS_TABMENU)
{
// Selecting tabline tab or using its menu.
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 2);
if (num_bytes == -1)
return -1;
current_tab = (int)bytes[0];
current_tabmenu = (int)bytes[1];
slen += num_bytes;
}
# endif
# ifndef USE_ON_FLY_SCROLL
else if (key_name[0] == (int)KS_VER_SCROLLBAR)
{
long_u val;
char_u bytes[6];
int num_bytes;
// Get the last scrollbar event in the queue of the same type
j = 0;
for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR
&& tp[j + 2] != NUL; ++i)
{
j += 3;
num_bytes = get_bytes_from_buf(tp + j, bytes, 1);
if (num_bytes == -1)
break;
if (i == 0)
current_scrollbar = (int)bytes[0];
else if (current_scrollbar != (int)bytes[0])
break;
j += num_bytes;
num_bytes = get_long_from_buf(tp + j, &val);
if (num_bytes == -1)
break;
scrollbar_value = val;
j += num_bytes;
slen = j;
}
if (i == 0) // not enough characters to make one
return -1;
}
else if (key_name[0] == (int)KS_HOR_SCROLLBAR)
{
long_u val;
int num_bytes;
// Get the last horiz. scrollbar event in the queue
j = 0;
for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR
&& tp[j + 2] != NUL; ++i)
{
j += 3;
num_bytes = get_long_from_buf(tp + j, &val);
if (num_bytes == -1)
break;
scrollbar_value = val;
j += num_bytes;
slen = j;
}
if (i == 0) // not enough characters to make one
return -1;
}
# endif // !USE_ON_FLY_SCROLL
#endif // FEAT_GUI
#if (defined(UNIX) || defined(VMS))
/*
* Handle FocusIn/FocusOut event sequences reported by XTerm.
* (CSI I/CSI O)
*/
if (key_name[0] == KS_EXTRA
# ifdef FEAT_GUI
&& !gui.in_use
# endif
)
{
if (key_name[1] == KE_FOCUSGAINED)
{
if (!focus_state)
{
ui_focus_change(TRUE);
did_cursorhold = TRUE;
focus_state = TRUE;
}
key_name[1] = (int)KE_IGNORE;
}
else if (key_name[1] == KE_FOCUSLOST)
{
if (focus_state)
{
ui_focus_change(FALSE);
did_cursorhold = TRUE;
focus_state = FALSE;
}
key_name[1] = (int)KE_IGNORE;
}
}
#endif
/*
* Change <xHome> to <Home>, <xUp> to <Up>, etc.
*/
key = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1]));
/*
* Add any modifier codes to our string.
*/
new_slen = modifiers2keycode(modifiers, &key, string);
// Finally, add the special key code to our string
key_name[0] = KEY2TERMCAP0(key);
key_name[1] = KEY2TERMCAP1(key);
if (key_name[0] == KS_KEY)
{
// from ":set <M-b>=xx"
if (has_mbyte)
new_slen += (*mb_char2bytes)(key_name[1], string + new_slen);
else
string[new_slen++] = key_name[1];
}
else if (new_slen == 0 && key_name[0] == KS_EXTRA
&& key_name[1] == KE_IGNORE)
{
// Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED
// to indicate what happened.
retval = KEYLEN_REMOVED;
}
else
{
string[new_slen++] = K_SPECIAL;
string[new_slen++] = key_name[0];
string[new_slen++] = key_name[1];
}
if (put_string_in_typebuf(offset, slen, string, new_slen,
buf, bufsize, buflen) == FAIL)
return -1;
return retval == 0 ? (len + new_slen - slen + offset) : retval;
}
#ifdef FEAT_TERMRESPONSE
LOG_TR(("normal character"));
#endif
return 0; // no match found
}
|
196889976171376146553776878857496634863
|
term.c
|
255079853890988870585830908048537470004
|
CWE-787
|
CVE-2022-2285
|
Integer Overflow or Wraparound in GitHub repository vim/vim prior to 9.0.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2285
|
409,515
|
vim
|
27efc62f5d86afcb2ecb7565587fe8dea4b036fe
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/27efc62f5d86afcb2ecb7565587fe8dea4b036fe
|
patch 9.0.0018: going over the end of the typahead
Problem: Going over the end of the typahead.
Solution: Put a NUL after the typeahead.
| 0
|
check_termcode(
int max_offset,
char_u *buf,
int bufsize,
int *buflen)
{
char_u *tp;
char_u *p;
int slen = 0; // init for GCC
int modslen;
int len;
int retval = 0;
int offset;
char_u key_name[2];
int modifiers;
char_u *modifiers_start = NULL;
int key;
int new_slen; // Length of what will replace the termcode
char_u string[MAX_KEY_CODE_LEN + 1];
int i, j;
int idx = 0;
int cpo_koffset;
cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL);
/*
* Speed up the checks for terminal codes by gathering all first bytes
* used in termleader[]. Often this is just a single <Esc>.
*/
if (need_gather)
gather_termleader();
/*
* Check at several positions in typebuf.tb_buf[], to catch something like
* "x<Up>" that can be mapped. Stop at max_offset, because characters
* after that cannot be used for mapping, and with @r commands
* typebuf.tb_buf[] can become very long.
* This is used often, KEEP IT FAST!
*/
for (offset = 0; offset < max_offset; ++offset)
{
if (buf == NULL)
{
if (offset >= typebuf.tb_len)
break;
tp = typebuf.tb_buf + typebuf.tb_off + offset;
len = typebuf.tb_len - offset; // length of the input
}
else
{
if (offset >= *buflen)
break;
tp = buf + offset;
len = *buflen - offset;
}
/*
* Don't check characters after K_SPECIAL, those are already
* translated terminal chars (avoid translating ~@^Hx).
*/
if (*tp == K_SPECIAL)
{
offset += 2; // there are always 2 extra characters
continue;
}
/*
* Skip this position if the character does not appear as the first
* character in term_strings. This speeds up a lot, since most
* termcodes start with the same character (ESC or CSI).
*/
i = *tp;
for (p = termleader; *p && *p != i; ++p)
;
if (*p == NUL)
continue;
/*
* Skip this position if p_ek is not set and tp[0] is an ESC and we
* are in Insert mode.
*/
if (*tp == ESC && !p_ek && (State & MODE_INSERT))
continue;
tp[len] = NUL;
key_name[0] = NUL; // no key name found yet
key_name[1] = NUL; // no key name found yet
modifiers = 0; // no modifiers yet
#ifdef FEAT_GUI
if (gui.in_use)
{
/*
* GUI special key codes are all of the form [CSI xx].
*/
if (*tp == CSI) // Special key from GUI
{
if (len < 3)
return -1; // Shouldn't happen
slen = 3;
key_name[0] = tp[1];
key_name[1] = tp[2];
}
}
else
#endif // FEAT_GUI
{
int mouse_index_found = -1;
for (idx = 0; idx < tc_len; ++idx)
{
/*
* Ignore the entry if we are not at the start of
* typebuf.tb_buf[]
* and there are not enough characters to make a match.
* But only when the 'K' flag is in 'cpoptions'.
*/
slen = termcodes[idx].len;
modifiers_start = NULL;
if (cpo_koffset && offset && len < slen)
continue;
if (STRNCMP(termcodes[idx].code, tp,
(size_t)(slen > len ? len : slen)) == 0)
{
int looks_like_mouse_start = FALSE;
if (len < slen) // got a partial sequence
return -1; // need to get more chars
/*
* When found a keypad key, check if there is another key
* that matches and use that one. This makes <Home> to be
* found instead of <kHome> when they produce the same
* key code.
*/
if (termcodes[idx].name[0] == 'K'
&& VIM_ISDIGIT(termcodes[idx].name[1]))
{
for (j = idx + 1; j < tc_len; ++j)
if (termcodes[j].len == slen &&
STRNCMP(termcodes[idx].code,
termcodes[j].code, slen) == 0)
{
idx = j;
break;
}
}
if (slen == 2 && len > 2
&& termcodes[idx].code[0] == ESC
&& termcodes[idx].code[1] == '[')
{
// The mouse termcode "ESC [" is also the prefix of
// "ESC [ I" (focus gained) and other keys. Check some
// more bytes to find out.
if (!isdigit(tp[2]))
{
// ESC [ without number following: Only use it when
// there is no other match.
looks_like_mouse_start = TRUE;
}
else if (termcodes[idx].name[0] == KS_DEC_MOUSE)
{
char_u *nr = tp + 2;
int count = 0;
// If a digit is following it could be a key with
// modifier, e.g., ESC [ 1;2P. Can be confused
// with DEC_MOUSE, which requires four numbers
// following. If not then it can't be a DEC_MOUSE
// code.
for (;;)
{
++count;
(void)getdigits(&nr);
if (nr >= tp + len)
return -1; // partial sequence
if (*nr != ';')
break;
++nr;
if (nr >= tp + len)
return -1; // partial sequence
}
if (count < 4)
continue; // no match
}
}
if (looks_like_mouse_start)
{
// Only use it when there is no other match.
if (mouse_index_found < 0)
mouse_index_found = idx;
}
else
{
key_name[0] = termcodes[idx].name[0];
key_name[1] = termcodes[idx].name[1];
break;
}
}
/*
* Check for code with modifier, like xterm uses:
* <Esc>[123;*X (modslen == slen - 3)
* <Esc>[@;*X (matches <Esc>[X and <Esc>[1;9X )
* Also <Esc>O*X and <M-O>*X (modslen == slen - 2).
* When there is a modifier the * matches a number.
* When there is no modifier the ;* or * is omitted.
*/
if (termcodes[idx].modlen > 0 && mouse_index_found < 0)
{
int at_code;
modslen = termcodes[idx].modlen;
if (cpo_koffset && offset && len < modslen)
continue;
at_code = termcodes[idx].code[modslen] == '@';
if (STRNCMP(termcodes[idx].code, tp,
(size_t)(modslen > len ? len : modslen)) == 0)
{
int n;
if (len <= modslen) // got a partial sequence
return -1; // need to get more chars
if (tp[modslen] == termcodes[idx].code[slen - 1])
// no modifiers
slen = modslen + 1;
else if (tp[modslen] != ';' && modslen == slen - 3)
// no match for "code;*X" with "code;"
continue;
else if (at_code && tp[modslen] != '1')
// no match for "<Esc>[@" with "<Esc>[1"
continue;
else
{
// Skip over the digits, the final char must
// follow. URXVT can use a negative value, thus
// also accept '-'.
for (j = slen - 2; j < len && (isdigit(tp[j])
|| tp[j] == '-' || tp[j] == ';'); ++j)
;
++j;
if (len < j) // got a partial sequence
return -1; // need to get more chars
if (tp[j - 1] != termcodes[idx].code[slen - 1])
continue; // no match
modifiers_start = tp + slen - 2;
// Match! Convert modifier bits.
n = atoi((char *)modifiers_start);
modifiers |= decode_modifiers(n);
slen = j;
}
key_name[0] = termcodes[idx].name[0];
key_name[1] = termcodes[idx].name[1];
break;
}
}
}
if (idx == tc_len && mouse_index_found >= 0)
{
key_name[0] = termcodes[mouse_index_found].name[0];
key_name[1] = termcodes[mouse_index_found].name[1];
}
}
#ifdef FEAT_TERMRESPONSE
if (key_name[0] == NUL
// Mouse codes of DEC and pterm start with <ESC>[. When
// detecting the start of these mouse codes they might as well be
// another key code or terminal response.
# ifdef FEAT_MOUSE_DEC
|| key_name[0] == KS_DEC_MOUSE
# endif
# ifdef FEAT_MOUSE_PTERM
|| key_name[0] == KS_PTERM_MOUSE
# endif
)
{
char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1;
/*
* Check for responses from the terminal starting with {lead}:
* "<Esc>[" or CSI followed by [0-9>?]
*
* - Xterm version string: {lead}>{x};{vers};{y}c
* Also eat other possible responses to t_RV, rxvt returns
* "{lead}?1;2c".
*
* - Cursor position report: {lead}{row};{col}R
* The final byte must be 'R'. It is used for checking the
* ambiguous-width character state.
*
* - window position reply: {lead}3;{x};{y}t
*
* - key with modifiers when modifyOtherKeys is enabled:
* {lead}27;{modifier};{key}~
* {lead}{key};{modifier}u
*/
if (((tp[0] == ESC && len >= 3 && tp[1] == '[')
|| (tp[0] == CSI && len >= 2))
&& (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?'))
{
int resp = handle_csi(tp, len, argp, offset, buf,
bufsize, buflen, key_name, &slen);
if (resp != 0)
{
# ifdef DEBUG_TERMRESPONSE
if (resp == -1)
LOG_TR(("Not enough characters for CSI sequence"));
# endif
return resp;
}
}
// Check for fore/background color response from the terminal,
// starting} with <Esc>] or OSC
else if ((*T_RBG != NUL || *T_RFG != NUL)
&& ((tp[0] == ESC && len >= 2 && tp[1] == ']')
|| tp[0] == OSC))
{
if (handle_osc(tp, argp, len, key_name, &slen) == FAIL)
return -1;
}
// Check for key code response from xterm,
// starting with <Esc>P or DCS
else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT)
&& ((tp[0] == ESC && len >= 2 && tp[1] == 'P')
|| tp[0] == DCS))
{
if (handle_dcs(tp, argp, len, key_name, &slen) == FAIL)
return -1;
}
}
#endif
if (key_name[0] == NUL)
continue; // No match at this position, try next one
// We only get here when we have a complete termcode match
#ifdef FEAT_GUI
/*
* Only in the GUI: Fetch the pointer coordinates of the scroll event
* so that we know which window to scroll later.
*/
if (gui.in_use
&& key_name[0] == (int)KS_EXTRA
&& (key_name[1] == (int)KE_X1MOUSE
|| key_name[1] == (int)KE_X2MOUSE
|| key_name[1] == (int)KE_MOUSEMOVE_XY
|| key_name[1] == (int)KE_MOUSELEFT
|| key_name[1] == (int)KE_MOUSERIGHT
|| key_name[1] == (int)KE_MOUSEDOWN
|| key_name[1] == (int)KE_MOUSEUP))
{
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 4);
if (num_bytes == -1) // not enough coordinates
return -1;
mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1;
mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1;
slen += num_bytes;
// equal to K_MOUSEMOVE
if (key_name[1] == (int)KE_MOUSEMOVE_XY)
key_name[1] = (int)KE_MOUSEMOVE;
}
else
#endif
/*
* If it is a mouse click, get the coordinates.
*/
if (key_name[0] == KS_MOUSE
#ifdef FEAT_MOUSE_GPM
|| key_name[0] == KS_GPM_MOUSE
#endif
#ifdef FEAT_MOUSE_JSB
|| key_name[0] == KS_JSBTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_NET
|| key_name[0] == KS_NETTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_DEC
|| key_name[0] == KS_DEC_MOUSE
#endif
#ifdef FEAT_MOUSE_PTERM
|| key_name[0] == KS_PTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_URXVT
|| key_name[0] == KS_URXVT_MOUSE
#endif
|| key_name[0] == KS_SGR_MOUSE
|| key_name[0] == KS_SGR_MOUSE_RELEASE)
{
if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx,
&modifiers) == -1)
return -1;
}
#ifdef FEAT_GUI
/*
* If using the GUI, then we get menu and scrollbar events.
*
* A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by
* four bytes which are to be taken as a pointer to the vimmenu_T
* structure.
*
* A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where "nr"
* is one byte with the tab index.
*
* A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed
* by one byte representing the scrollbar number, and then four bytes
* representing a long_u which is the new value of the scrollbar.
*
* A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,
* KE_FILLER followed by four bytes representing a long_u which is the
* new value of the scrollbar.
*/
# ifdef FEAT_MENU
else if (key_name[0] == (int)KS_MENU)
{
long_u val;
int num_bytes = get_long_from_buf(tp + slen, &val);
if (num_bytes == -1)
return -1;
current_menu = (vimmenu_T *)val;
slen += num_bytes;
// The menu may have been deleted right after it was used, check
// for that.
if (check_menu_pointer(root_menu, current_menu) == FAIL)
{
key_name[0] = KS_EXTRA;
key_name[1] = (int)KE_IGNORE;
}
}
# endif
# ifdef FEAT_GUI_TABLINE
else if (key_name[0] == (int)KS_TABLINE)
{
// Selecting tabline tab or using its menu.
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 1);
if (num_bytes == -1)
return -1;
current_tab = (int)bytes[0];
if (current_tab == 255) // -1 in a byte gives 255
current_tab = -1;
slen += num_bytes;
}
else if (key_name[0] == (int)KS_TABMENU)
{
// Selecting tabline tab or using its menu.
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 2);
if (num_bytes == -1)
return -1;
current_tab = (int)bytes[0];
current_tabmenu = (int)bytes[1];
slen += num_bytes;
}
# endif
# ifndef USE_ON_FLY_SCROLL
else if (key_name[0] == (int)KS_VER_SCROLLBAR)
{
long_u val;
char_u bytes[6];
int num_bytes;
// Get the last scrollbar event in the queue of the same type
j = 0;
for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR
&& tp[j + 2] != NUL; ++i)
{
j += 3;
num_bytes = get_bytes_from_buf(tp + j, bytes, 1);
if (num_bytes == -1)
break;
if (i == 0)
current_scrollbar = (int)bytes[0];
else if (current_scrollbar != (int)bytes[0])
break;
j += num_bytes;
num_bytes = get_long_from_buf(tp + j, &val);
if (num_bytes == -1)
break;
scrollbar_value = val;
j += num_bytes;
slen = j;
}
if (i == 0) // not enough characters to make one
return -1;
}
else if (key_name[0] == (int)KS_HOR_SCROLLBAR)
{
long_u val;
int num_bytes;
// Get the last horiz. scrollbar event in the queue
j = 0;
for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR
&& tp[j + 2] != NUL; ++i)
{
j += 3;
num_bytes = get_long_from_buf(tp + j, &val);
if (num_bytes == -1)
break;
scrollbar_value = val;
j += num_bytes;
slen = j;
}
if (i == 0) // not enough characters to make one
return -1;
}
# endif // !USE_ON_FLY_SCROLL
#endif // FEAT_GUI
#if (defined(UNIX) || defined(VMS))
/*
* Handle FocusIn/FocusOut event sequences reported by XTerm.
* (CSI I/CSI O)
*/
if (key_name[0] == KS_EXTRA
# ifdef FEAT_GUI
&& !gui.in_use
# endif
)
{
if (key_name[1] == KE_FOCUSGAINED)
{
if (!focus_state)
{
ui_focus_change(TRUE);
did_cursorhold = TRUE;
focus_state = TRUE;
}
key_name[1] = (int)KE_IGNORE;
}
else if (key_name[1] == KE_FOCUSLOST)
{
if (focus_state)
{
ui_focus_change(FALSE);
did_cursorhold = TRUE;
focus_state = FALSE;
}
key_name[1] = (int)KE_IGNORE;
}
}
#endif
/*
* Change <xHome> to <Home>, <xUp> to <Up>, etc.
*/
key = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1]));
/*
* Add any modifier codes to our string.
*/
new_slen = modifiers2keycode(modifiers, &key, string);
// Finally, add the special key code to our string
key_name[0] = KEY2TERMCAP0(key);
key_name[1] = KEY2TERMCAP1(key);
if (key_name[0] == KS_KEY)
{
// from ":set <M-b>=xx"
if (has_mbyte)
new_slen += (*mb_char2bytes)(key_name[1], string + new_slen);
else
string[new_slen++] = key_name[1];
}
else if (new_slen == 0 && key_name[0] == KS_EXTRA
&& key_name[1] == KE_IGNORE)
{
// Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED
// to indicate what happened.
retval = KEYLEN_REMOVED;
}
else
{
string[new_slen++] = K_SPECIAL;
string[new_slen++] = key_name[0];
string[new_slen++] = key_name[1];
}
if (put_string_in_typebuf(offset, slen, string, new_slen,
buf, bufsize, buflen) == FAIL)
return -1;
return retval == 0 ? (len + new_slen - slen + offset) : retval;
}
#ifdef FEAT_TERMRESPONSE
LOG_TR(("normal character"));
#endif
return 0; // no match found
}
|
105354748681163651663383549655228844664
|
term.c
|
113564079834188954277061754674630069521
|
CWE-787
|
CVE-2022-2285
|
Integer Overflow or Wraparound in GitHub repository vim/vim prior to 9.0.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2285
|
208,505
|
tor
|
57e35ad3d91724882c345ac709666a551a977f0f
|
https://github.com/torproject/tor
|
https://gitweb.torproject.org/tor.git/commitdiff/57e35ad3d91724882c345ac709666a551a977f0f
|
Avoid possible segfault when handling networkstatus vote with bad flavor
Fix for 6530; fix on 0.2.2.6-alpha.
| 1
|
networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
networkstatus_type_t ns_type)
{
smartlist_t *tokens = smartlist_create();
smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
networkstatus_voter_info_t *voter = NULL;
networkstatus_t *ns = NULL;
digests_t ns_digests;
const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
directory_token_t *tok;
int ok;
struct in_addr in;
int i, inorder, n_signatures = 0;
memarea_t *area = NULL, *rs_area = NULL;
consensus_flavor_t flav = FLAV_NS;
tor_assert(s);
if (eos_out)
*eos_out = NULL;
if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
log_warn(LD_DIR, "Unable to compute digest of network-status");
goto err;
}
area = memarea_new();
end_of_header = find_start_of_next_routerstatus(s);
if (tokenize_string(area, s, end_of_header, tokens,
(ns_type == NS_TYPE_CONSENSUS) ?
networkstatus_consensus_token_table :
networkstatus_token_table, 0)) {
log_warn(LD_DIR, "Error tokenizing network-status vote header");
goto err;
}
ns = tor_malloc_zero(sizeof(networkstatus_t));
memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
tor_assert(tok);
if (tok->n_args > 1) {
int flavor = networkstatus_parse_flavor_name(tok->args[1]);
if (flavor < 0) {
log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
escaped(tok->args[2]));
goto err;
}
ns->flavor = flav = flavor;
}
if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
goto err;
}
if (ns_type != NS_TYPE_CONSENSUS) {
const char *end_of_cert = NULL;
if (!(cert = strstr(s, "\ndir-key-certificate-version")))
goto err;
++cert;
ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
goto err;
}
tok = find_by_keyword(tokens, K_VOTE_STATUS);
tor_assert(tok->n_args);
if (!strcmp(tok->args[0], "vote")) {
ns->type = NS_TYPE_VOTE;
} else if (!strcmp(tok->args[0], "consensus")) {
ns->type = NS_TYPE_CONSENSUS;
} else if (!strcmp(tok->args[0], "opinion")) {
ns->type = NS_TYPE_OPINION;
} else {
log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
escaped(tok->args[0]));
goto err;
}
if (ns_type != ns->type) {
log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
goto err;
}
if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
tok = find_by_keyword(tokens, K_PUBLISHED);
if (parse_iso_time(tok->args[0], &ns->published))
goto err;
ns->supported_methods = smartlist_create();
tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
if (tok) {
for (i=0; i < tok->n_args; ++i)
smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
} else {
smartlist_add(ns->supported_methods, tor_strdup("1"));
}
} else {
tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
if (tok) {
ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
&ok, NULL);
if (!ok)
goto err;
} else {
ns->consensus_method = 1;
}
}
tok = find_by_keyword(tokens, K_VALID_AFTER);
if (parse_iso_time(tok->args[0], &ns->valid_after))
goto err;
tok = find_by_keyword(tokens, K_FRESH_UNTIL);
if (parse_iso_time(tok->args[0], &ns->fresh_until))
goto err;
tok = find_by_keyword(tokens, K_VALID_UNTIL);
if (parse_iso_time(tok->args[0], &ns->valid_until))
goto err;
tok = find_by_keyword(tokens, K_VOTING_DELAY);
tor_assert(tok->n_args >= 2);
ns->vote_seconds =
(int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
if (!ok)
goto err;
ns->dist_seconds =
(int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
if (!ok)
goto err;
if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
goto err;
}
if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
goto err;
}
if (ns->vote_seconds < MIN_VOTE_SECONDS) {
log_warn(LD_DIR, "Vote seconds is too short");
goto err;
}
if (ns->dist_seconds < MIN_DIST_SECONDS) {
log_warn(LD_DIR, "Dist seconds is too short");
goto err;
}
if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
ns->client_versions = tor_strdup(tok->args[0]);
}
if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
ns->server_versions = tor_strdup(tok->args[0]);
}
tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
ns->known_flags = smartlist_create();
inorder = 1;
for (i = 0; i < tok->n_args; ++i) {
smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
inorder = 0;
}
}
if (!inorder) {
log_warn(LD_DIR, "known-flags not in order");
goto err;
}
tok = find_opt_by_keyword(tokens, K_PARAMS);
if (tok) {
inorder = 1;
ns->net_params = smartlist_create();
for (i = 0; i < tok->n_args; ++i) {
int ok=0;
char *eq = strchr(tok->args[i], '=');
if (!eq) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
if (!ok) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
inorder = 0;
}
smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
}
if (!inorder) {
log_warn(LD_DIR, "params not in order");
goto err;
}
}
ns->voters = smartlist_create();
SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
tok = _tok;
if (tok->tp == K_DIR_SOURCE) {
tor_assert(tok->n_args >= 6);
if (voter)
smartlist_add(ns->voters, voter);
voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
voter->sigs = smartlist_create();
if (ns->type != NS_TYPE_CONSENSUS)
memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
voter->nickname = tor_strdup(tok->args[0]);
if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
tok->args[1], HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding identity digest %s in "
"network-status vote.", escaped(tok->args[1]));
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS &&
tor_memneq(ns->cert->cache_info.identity_digest,
voter->identity_digest, DIGEST_LEN)) {
log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
goto err;
}
voter->address = tor_strdup(tok->args[2]);
if (!tor_inet_aton(tok->args[3], &in)) {
log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
escaped(tok->args[3]));
goto err;
}
voter->addr = ntohl(in.s_addr);
voter->dir_port = (uint16_t)
tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
if (!ok)
goto err;
voter->or_port = (uint16_t)
tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
if (!ok)
goto err;
} else if (tok->tp == K_CONTACT) {
if (!voter || voter->contact) {
log_warn(LD_DIR, "contact element is out of place.");
goto err;
}
voter->contact = tor_strdup(tok->args[0]);
} else if (tok->tp == K_VOTE_DIGEST) {
tor_assert(ns->type == NS_TYPE_CONSENSUS);
tor_assert(tok->n_args >= 1);
if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
log_warn(LD_DIR, "vote-digest element is out of place.");
goto err;
}
if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
tok->args[0], HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding vote digest %s in "
"network-status consensus.", escaped(tok->args[0]));
goto err;
}
}
} SMARTLIST_FOREACH_END(_tok);
if (voter) {
smartlist_add(ns->voters, voter);
voter = NULL;
}
if (smartlist_len(ns->voters) == 0) {
log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
goto err;
} else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS &&
(tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
int bad = 1;
if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
tok->args[0], HEX_DIGEST_LEN)<0)
bad = 1;
else
bad = 0;
}
if (bad) {
log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
escaped(tok->args[0]));
}
}
/* Parse routerstatus lines. */
rs_tokens = smartlist_create();
rs_area = memarea_new();
s = end_of_header;
ns->routerstatus_list = smartlist_create();
while (!strcmpstart(s, "r ")) {
if (ns->type != NS_TYPE_CONSENSUS) {
vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
rs, 0, 0))
smartlist_add(ns->routerstatus_list, rs);
else {
tor_free(rs->version);
tor_free(rs);
}
} else {
routerstatus_t *rs;
if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
NULL, NULL,
ns->consensus_method,
flav)))
smartlist_add(ns->routerstatus_list, rs);
}
}
for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
routerstatus_t *rs1, *rs2;
if (ns->type != NS_TYPE_CONSENSUS) {
vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
rs1 = &a->status; rs2 = &b->status;
} else {
rs1 = smartlist_get(ns->routerstatus_list, i-1);
rs2 = smartlist_get(ns->routerstatus_list, i);
}
if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
>= 0) {
log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
"digest");
goto err;
}
}
/* Parse footer; check signature. */
footer_tokens = smartlist_create();
if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
++end_of_footer;
else
end_of_footer = s + strlen(s);
if (tokenize_string(area,s, end_of_footer, footer_tokens,
networkstatus_vote_footer_token_table, 0)) {
log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
goto err;
}
{
int found_sig = 0;
SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
tok = _tok;
if (tok->tp == K_DIRECTORY_SIGNATURE)
found_sig = 1;
else if (found_sig) {
log_warn(LD_DIR, "Extraneous token after first directory-signature");
goto err;
}
} SMARTLIST_FOREACH_END(_tok);
}
if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
if (tok != smartlist_get(footer_tokens, 0)) {
log_warn(LD_DIR, "Misplaced directory-footer token");
goto err;
}
}
tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
if (tok) {
ns->weight_params = smartlist_create();
for (i = 0; i < tok->n_args; ++i) {
int ok=0;
char *eq = strchr(tok->args[i], '=');
if (!eq) {
log_warn(LD_DIR, "Bad element '%s' in weight params",
escaped(tok->args[i]));
goto err;
}
tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
if (!ok) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
}
}
SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
char declared_identity[DIGEST_LEN];
networkstatus_voter_info_t *v;
document_signature_t *sig;
const char *id_hexdigest = NULL;
const char *sk_hexdigest = NULL;
digest_algorithm_t alg = DIGEST_SHA1;
tok = _tok;
if (tok->tp != K_DIRECTORY_SIGNATURE)
continue;
tor_assert(tok->n_args >= 2);
if (tok->n_args == 2) {
id_hexdigest = tok->args[0];
sk_hexdigest = tok->args[1];
} else {
const char *algname = tok->args[0];
int a;
id_hexdigest = tok->args[1];
sk_hexdigest = tok->args[2];
a = crypto_digest_algorithm_parse_name(algname);
if (a<0) {
log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
escaped(algname));
continue;
}
alg = a;
}
if (!tok->object_type ||
strcmp(tok->object_type, "SIGNATURE") ||
tok->object_size < 128 || tok->object_size > 512) {
log_warn(LD_DIR, "Bad object type or length on directory-signature");
goto err;
}
if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
base16_decode(declared_identity, sizeof(declared_identity),
id_hexdigest, HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding declared identity %s in "
"network-status vote.", escaped(id_hexdigest));
goto err;
}
if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
log_warn(LD_DIR, "ID on signature on network-status vote does not match "
"any declared directory source.");
goto err;
}
sig = tor_malloc_zero(sizeof(document_signature_t));
memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
sig->alg = alg;
if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
sk_hexdigest, HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
"network-status vote.", escaped(sk_hexdigest));
tor_free(sig);
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS) {
if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
DIGEST_LEN)) {
log_warn(LD_DIR, "Digest mismatch between declared and actual on "
"network-status vote.");
tor_free(sig);
goto err;
}
}
if (voter_get_sig_by_algorithm(v, sig->alg)) {
/* We already parsed a vote with this algorithm from this voter. Use the
first one. */
log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
"that contains two votes from the same voter with the same "
"algorithm. Ignoring the second vote.");
tor_free(sig);
continue;
}
if (ns->type != NS_TYPE_CONSENSUS) {
if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
tok, ns->cert->signing_key, 0,
"network-status vote")) {
tor_free(sig);
goto err;
}
sig->good_signature = 1;
} else {
if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
tor_free(sig);
goto err;
}
sig->signature = tor_memdup(tok->object_body, tok->object_size);
sig->signature_len = (int) tok->object_size;
}
smartlist_add(v->sigs, sig);
++n_signatures;
} SMARTLIST_FOREACH_END(_tok);
if (! n_signatures) {
log_warn(LD_DIR, "No signatures on networkstatus vote.");
goto err;
} else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
log_warn(LD_DIR, "Received more than one signature on a "
"network-status vote.");
goto err;
}
if (eos_out)
*eos_out = end_of_footer;
goto done;
err:
dump_desc(s_dup, "v3 networkstatus");
networkstatus_vote_free(ns);
ns = NULL;
done:
if (tokens) {
SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
smartlist_free(tokens);
}
if (voter) {
if (voter->sigs) {
SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
document_signature_free(sig));
smartlist_free(voter->sigs);
}
tor_free(voter->nickname);
tor_free(voter->address);
tor_free(voter->contact);
tor_free(voter);
}
if (rs_tokens) {
SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
smartlist_free(rs_tokens);
}
if (footer_tokens) {
SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
smartlist_free(footer_tokens);
}
if (area) {
DUMP_AREA(area, "v3 networkstatus");
memarea_drop_all(area);
}
if (rs_area)
memarea_drop_all(rs_area);
return ns;
}
|
297795787979009632344281497591388902899
|
routerparse.c
|
22420103474128049345359193080521452725
|
CWE-399
|
CVE-2012-3517
|
Use-after-free vulnerability in dns.c in Tor before 0.2.2.38 might allow remote attackers to cause a denial of service (daemon crash) via vectors related to failed DNS requests.
|
https://nvd.nist.gov/vuln/detail/CVE-2012-3517
|
411,896
|
tor
|
57e35ad3d91724882c345ac709666a551a977f0f
|
https://github.com/torproject/tor
|
https://gitweb.torproject.org/tor.git/commitdiff/57e35ad3d91724882c345ac709666a551a977f0f
|
Avoid possible segfault when handling networkstatus vote with bad flavor
Fix for 6530; fix on 0.2.2.6-alpha.
| 0
|
networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
networkstatus_type_t ns_type)
{
smartlist_t *tokens = smartlist_create();
smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
networkstatus_voter_info_t *voter = NULL;
networkstatus_t *ns = NULL;
digests_t ns_digests;
const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
directory_token_t *tok;
int ok;
struct in_addr in;
int i, inorder, n_signatures = 0;
memarea_t *area = NULL, *rs_area = NULL;
consensus_flavor_t flav = FLAV_NS;
tor_assert(s);
if (eos_out)
*eos_out = NULL;
if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
log_warn(LD_DIR, "Unable to compute digest of network-status");
goto err;
}
area = memarea_new();
end_of_header = find_start_of_next_routerstatus(s);
if (tokenize_string(area, s, end_of_header, tokens,
(ns_type == NS_TYPE_CONSENSUS) ?
networkstatus_consensus_token_table :
networkstatus_token_table, 0)) {
log_warn(LD_DIR, "Error tokenizing network-status vote header");
goto err;
}
ns = tor_malloc_zero(sizeof(networkstatus_t));
memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
tor_assert(tok);
if (tok->n_args > 1) {
int flavor = networkstatus_parse_flavor_name(tok->args[1]);
if (flavor < 0) {
log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
escaped(tok->args[1]));
goto err;
}
ns->flavor = flav = flavor;
}
if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
goto err;
}
if (ns_type != NS_TYPE_CONSENSUS) {
const char *end_of_cert = NULL;
if (!(cert = strstr(s, "\ndir-key-certificate-version")))
goto err;
++cert;
ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
goto err;
}
tok = find_by_keyword(tokens, K_VOTE_STATUS);
tor_assert(tok->n_args);
if (!strcmp(tok->args[0], "vote")) {
ns->type = NS_TYPE_VOTE;
} else if (!strcmp(tok->args[0], "consensus")) {
ns->type = NS_TYPE_CONSENSUS;
} else if (!strcmp(tok->args[0], "opinion")) {
ns->type = NS_TYPE_OPINION;
} else {
log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
escaped(tok->args[0]));
goto err;
}
if (ns_type != ns->type) {
log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
goto err;
}
if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
tok = find_by_keyword(tokens, K_PUBLISHED);
if (parse_iso_time(tok->args[0], &ns->published))
goto err;
ns->supported_methods = smartlist_create();
tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
if (tok) {
for (i=0; i < tok->n_args; ++i)
smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
} else {
smartlist_add(ns->supported_methods, tor_strdup("1"));
}
} else {
tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
if (tok) {
ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
&ok, NULL);
if (!ok)
goto err;
} else {
ns->consensus_method = 1;
}
}
tok = find_by_keyword(tokens, K_VALID_AFTER);
if (parse_iso_time(tok->args[0], &ns->valid_after))
goto err;
tok = find_by_keyword(tokens, K_FRESH_UNTIL);
if (parse_iso_time(tok->args[0], &ns->fresh_until))
goto err;
tok = find_by_keyword(tokens, K_VALID_UNTIL);
if (parse_iso_time(tok->args[0], &ns->valid_until))
goto err;
tok = find_by_keyword(tokens, K_VOTING_DELAY);
tor_assert(tok->n_args >= 2);
ns->vote_seconds =
(int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
if (!ok)
goto err;
ns->dist_seconds =
(int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
if (!ok)
goto err;
if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
goto err;
}
if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
goto err;
}
if (ns->vote_seconds < MIN_VOTE_SECONDS) {
log_warn(LD_DIR, "Vote seconds is too short");
goto err;
}
if (ns->dist_seconds < MIN_DIST_SECONDS) {
log_warn(LD_DIR, "Dist seconds is too short");
goto err;
}
if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
ns->client_versions = tor_strdup(tok->args[0]);
}
if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
ns->server_versions = tor_strdup(tok->args[0]);
}
tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
ns->known_flags = smartlist_create();
inorder = 1;
for (i = 0; i < tok->n_args; ++i) {
smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
inorder = 0;
}
}
if (!inorder) {
log_warn(LD_DIR, "known-flags not in order");
goto err;
}
tok = find_opt_by_keyword(tokens, K_PARAMS);
if (tok) {
inorder = 1;
ns->net_params = smartlist_create();
for (i = 0; i < tok->n_args; ++i) {
int ok=0;
char *eq = strchr(tok->args[i], '=');
if (!eq) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
if (!ok) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
inorder = 0;
}
smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
}
if (!inorder) {
log_warn(LD_DIR, "params not in order");
goto err;
}
}
ns->voters = smartlist_create();
SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
tok = _tok;
if (tok->tp == K_DIR_SOURCE) {
tor_assert(tok->n_args >= 6);
if (voter)
smartlist_add(ns->voters, voter);
voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
voter->sigs = smartlist_create();
if (ns->type != NS_TYPE_CONSENSUS)
memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
voter->nickname = tor_strdup(tok->args[0]);
if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
tok->args[1], HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding identity digest %s in "
"network-status vote.", escaped(tok->args[1]));
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS &&
tor_memneq(ns->cert->cache_info.identity_digest,
voter->identity_digest, DIGEST_LEN)) {
log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
goto err;
}
voter->address = tor_strdup(tok->args[2]);
if (!tor_inet_aton(tok->args[3], &in)) {
log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
escaped(tok->args[3]));
goto err;
}
voter->addr = ntohl(in.s_addr);
voter->dir_port = (uint16_t)
tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
if (!ok)
goto err;
voter->or_port = (uint16_t)
tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
if (!ok)
goto err;
} else if (tok->tp == K_CONTACT) {
if (!voter || voter->contact) {
log_warn(LD_DIR, "contact element is out of place.");
goto err;
}
voter->contact = tor_strdup(tok->args[0]);
} else if (tok->tp == K_VOTE_DIGEST) {
tor_assert(ns->type == NS_TYPE_CONSENSUS);
tor_assert(tok->n_args >= 1);
if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
log_warn(LD_DIR, "vote-digest element is out of place.");
goto err;
}
if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
tok->args[0], HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding vote digest %s in "
"network-status consensus.", escaped(tok->args[0]));
goto err;
}
}
} SMARTLIST_FOREACH_END(_tok);
if (voter) {
smartlist_add(ns->voters, voter);
voter = NULL;
}
if (smartlist_len(ns->voters) == 0) {
log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
goto err;
} else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS &&
(tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
int bad = 1;
if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
tok->args[0], HEX_DIGEST_LEN)<0)
bad = 1;
else
bad = 0;
}
if (bad) {
log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
escaped(tok->args[0]));
}
}
/* Parse routerstatus lines. */
rs_tokens = smartlist_create();
rs_area = memarea_new();
s = end_of_header;
ns->routerstatus_list = smartlist_create();
while (!strcmpstart(s, "r ")) {
if (ns->type != NS_TYPE_CONSENSUS) {
vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
rs, 0, 0))
smartlist_add(ns->routerstatus_list, rs);
else {
tor_free(rs->version);
tor_free(rs);
}
} else {
routerstatus_t *rs;
if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
NULL, NULL,
ns->consensus_method,
flav)))
smartlist_add(ns->routerstatus_list, rs);
}
}
for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
routerstatus_t *rs1, *rs2;
if (ns->type != NS_TYPE_CONSENSUS) {
vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
rs1 = &a->status; rs2 = &b->status;
} else {
rs1 = smartlist_get(ns->routerstatus_list, i-1);
rs2 = smartlist_get(ns->routerstatus_list, i);
}
if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
>= 0) {
log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
"digest");
goto err;
}
}
/* Parse footer; check signature. */
footer_tokens = smartlist_create();
if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
++end_of_footer;
else
end_of_footer = s + strlen(s);
if (tokenize_string(area,s, end_of_footer, footer_tokens,
networkstatus_vote_footer_token_table, 0)) {
log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
goto err;
}
{
int found_sig = 0;
SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
tok = _tok;
if (tok->tp == K_DIRECTORY_SIGNATURE)
found_sig = 1;
else if (found_sig) {
log_warn(LD_DIR, "Extraneous token after first directory-signature");
goto err;
}
} SMARTLIST_FOREACH_END(_tok);
}
if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
if (tok != smartlist_get(footer_tokens, 0)) {
log_warn(LD_DIR, "Misplaced directory-footer token");
goto err;
}
}
tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
if (tok) {
ns->weight_params = smartlist_create();
for (i = 0; i < tok->n_args; ++i) {
int ok=0;
char *eq = strchr(tok->args[i], '=');
if (!eq) {
log_warn(LD_DIR, "Bad element '%s' in weight params",
escaped(tok->args[i]));
goto err;
}
tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
if (!ok) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
}
}
SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
char declared_identity[DIGEST_LEN];
networkstatus_voter_info_t *v;
document_signature_t *sig;
const char *id_hexdigest = NULL;
const char *sk_hexdigest = NULL;
digest_algorithm_t alg = DIGEST_SHA1;
tok = _tok;
if (tok->tp != K_DIRECTORY_SIGNATURE)
continue;
tor_assert(tok->n_args >= 2);
if (tok->n_args == 2) {
id_hexdigest = tok->args[0];
sk_hexdigest = tok->args[1];
} else {
const char *algname = tok->args[0];
int a;
id_hexdigest = tok->args[1];
sk_hexdigest = tok->args[2];
a = crypto_digest_algorithm_parse_name(algname);
if (a<0) {
log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
escaped(algname));
continue;
}
alg = a;
}
if (!tok->object_type ||
strcmp(tok->object_type, "SIGNATURE") ||
tok->object_size < 128 || tok->object_size > 512) {
log_warn(LD_DIR, "Bad object type or length on directory-signature");
goto err;
}
if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
base16_decode(declared_identity, sizeof(declared_identity),
id_hexdigest, HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding declared identity %s in "
"network-status vote.", escaped(id_hexdigest));
goto err;
}
if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
log_warn(LD_DIR, "ID on signature on network-status vote does not match "
"any declared directory source.");
goto err;
}
sig = tor_malloc_zero(sizeof(document_signature_t));
memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
sig->alg = alg;
if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
sk_hexdigest, HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
"network-status vote.", escaped(sk_hexdigest));
tor_free(sig);
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS) {
if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
DIGEST_LEN)) {
log_warn(LD_DIR, "Digest mismatch between declared and actual on "
"network-status vote.");
tor_free(sig);
goto err;
}
}
if (voter_get_sig_by_algorithm(v, sig->alg)) {
/* We already parsed a vote with this algorithm from this voter. Use the
first one. */
log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
"that contains two votes from the same voter with the same "
"algorithm. Ignoring the second vote.");
tor_free(sig);
continue;
}
if (ns->type != NS_TYPE_CONSENSUS) {
if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
tok, ns->cert->signing_key, 0,
"network-status vote")) {
tor_free(sig);
goto err;
}
sig->good_signature = 1;
} else {
if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
tor_free(sig);
goto err;
}
sig->signature = tor_memdup(tok->object_body, tok->object_size);
sig->signature_len = (int) tok->object_size;
}
smartlist_add(v->sigs, sig);
++n_signatures;
} SMARTLIST_FOREACH_END(_tok);
if (! n_signatures) {
log_warn(LD_DIR, "No signatures on networkstatus vote.");
goto err;
} else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
log_warn(LD_DIR, "Received more than one signature on a "
"network-status vote.");
goto err;
}
if (eos_out)
*eos_out = end_of_footer;
goto done;
err:
dump_desc(s_dup, "v3 networkstatus");
networkstatus_vote_free(ns);
ns = NULL;
done:
if (tokens) {
SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
smartlist_free(tokens);
}
if (voter) {
if (voter->sigs) {
SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
document_signature_free(sig));
smartlist_free(voter->sigs);
}
tor_free(voter->nickname);
tor_free(voter->address);
tor_free(voter->contact);
tor_free(voter);
}
if (rs_tokens) {
SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
smartlist_free(rs_tokens);
}
if (footer_tokens) {
SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
smartlist_free(footer_tokens);
}
if (area) {
DUMP_AREA(area, "v3 networkstatus");
memarea_drop_all(area);
}
if (rs_area)
memarea_drop_all(rs_area);
return ns;
}
|
32476189085047846654485357461000169303
|
routerparse.c
|
74078993205863755729749320619386018823
|
CWE-399
|
CVE-2012-3517
|
Use-after-free vulnerability in dns.c in Tor before 0.2.2.38 might allow remote attackers to cause a denial of service (daemon crash) via vectors related to failed DNS requests.
|
https://nvd.nist.gov/vuln/detail/CVE-2012-3517
|
208,506
|
heimdal
|
04171147948d0a3636bc6374181926f0fb2ec83a
|
https://github.com/heimdal/heimdal
|
https://github.com/heimdal/heimdal/commit/04171147948d0a3636bc6374181926f0fb2ec83a
|
kdc: validate sname in TGS-REQ
In tgs_build_reply(), validate the server name in the TGS-REQ is present before
dereferencing.
| 1
|
tgs_build_reply(astgs_request_t priv,
hdb_entry_ex *krbtgt,
krb5_enctype krbtgt_etype,
const krb5_keyblock *replykey,
int rk_is_subkey,
krb5_ticket *ticket,
const char **e_text,
AuthorizationData **auth_data,
const struct sockaddr *from_addr)
{
krb5_context context = priv->context;
krb5_kdc_configuration *config = priv->config;
KDC_REQ *req = &priv->req;
KDC_REQ_BODY *b = &priv->req.req_body;
const char *from = priv->from;
krb5_error_code ret, ret2;
krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;
krb5_principal krbtgt_out_principal = NULL;
char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;
hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;
HDB *clientdb, *s4u2self_impersonated_clientdb;
krb5_realm ref_realm = NULL;
EncTicketPart *tgt = &ticket->ticket;
krb5_principals spp = NULL;
const EncryptionKey *ekey;
krb5_keyblock sessionkey;
krb5_kvno kvno;
krb5_data rspac;
const char *tgt_realm = /* Realm of TGT issuer */
krb5_principal_get_realm(context, krbtgt->entry.principal);
const char *our_realm = /* Realm of this KDC */
krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);
char **capath = NULL;
size_t num_capath = 0;
hdb_entry_ex *krbtgt_out = NULL;
METHOD_DATA enc_pa_data;
PrincipalName *s;
Realm r;
EncTicketPart adtkt;
char opt_str[128];
int signedpath = 0;
Key *tkey_check;
Key *tkey_sign;
int flags = HDB_F_FOR_TGS_REQ;
memset(&sessionkey, 0, sizeof(sessionkey));
memset(&adtkt, 0, sizeof(adtkt));
krb5_data_zero(&rspac);
memset(&enc_pa_data, 0, sizeof(enc_pa_data));
s = b->sname;
r = b->realm;
/*
* The canonicalize KDC option is passed as a hint to the backend, but
* can typically be ignored. Per RFC 6806, names are not canonicalized
* in response to a TGS request (although we make an exception, see
* force-canonicalize below).
*/
if (b->kdc_options.canonicalize)
flags |= HDB_F_CANON;
if(b->kdc_options.enc_tkt_in_skey){
Ticket *t;
hdb_entry_ex *uu;
krb5_principal p;
Key *uukey;
krb5uint32 second_kvno = 0;
krb5uint32 *kvno_ptr = NULL;
if(b->additional_tickets == NULL ||
b->additional_tickets->len == 0){
ret = KRB5KDC_ERR_BADOPTION; /* ? */
kdc_log(context, config, 4,
"No second ticket present in user-to-user request");
_kdc_audit_addreason((kdc_request_t)priv,
"No second ticket present in user-to-user request");
goto out;
}
t = &b->additional_tickets->val[0];
if(!get_krbtgt_realm(&t->sname)){
kdc_log(context, config, 4,
"Additional ticket is not a ticket-granting ticket");
_kdc_audit_addreason((kdc_request_t)priv,
"Additional ticket is not a ticket-granting ticket");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);
ret = krb5_unparse_name(context, p, &tpn);
if (ret)
goto out;
if(t->enc_part.kvno){
second_kvno = *t->enc_part.kvno;
kvno_ptr = &second_kvno;
}
ret = _kdc_db_fetch(context, config, p,
HDB_F_GET_KRBTGT, kvno_ptr,
NULL, &uu);
krb5_free_principal(context, p);
if(ret){
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user service principal (TGS) unknown");
goto out;
}
ret = hdb_enctype2key(context, &uu->entry, NULL,
t->enc_part.etype, &uukey);
if(ret){
_kdc_free_ent(context, uu);
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user enctype not supported");
goto out;
}
ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);
_kdc_free_ent(context, uu);
if(ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user TGT decrypt failure");
goto out;
}
ret = verify_flags(context, config, &adtkt, tpn);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user TGT expired or invalid");
goto out;
}
s = &adtkt.cname;
r = adtkt.crealm;
}
_krb5_principalname2krb5_principal(context, &sp, *s, r);
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
_krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);
ret = krb5_unparse_name(context, cp, &priv->cname);
if (ret)
goto out;
cpn = priv->cname;
unparse_flags (KDCOptions2int(b->kdc_options),
asn1_KDCOptions_units(),
opt_str, sizeof(opt_str));
if(*opt_str)
kdc_log(context, config, 4,
"TGS-REQ %s from %s for %s [%s]",
cpn, from, spn, opt_str);
else
kdc_log(context, config, 4,
"TGS-REQ %s from %s for %s", cpn, from, spn);
/*
* Fetch server
*/
server_lookup:
ret = _kdc_db_fetch(context, config, sp,
HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags,
NULL, NULL, &server);
priv->server = server;
if (ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", spn);
_kdc_audit_addreason((kdc_request_t)priv, "Target not found here");
goto out;
} else if (ret == HDB_ERR_WRONG_REALM) {
free(ref_realm);
ref_realm = strdup(server->entry.principal->realm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
kdc_log(context, config, 4,
"Returning a referral to realm %s for "
"server %s.",
ref_realm, spn);
krb5_free_principal(context, sp);
sp = NULL;
ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
ref_realm, NULL);
if (ret)
goto out;
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
goto server_lookup;
} else if (ret) {
const char *new_rlm, *msg;
Realm req_rlm;
krb5_realm *realms;
if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {
if (capath == NULL) {
/* With referalls, hierarchical capaths are always enabled */
ret2 = _krb5_find_capath(context, tgt->crealm, our_realm,
req_rlm, TRUE, &capath, &num_capath);
if (ret2) {
ret = ret2;
_kdc_audit_addreason((kdc_request_t)priv,
"No trusted path from client realm to ours");
goto out;
}
}
new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;
if (new_rlm) {
kdc_log(context, config, 5, "krbtgt from %s via %s for "
"realm %s not found, trying %s", tgt->crealm,
our_realm, req_rlm, new_rlm);
free(ref_realm);
ref_realm = strdup(new_rlm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r,
KRB5_TGS_NAME, ref_realm, NULL);
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
goto server_lookup;
}
} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {
if (strcmp(realms[0], sp->realm) != 0) {
kdc_log(context, config, 4,
"Returning a referral to realm %s for "
"server %s that was not found",
realms[0], spn);
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
realms[0], NULL);
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret) {
krb5_free_host_realm(context, realms);
goto out;
}
spn = priv->sname;
free(ref_realm);
ref_realm = strdup(realms[0]);
krb5_free_host_realm(context, realms);
goto server_lookup;
}
krb5_free_host_realm(context, realms);
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 3,
"Server not found in database: %s: %s", spn, msg);
krb5_free_error_message(context, msg);
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
_kdc_audit_addreason((kdc_request_t)priv,
"Service principal unknown");
goto out;
}
/*
* RFC 6806 notes that names MUST NOT be changed in the response to
* a TGS request. Hence we ignore the setting of the canonicalize
* KDC option. However, for legacy interoperability we do allow the
* backend to override this by setting the force-canonicalize HDB
* flag in the server entry.
*/
if (server->entry.flags.force_canonicalize)
rsp = server->entry.principal;
else
rsp = sp;
/*
* Select enctype, return key and kvno.
*/
{
krb5_enctype etype;
if(b->kdc_options.enc_tkt_in_skey) {
size_t i;
ekey = &adtkt.key;
for(i = 0; i < b->etype.len; i++)
if (b->etype.val[i] == adtkt.key.keytype)
break;
if(i == b->etype.len) {
kdc_log(context, config, 4,
"Addition ticket have not matching etypes");
krb5_clear_error_message(context);
ret = KRB5KDC_ERR_ETYPE_NOSUPP;
_kdc_audit_addreason((kdc_request_t)priv,
"No matching enctypes for 2nd ticket");
goto out;
}
etype = b->etype.val[i];
kvno = 0;
} else {
Key *skey;
ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp)
? KFE_IS_TGS : 0,
b->etype.val, b->etype.len, &etype, NULL,
NULL);
if(ret) {
kdc_log(context, config, 4,
"Server (%s) has no support for etypes", spn);
_kdc_audit_addreason((kdc_request_t)priv,
"Enctype not supported");
goto out;
}
ret = _kdc_get_preferred_key(context, config, server, spn,
NULL, &skey);
if(ret) {
kdc_log(context, config, 4,
"Server (%s) has no supported etypes", spn);
_kdc_audit_addreason((kdc_request_t)priv,
"Enctype not supported");
goto out;
}
ekey = &skey->key;
kvno = server->entry.kvno;
}
ret = krb5_generate_random_keyblock(context, etype, &sessionkey);
if (ret)
goto out;
}
/*
* Check that service is in the same realm as the krbtgt. If it's
* not the same, it's someone that is using a uni-directional trust
* backward.
*/
/*
* Validate authorization data
*/
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */
krbtgt_etype, &tkey_check);
if(ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC check");
_kdc_audit_addreason((kdc_request_t)priv,
"No key for krbtgt PAC check");
goto out;
}
/*
* Now refetch the primary krbtgt, and get the current kvno (the
* sign check may have been on an old kvno, and the server may
* have been an incoming trust)
*/
ret = krb5_make_principal(context,
&krbtgt_out_principal,
our_realm,
KRB5_TGS_NAME,
our_realm,
NULL);
if (ret) {
kdc_log(context, config, 4,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);
if (ret) {
kdc_log(context, config, 4,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = _kdc_db_fetch(context, config, krbtgt_out_principal,
HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);
if (ret) {
char *ktpn = NULL;
ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);
kdc_log(context, config, 4,
"No such principal %s (needed for authz-data signature keys) "
"while processing TGS-REQ for service %s with krbtg %s",
krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>");
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
/*
* The first realm is the realm of the service, the second is
* krbtgt/<this>/@REALM component of the krbtgt DN the request was
* encrypted to. The redirection via the krbtgt_out entry allows
* the DB to possibly correct the case of the realm (Samba4 does
* this) before the strcmp()
*/
if (strcmp(krb5_principal_get_realm(context, server->entry.principal),
krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {
char *ktpn;
ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);
kdc_log(context, config, 4,
"Request with wrong krbtgt: %s",
(ret == 0) ? ktpn : "<unknown>");
if(ret == 0)
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
_kdc_audit_addreason((kdc_request_t)priv, "Request with wrong TGT");
goto out;
}
ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,
NULL, &tkey_sign);
if (ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC signature");
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to find key for krbtgt PAC signature");
goto out;
}
ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,
tkey_sign->key.keytype, &tkey_sign);
if(ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC signature");
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to find key for krbtgt PAC signature");
goto out;
}
{
krb5_data verified_cas;
/*
* If the client doesn't exist in the HDB but has a TGT and it's
* obtained with PKINIT then we assume it's a synthetic client -- that
* is, a client whose name was vouched for by a CA using a PKINIT SAN,
* but which doesn't exist in the HDB proper. We'll allow such a
* client to do TGT requests even though normally we'd reject all
* clients that don't exist in the HDB.
*/
ret = krb5_ticket_get_authorization_data_type(context, ticket,
KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,
&verified_cas);
if (ret == 0) {
krb5_data_free(&verified_cas);
flags |= HDB_F_SYNTHETIC_OK;
}
}
ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,
NULL, &clientdb, &client);
flags &= ~HDB_F_SYNTHETIC_OK;
priv->client = client;
if(ret == HDB_ERR_NOT_FOUND_HERE) {
/* This is OK, we are just trying to find out if they have
* been disabled or deleted in the meantime, missing secrets
* is OK */
} else if(ret){
const char *krbtgt_realm, *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);
if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
kdc_log(context, config, 4, "Client no longer in database: %s",
cpn);
_kdc_audit_addreason((kdc_request_t)priv, "Client no longer in HDB");
goto out;
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 4, "Client not found in database: %s", msg);
_kdc_audit_addreason((kdc_request_t)priv, "Client does not exist");
krb5_free_error_message(context, msg);
} else if (ret == 0 &&
(client->entry.flags.invalid || !client->entry.flags.client)) {
_kdc_audit_addreason((kdc_request_t)priv, "Client has invalid bit set");
kdc_log(context, config, 4, "Client has invalid bit set");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
ret = check_PAC(context, config, cp, NULL,
client, server, krbtgt,
&tkey_check->key,
ekey, &tkey_sign->key,
tgt, &rspac, &signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv, "PAC check failed");
kdc_log(context, config, 4,
"Verify PAC failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/* also check the krbtgt for signature */
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
tgt,
&spp,
&signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed");
kdc_log(context, config, 4,
"KRB5SignedPath check failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Process request
*/
/* by default the tgt principal matches the client principal */
tp = cp;
tpn = cpn;
if (client) {
const PA_DATA *sdata;
int i = 0;
sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);
if (sdata) {
struct astgs_request_desc imp_req;
krb5_crypto crypto;
krb5_data datack;
PA_S4U2Self self;
const char *str;
ret = decode_PA_S4U2Self(sdata->padata_value.data,
sdata->padata_value.length,
&self, NULL);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to decode PA-S4U2Self");
kdc_log(context, config, 4, "Failed to decode PA-S4U2Self");
goto out;
}
if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) {
free_PA_S4U2Self(&self);
_kdc_audit_addreason((kdc_request_t)priv,
"PA-S4U2Self with unkeyed checksum");
kdc_log(context, config, 4, "Reject PA-S4U2Self with unkeyed checksum");
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);
if (ret)
goto out;
ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
krb5_data_free(&datack);
kdc_log(context, config, 4, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
/* Allow HMAC_MD5 checksum with any key type */
if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) {
struct krb5_crypto_iov iov;
unsigned char csdata[16];
Checksum cs;
cs.checksum.length = sizeof(csdata);
cs.checksum.data = &csdata;
iov.data.data = datack.data;
iov.data.length = datack.length;
iov.flags = KRB5_CRYPTO_TYPE_DATA;
ret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key,
KRB5_KU_OTHER_CKSUM, &iov, 1,
&cs);
if (ret == 0 &&
krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0)
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
}
else {
ret = krb5_verify_checksum(context,
crypto,
KRB5_KU_OTHER_CKSUM,
datack.data,
datack.length,
&self.cksum);
}
krb5_data_free(&datack);
krb5_crypto_destroy(context, crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
_kdc_audit_addreason((kdc_request_t)priv,
"S4U2Self checksum failed");
kdc_log(context, config, 4,
"krb5_verify_checksum failed for S4U2Self: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
self.name,
self.realm);
free_PA_S4U2Self(&self);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
/*
* Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients
* is probably not desirable!
*/
ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,
NULL, &s4u2self_impersonated_clientdb,
&s4u2self_impersonated_client);
if (ret) {
const char *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv,
"S4U2Self principal to impersonate not found");
kdc_log(context, config, 2,
"S4U2Self principal to impersonate %s not found in database: %s",
tpn, msg);
krb5_free_error_message(context, msg);
goto out;
}
/* Ignore require_pwchange and pw_end attributes (as Windows does),
* since S4U2Self is not password authentication. */
s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE;
free(s4u2self_impersonated_client->entry.pw_end);
s4u2self_impersonated_client->entry.pw_end = NULL;
imp_req = *priv;
imp_req.client = s4u2self_impersonated_client;
imp_req.client_princ = tp;
ret = kdc_check_flags(&imp_req, FALSE);
if (ret)
goto out; /* kdc_check_flags() calls _kdc_audit_addreason() */
/* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */
if(rspac.data) {
krb5_pac p = NULL;
krb5_data_free(&rspac);
ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"KRB5SignedPath missing");
kdc_log(context, config, 4, "PAC generation failed for -- %s",
tpn);
goto out;
}
if (p != NULL) {
ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,
s4u2self_impersonated_client->entry.principal,
ekey, &tkey_sign->key,
&rspac);
krb5_pac_free(context, p);
if (ret) {
kdc_log(context, config, 4, "PAC signing failed for -- %s",
tpn);
goto out;
}
}
}
/*
* Check that service doing the impersonating is
* requesting a ticket to it-self.
*/
ret = check_s4u2self(context, config, clientdb, client, sp);
if (ret) {
kdc_log(context, config, 4, "S4U2Self: %s is not allowed "
"to impersonate to service "
"(tried for user %s to service %s)",
cpn, tpn, spn);
goto out;
}
/*
* If the service isn't trusted for authentication to
* delegation or if the impersonate client is disallowed
* forwardable, remove the forwardable flag.
*/
if (client->entry.flags.trusted_for_delegation &&
s4u2self_impersonated_client->entry.flags.forwardable) {
str = "[forwardable]";
} else {
b->kdc_options.forwardable = 0;
str = "";
}
kdc_log(context, config, 4, "s4u2self %s impersonating %s to "
"service %s %s", cpn, tpn, spn, str);
}
}
/*
* Constrained delegation
*/
if (client != NULL
&& b->additional_tickets != NULL
&& b->additional_tickets->len != 0
&& b->kdc_options.cname_in_addl_tkt
&& b->kdc_options.enc_tkt_in_skey == 0)
{
int ad_signedpath = 0;
Key *clientkey;
Ticket *t;
/*
* Require that the KDC have issued the service's krbtgt (not
* self-issued ticket with kimpersonate(1).
*/
if (!signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
_kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing");
kdc_log(context, config, 4,
"Constrained delegation done on service ticket %s/%s",
cpn, spn);
goto out;
}
t = &b->additional_tickets->val[0];
ret = hdb_enctype2key(context, &client->entry,
hdb_kvno2keys(context, &client->entry,
t->enc_part.kvno ? * t->enc_part.kvno : 0),
t->enc_part.etype, &clientkey);
if(ret){
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
goto out;
}
ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to decrypt constrained delegation ticket");
kdc_log(context, config, 4,
"failed to decrypt ticket for "
"constrained delegation from %s to %s ", cpn, spn);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
adtkt.cname,
adtkt.crealm);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
_kdc_audit_addkv((kdc_request_t)priv, 0, "impersonatee", "%s", tpn);
ret = _krb5_principalname2krb5_principal(context,
&dp,
t->sname,
t->realm);
if (ret)
goto out;
ret = krb5_unparse_name(context, dp, &dpn);
if (ret)
goto out;
/* check that ticket is valid */
if (adtkt.flags.forwardable == 0) {
_kdc_audit_addreason((kdc_request_t)priv,
"Missing forwardable flag on ticket for constrained delegation");
kdc_log(context, config, 4,
"Missing forwardable flag on ticket for "
"constrained delegation from %s (%s) as %s to %s ",
cpn, dpn, tpn, spn);
ret = KRB5KDC_ERR_BADOPTION;
goto out;
}
ret = check_constrained_delegation(context, config, clientdb,
client, server, sp);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation not allowed");
kdc_log(context, config, 4,
"constrained delegation from %s (%s) as %s to %s not allowed",
cpn, dpn, tpn, spn);
goto out;
}
ret = verify_flags(context, config, &adtkt, tpn);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket expired or invalid");
goto out;
}
krb5_data_free(&rspac);
/*
* generate the PAC for the user.
*
* TODO: pass in t->sname and t->realm and build
* a S4U_DELEGATION_INFO blob to the PAC.
*/
ret = check_PAC(context, config, tp, dp,
client, server, krbtgt,
&clientkey->key,
ekey, &tkey_sign->key,
&adtkt, &rspac, &ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket PAC check failed");
kdc_log(context, config, 4,
"Verify delegated PAC failed to %s for client"
"%s (%s) as %s from %s with %s",
spn, cpn, dpn, tpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Check that the KDC issued the user's ticket.
*/
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
&adtkt,
NULL,
&ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 4,
"KRB5SignedPath check from service %s failed "
"for delegation to %s for client %s (%s)"
"from %s failed with %s",
spn, tpn, dpn, cpn, from, msg);
krb5_free_error_message(context, msg);
_kdc_audit_addreason((kdc_request_t)priv,
"KRB5SignedPath check failed");
goto out;
}
if (!ad_signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 4,
"Ticket not signed with PAC nor SignedPath service %s failed "
"for delegation to %s for client %s (%s)"
"from %s",
spn, tpn, dpn, cpn, from);
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket not signed");
goto out;
}
kdc_log(context, config, 4, "constrained delegation for %s "
"from %s (%s) to %s", tpn, cpn, dpn, spn);
}
/*
* Check flags
*/
ret = kdc_check_flags(priv, FALSE);
if(ret)
goto out;
if((b->kdc_options.validate || b->kdc_options.renew) &&
!krb5_principal_compare(context,
krbtgt->entry.principal,
server->entry.principal)){
_kdc_audit_addreason((kdc_request_t)priv, "Inconsistent request");
kdc_log(context, config, 4, "Inconsistent request.");
ret = KRB5KDC_ERR_SERVER_NOMATCH;
goto out;
}
/* check for valid set of addresses */
if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) {
if (config->check_ticket_addresses) {
ret = KRB5KRB_AP_ERR_BADADDR;
_kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes");
kdc_log(context, config, 4, "Request from wrong address");
_kdc_audit_addreason((kdc_request_t)priv, "Request from wrong address");
goto out;
} else if (config->warn_ticket_addresses) {
_kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes");
}
}
/* check local and per-principal anonymous ticket issuance policy */
if (is_anon_tgs_request_p(b, tgt)) {
ret = _kdc_check_anon_policy(priv);
if (ret)
goto out;
}
/*
* If this is an referral, add server referral data to the
* auth_data reply .
*/
if (ref_realm) {
PA_DATA pa;
krb5_crypto crypto;
kdc_log(context, config, 3,
"Adding server referral to %s", ref_realm);
ret = krb5_crypto_init(context, &sessionkey, 0, &crypto);
if (ret)
goto out;
ret = build_server_referral(context, config, crypto, ref_realm,
NULL, s, &pa.padata_value);
krb5_crypto_destroy(context, crypto);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv, "Referral build failed");
kdc_log(context, config, 4,
"Failed building server referral");
goto out;
}
pa.padata_type = KRB5_PADATA_SERVER_REFERRAL;
ret = add_METHOD_DATA(&enc_pa_data, &pa);
krb5_data_free(&pa.padata_value);
if (ret) {
kdc_log(context, config, 4,
"Add server referral METHOD-DATA failed");
goto out;
}
}
/*
*
*/
ret = tgs_make_reply(priv,
tp,
tgt,
replykey,
rk_is_subkey,
ekey,
&sessionkey,
kvno,
*auth_data,
server,
rsp,
client,
cp,
tgt_realm,
krbtgt_out,
tkey_sign->key.keytype,
spp,
&rspac,
&enc_pa_data);
out:
if (tpn != cpn)
free(tpn);
free(dpn);
free(krbtgt_out_n);
_krb5_free_capath(context, capath);
krb5_data_free(&rspac);
krb5_free_keyblock_contents(context, &sessionkey);
if(krbtgt_out)
_kdc_free_ent(context, krbtgt_out);
if(server)
_kdc_free_ent(context, server);
if(client)
_kdc_free_ent(context, client);
if(s4u2self_impersonated_client)
_kdc_free_ent(context, s4u2self_impersonated_client);
if (tp && tp != cp)
krb5_free_principal(context, tp);
krb5_free_principal(context, cp);
krb5_free_principal(context, dp);
krb5_free_principal(context, sp);
krb5_free_principal(context, krbtgt_out_principal);
free(ref_realm);
free_METHOD_DATA(&enc_pa_data);
free_EncTicketPart(&adtkt);
return ret;
}
|
180711409541748394655723306760719102268
|
None
|
CWE-476
|
CVE-2021-3671
|
A null pointer de-reference was found in the way samba kerberos server handled missing sname in TGS-REQ (Ticket Granting Server - Request). An authenticated user could use this flaw to crash the samba server.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-3671
|
|
411,926
|
heimdal
|
04171147948d0a3636bc6374181926f0fb2ec83a
|
https://github.com/heimdal/heimdal
|
https://github.com/heimdal/heimdal/commit/04171147948d0a3636bc6374181926f0fb2ec83a
|
kdc: validate sname in TGS-REQ
In tgs_build_reply(), validate the server name in the TGS-REQ is present before
dereferencing.
| 0
|
tgs_build_reply(astgs_request_t priv,
hdb_entry_ex *krbtgt,
krb5_enctype krbtgt_etype,
const krb5_keyblock *replykey,
int rk_is_subkey,
krb5_ticket *ticket,
const char **e_text,
AuthorizationData **auth_data,
const struct sockaddr *from_addr)
{
krb5_context context = priv->context;
krb5_kdc_configuration *config = priv->config;
KDC_REQ *req = &priv->req;
KDC_REQ_BODY *b = &priv->req.req_body;
const char *from = priv->from;
krb5_error_code ret, ret2;
krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;
krb5_principal krbtgt_out_principal = NULL;
char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;
hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;
HDB *clientdb, *s4u2self_impersonated_clientdb;
krb5_realm ref_realm = NULL;
EncTicketPart *tgt = &ticket->ticket;
krb5_principals spp = NULL;
const EncryptionKey *ekey;
krb5_keyblock sessionkey;
krb5_kvno kvno;
krb5_data rspac;
const char *tgt_realm = /* Realm of TGT issuer */
krb5_principal_get_realm(context, krbtgt->entry.principal);
const char *our_realm = /* Realm of this KDC */
krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);
char **capath = NULL;
size_t num_capath = 0;
hdb_entry_ex *krbtgt_out = NULL;
METHOD_DATA enc_pa_data;
PrincipalName *s;
Realm r;
EncTicketPart adtkt;
char opt_str[128];
int signedpath = 0;
Key *tkey_check;
Key *tkey_sign;
int flags = HDB_F_FOR_TGS_REQ;
memset(&sessionkey, 0, sizeof(sessionkey));
memset(&adtkt, 0, sizeof(adtkt));
krb5_data_zero(&rspac);
memset(&enc_pa_data, 0, sizeof(enc_pa_data));
s = b->sname;
r = b->realm;
/*
* The canonicalize KDC option is passed as a hint to the backend, but
* can typically be ignored. Per RFC 6806, names are not canonicalized
* in response to a TGS request (although we make an exception, see
* force-canonicalize below).
*/
if (b->kdc_options.canonicalize)
flags |= HDB_F_CANON;
if(b->kdc_options.enc_tkt_in_skey){
Ticket *t;
hdb_entry_ex *uu;
krb5_principal p;
Key *uukey;
krb5uint32 second_kvno = 0;
krb5uint32 *kvno_ptr = NULL;
if(b->additional_tickets == NULL ||
b->additional_tickets->len == 0){
ret = KRB5KDC_ERR_BADOPTION; /* ? */
kdc_log(context, config, 4,
"No second ticket present in user-to-user request");
_kdc_audit_addreason((kdc_request_t)priv,
"No second ticket present in user-to-user request");
goto out;
}
t = &b->additional_tickets->val[0];
if(!get_krbtgt_realm(&t->sname)){
kdc_log(context, config, 4,
"Additional ticket is not a ticket-granting ticket");
_kdc_audit_addreason((kdc_request_t)priv,
"Additional ticket is not a ticket-granting ticket");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);
ret = krb5_unparse_name(context, p, &tpn);
if (ret)
goto out;
if(t->enc_part.kvno){
second_kvno = *t->enc_part.kvno;
kvno_ptr = &second_kvno;
}
ret = _kdc_db_fetch(context, config, p,
HDB_F_GET_KRBTGT, kvno_ptr,
NULL, &uu);
krb5_free_principal(context, p);
if(ret){
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user service principal (TGS) unknown");
goto out;
}
ret = hdb_enctype2key(context, &uu->entry, NULL,
t->enc_part.etype, &uukey);
if(ret){
_kdc_free_ent(context, uu);
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user enctype not supported");
goto out;
}
ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);
_kdc_free_ent(context, uu);
if(ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user TGT decrypt failure");
goto out;
}
ret = verify_flags(context, config, &adtkt, tpn);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user TGT expired or invalid");
goto out;
}
s = &adtkt.cname;
r = adtkt.crealm;
} else if (s == NULL) {
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
_kdc_set_e_text(r, "No server in request");
goto out;
}
_krb5_principalname2krb5_principal(context, &sp, *s, r);
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
_krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);
ret = krb5_unparse_name(context, cp, &priv->cname);
if (ret)
goto out;
cpn = priv->cname;
unparse_flags (KDCOptions2int(b->kdc_options),
asn1_KDCOptions_units(),
opt_str, sizeof(opt_str));
if(*opt_str)
kdc_log(context, config, 4,
"TGS-REQ %s from %s for %s [%s]",
cpn, from, spn, opt_str);
else
kdc_log(context, config, 4,
"TGS-REQ %s from %s for %s", cpn, from, spn);
/*
* Fetch server
*/
server_lookup:
ret = _kdc_db_fetch(context, config, sp,
HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags,
NULL, NULL, &server);
priv->server = server;
if (ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", spn);
_kdc_audit_addreason((kdc_request_t)priv, "Target not found here");
goto out;
} else if (ret == HDB_ERR_WRONG_REALM) {
free(ref_realm);
ref_realm = strdup(server->entry.principal->realm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
kdc_log(context, config, 4,
"Returning a referral to realm %s for "
"server %s.",
ref_realm, spn);
krb5_free_principal(context, sp);
sp = NULL;
ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
ref_realm, NULL);
if (ret)
goto out;
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
goto server_lookup;
} else if (ret) {
const char *new_rlm, *msg;
Realm req_rlm;
krb5_realm *realms;
if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {
if (capath == NULL) {
/* With referalls, hierarchical capaths are always enabled */
ret2 = _krb5_find_capath(context, tgt->crealm, our_realm,
req_rlm, TRUE, &capath, &num_capath);
if (ret2) {
ret = ret2;
_kdc_audit_addreason((kdc_request_t)priv,
"No trusted path from client realm to ours");
goto out;
}
}
new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;
if (new_rlm) {
kdc_log(context, config, 5, "krbtgt from %s via %s for "
"realm %s not found, trying %s", tgt->crealm,
our_realm, req_rlm, new_rlm);
free(ref_realm);
ref_realm = strdup(new_rlm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r,
KRB5_TGS_NAME, ref_realm, NULL);
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
goto server_lookup;
}
} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {
if (strcmp(realms[0], sp->realm) != 0) {
kdc_log(context, config, 4,
"Returning a referral to realm %s for "
"server %s that was not found",
realms[0], spn);
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
realms[0], NULL);
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret) {
krb5_free_host_realm(context, realms);
goto out;
}
spn = priv->sname;
free(ref_realm);
ref_realm = strdup(realms[0]);
krb5_free_host_realm(context, realms);
goto server_lookup;
}
krb5_free_host_realm(context, realms);
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 3,
"Server not found in database: %s: %s", spn, msg);
krb5_free_error_message(context, msg);
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
_kdc_audit_addreason((kdc_request_t)priv,
"Service principal unknown");
goto out;
}
/*
* RFC 6806 notes that names MUST NOT be changed in the response to
* a TGS request. Hence we ignore the setting of the canonicalize
* KDC option. However, for legacy interoperability we do allow the
* backend to override this by setting the force-canonicalize HDB
* flag in the server entry.
*/
if (server->entry.flags.force_canonicalize)
rsp = server->entry.principal;
else
rsp = sp;
/*
* Select enctype, return key and kvno.
*/
{
krb5_enctype etype;
if(b->kdc_options.enc_tkt_in_skey) {
size_t i;
ekey = &adtkt.key;
for(i = 0; i < b->etype.len; i++)
if (b->etype.val[i] == adtkt.key.keytype)
break;
if(i == b->etype.len) {
kdc_log(context, config, 4,
"Addition ticket have not matching etypes");
krb5_clear_error_message(context);
ret = KRB5KDC_ERR_ETYPE_NOSUPP;
_kdc_audit_addreason((kdc_request_t)priv,
"No matching enctypes for 2nd ticket");
goto out;
}
etype = b->etype.val[i];
kvno = 0;
} else {
Key *skey;
ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp)
? KFE_IS_TGS : 0,
b->etype.val, b->etype.len, &etype, NULL,
NULL);
if(ret) {
kdc_log(context, config, 4,
"Server (%s) has no support for etypes", spn);
_kdc_audit_addreason((kdc_request_t)priv,
"Enctype not supported");
goto out;
}
ret = _kdc_get_preferred_key(context, config, server, spn,
NULL, &skey);
if(ret) {
kdc_log(context, config, 4,
"Server (%s) has no supported etypes", spn);
_kdc_audit_addreason((kdc_request_t)priv,
"Enctype not supported");
goto out;
}
ekey = &skey->key;
kvno = server->entry.kvno;
}
ret = krb5_generate_random_keyblock(context, etype, &sessionkey);
if (ret)
goto out;
}
/*
* Check that service is in the same realm as the krbtgt. If it's
* not the same, it's someone that is using a uni-directional trust
* backward.
*/
/*
* Validate authorization data
*/
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */
krbtgt_etype, &tkey_check);
if(ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC check");
_kdc_audit_addreason((kdc_request_t)priv,
"No key for krbtgt PAC check");
goto out;
}
/*
* Now refetch the primary krbtgt, and get the current kvno (the
* sign check may have been on an old kvno, and the server may
* have been an incoming trust)
*/
ret = krb5_make_principal(context,
&krbtgt_out_principal,
our_realm,
KRB5_TGS_NAME,
our_realm,
NULL);
if (ret) {
kdc_log(context, config, 4,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);
if (ret) {
kdc_log(context, config, 4,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = _kdc_db_fetch(context, config, krbtgt_out_principal,
HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);
if (ret) {
char *ktpn = NULL;
ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);
kdc_log(context, config, 4,
"No such principal %s (needed for authz-data signature keys) "
"while processing TGS-REQ for service %s with krbtg %s",
krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>");
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
/*
* The first realm is the realm of the service, the second is
* krbtgt/<this>/@REALM component of the krbtgt DN the request was
* encrypted to. The redirection via the krbtgt_out entry allows
* the DB to possibly correct the case of the realm (Samba4 does
* this) before the strcmp()
*/
if (strcmp(krb5_principal_get_realm(context, server->entry.principal),
krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {
char *ktpn;
ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);
kdc_log(context, config, 4,
"Request with wrong krbtgt: %s",
(ret == 0) ? ktpn : "<unknown>");
if(ret == 0)
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
_kdc_audit_addreason((kdc_request_t)priv, "Request with wrong TGT");
goto out;
}
ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,
NULL, &tkey_sign);
if (ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC signature");
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to find key for krbtgt PAC signature");
goto out;
}
ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,
tkey_sign->key.keytype, &tkey_sign);
if(ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC signature");
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to find key for krbtgt PAC signature");
goto out;
}
{
krb5_data verified_cas;
/*
* If the client doesn't exist in the HDB but has a TGT and it's
* obtained with PKINIT then we assume it's a synthetic client -- that
* is, a client whose name was vouched for by a CA using a PKINIT SAN,
* but which doesn't exist in the HDB proper. We'll allow such a
* client to do TGT requests even though normally we'd reject all
* clients that don't exist in the HDB.
*/
ret = krb5_ticket_get_authorization_data_type(context, ticket,
KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,
&verified_cas);
if (ret == 0) {
krb5_data_free(&verified_cas);
flags |= HDB_F_SYNTHETIC_OK;
}
}
ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,
NULL, &clientdb, &client);
flags &= ~HDB_F_SYNTHETIC_OK;
priv->client = client;
if(ret == HDB_ERR_NOT_FOUND_HERE) {
/* This is OK, we are just trying to find out if they have
* been disabled or deleted in the meantime, missing secrets
* is OK */
} else if(ret){
const char *krbtgt_realm, *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);
if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
kdc_log(context, config, 4, "Client no longer in database: %s",
cpn);
_kdc_audit_addreason((kdc_request_t)priv, "Client no longer in HDB");
goto out;
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 4, "Client not found in database: %s", msg);
_kdc_audit_addreason((kdc_request_t)priv, "Client does not exist");
krb5_free_error_message(context, msg);
} else if (ret == 0 &&
(client->entry.flags.invalid || !client->entry.flags.client)) {
_kdc_audit_addreason((kdc_request_t)priv, "Client has invalid bit set");
kdc_log(context, config, 4, "Client has invalid bit set");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
ret = check_PAC(context, config, cp, NULL,
client, server, krbtgt,
&tkey_check->key,
ekey, &tkey_sign->key,
tgt, &rspac, &signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv, "PAC check failed");
kdc_log(context, config, 4,
"Verify PAC failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/* also check the krbtgt for signature */
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
tgt,
&spp,
&signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed");
kdc_log(context, config, 4,
"KRB5SignedPath check failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Process request
*/
/* by default the tgt principal matches the client principal */
tp = cp;
tpn = cpn;
if (client) {
const PA_DATA *sdata;
int i = 0;
sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);
if (sdata) {
struct astgs_request_desc imp_req;
krb5_crypto crypto;
krb5_data datack;
PA_S4U2Self self;
const char *str;
ret = decode_PA_S4U2Self(sdata->padata_value.data,
sdata->padata_value.length,
&self, NULL);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to decode PA-S4U2Self");
kdc_log(context, config, 4, "Failed to decode PA-S4U2Self");
goto out;
}
if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) {
free_PA_S4U2Self(&self);
_kdc_audit_addreason((kdc_request_t)priv,
"PA-S4U2Self with unkeyed checksum");
kdc_log(context, config, 4, "Reject PA-S4U2Self with unkeyed checksum");
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);
if (ret)
goto out;
ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
krb5_data_free(&datack);
kdc_log(context, config, 4, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
/* Allow HMAC_MD5 checksum with any key type */
if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) {
struct krb5_crypto_iov iov;
unsigned char csdata[16];
Checksum cs;
cs.checksum.length = sizeof(csdata);
cs.checksum.data = &csdata;
iov.data.data = datack.data;
iov.data.length = datack.length;
iov.flags = KRB5_CRYPTO_TYPE_DATA;
ret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key,
KRB5_KU_OTHER_CKSUM, &iov, 1,
&cs);
if (ret == 0 &&
krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0)
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
}
else {
ret = krb5_verify_checksum(context,
crypto,
KRB5_KU_OTHER_CKSUM,
datack.data,
datack.length,
&self.cksum);
}
krb5_data_free(&datack);
krb5_crypto_destroy(context, crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
_kdc_audit_addreason((kdc_request_t)priv,
"S4U2Self checksum failed");
kdc_log(context, config, 4,
"krb5_verify_checksum failed for S4U2Self: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
self.name,
self.realm);
free_PA_S4U2Self(&self);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
/*
* Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients
* is probably not desirable!
*/
ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,
NULL, &s4u2self_impersonated_clientdb,
&s4u2self_impersonated_client);
if (ret) {
const char *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv,
"S4U2Self principal to impersonate not found");
kdc_log(context, config, 2,
"S4U2Self principal to impersonate %s not found in database: %s",
tpn, msg);
krb5_free_error_message(context, msg);
goto out;
}
/* Ignore require_pwchange and pw_end attributes (as Windows does),
* since S4U2Self is not password authentication. */
s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE;
free(s4u2self_impersonated_client->entry.pw_end);
s4u2self_impersonated_client->entry.pw_end = NULL;
imp_req = *priv;
imp_req.client = s4u2self_impersonated_client;
imp_req.client_princ = tp;
ret = kdc_check_flags(&imp_req, FALSE);
if (ret)
goto out; /* kdc_check_flags() calls _kdc_audit_addreason() */
/* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */
if(rspac.data) {
krb5_pac p = NULL;
krb5_data_free(&rspac);
ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"KRB5SignedPath missing");
kdc_log(context, config, 4, "PAC generation failed for -- %s",
tpn);
goto out;
}
if (p != NULL) {
ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,
s4u2self_impersonated_client->entry.principal,
ekey, &tkey_sign->key,
&rspac);
krb5_pac_free(context, p);
if (ret) {
kdc_log(context, config, 4, "PAC signing failed for -- %s",
tpn);
goto out;
}
}
}
/*
* Check that service doing the impersonating is
* requesting a ticket to it-self.
*/
ret = check_s4u2self(context, config, clientdb, client, sp);
if (ret) {
kdc_log(context, config, 4, "S4U2Self: %s is not allowed "
"to impersonate to service "
"(tried for user %s to service %s)",
cpn, tpn, spn);
goto out;
}
/*
* If the service isn't trusted for authentication to
* delegation or if the impersonate client is disallowed
* forwardable, remove the forwardable flag.
*/
if (client->entry.flags.trusted_for_delegation &&
s4u2self_impersonated_client->entry.flags.forwardable) {
str = "[forwardable]";
} else {
b->kdc_options.forwardable = 0;
str = "";
}
kdc_log(context, config, 4, "s4u2self %s impersonating %s to "
"service %s %s", cpn, tpn, spn, str);
}
}
/*
* Constrained delegation
*/
if (client != NULL
&& b->additional_tickets != NULL
&& b->additional_tickets->len != 0
&& b->kdc_options.cname_in_addl_tkt
&& b->kdc_options.enc_tkt_in_skey == 0)
{
int ad_signedpath = 0;
Key *clientkey;
Ticket *t;
/*
* Require that the KDC have issued the service's krbtgt (not
* self-issued ticket with kimpersonate(1).
*/
if (!signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
_kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing");
kdc_log(context, config, 4,
"Constrained delegation done on service ticket %s/%s",
cpn, spn);
goto out;
}
t = &b->additional_tickets->val[0];
ret = hdb_enctype2key(context, &client->entry,
hdb_kvno2keys(context, &client->entry,
t->enc_part.kvno ? * t->enc_part.kvno : 0),
t->enc_part.etype, &clientkey);
if(ret){
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
goto out;
}
ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to decrypt constrained delegation ticket");
kdc_log(context, config, 4,
"failed to decrypt ticket for "
"constrained delegation from %s to %s ", cpn, spn);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
adtkt.cname,
adtkt.crealm);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
_kdc_audit_addkv((kdc_request_t)priv, 0, "impersonatee", "%s", tpn);
ret = _krb5_principalname2krb5_principal(context,
&dp,
t->sname,
t->realm);
if (ret)
goto out;
ret = krb5_unparse_name(context, dp, &dpn);
if (ret)
goto out;
/* check that ticket is valid */
if (adtkt.flags.forwardable == 0) {
_kdc_audit_addreason((kdc_request_t)priv,
"Missing forwardable flag on ticket for constrained delegation");
kdc_log(context, config, 4,
"Missing forwardable flag on ticket for "
"constrained delegation from %s (%s) as %s to %s ",
cpn, dpn, tpn, spn);
ret = KRB5KDC_ERR_BADOPTION;
goto out;
}
ret = check_constrained_delegation(context, config, clientdb,
client, server, sp);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation not allowed");
kdc_log(context, config, 4,
"constrained delegation from %s (%s) as %s to %s not allowed",
cpn, dpn, tpn, spn);
goto out;
}
ret = verify_flags(context, config, &adtkt, tpn);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket expired or invalid");
goto out;
}
krb5_data_free(&rspac);
/*
* generate the PAC for the user.
*
* TODO: pass in t->sname and t->realm and build
* a S4U_DELEGATION_INFO blob to the PAC.
*/
ret = check_PAC(context, config, tp, dp,
client, server, krbtgt,
&clientkey->key,
ekey, &tkey_sign->key,
&adtkt, &rspac, &ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket PAC check failed");
kdc_log(context, config, 4,
"Verify delegated PAC failed to %s for client"
"%s (%s) as %s from %s with %s",
spn, cpn, dpn, tpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Check that the KDC issued the user's ticket.
*/
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
&adtkt,
NULL,
&ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 4,
"KRB5SignedPath check from service %s failed "
"for delegation to %s for client %s (%s)"
"from %s failed with %s",
spn, tpn, dpn, cpn, from, msg);
krb5_free_error_message(context, msg);
_kdc_audit_addreason((kdc_request_t)priv,
"KRB5SignedPath check failed");
goto out;
}
if (!ad_signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 4,
"Ticket not signed with PAC nor SignedPath service %s failed "
"for delegation to %s for client %s (%s)"
"from %s",
spn, tpn, dpn, cpn, from);
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket not signed");
goto out;
}
kdc_log(context, config, 4, "constrained delegation for %s "
"from %s (%s) to %s", tpn, cpn, dpn, spn);
}
/*
* Check flags
*/
ret = kdc_check_flags(priv, FALSE);
if(ret)
goto out;
if((b->kdc_options.validate || b->kdc_options.renew) &&
!krb5_principal_compare(context,
krbtgt->entry.principal,
server->entry.principal)){
_kdc_audit_addreason((kdc_request_t)priv, "Inconsistent request");
kdc_log(context, config, 4, "Inconsistent request.");
ret = KRB5KDC_ERR_SERVER_NOMATCH;
goto out;
}
/* check for valid set of addresses */
if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) {
if (config->check_ticket_addresses) {
ret = KRB5KRB_AP_ERR_BADADDR;
_kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes");
kdc_log(context, config, 4, "Request from wrong address");
_kdc_audit_addreason((kdc_request_t)priv, "Request from wrong address");
goto out;
} else if (config->warn_ticket_addresses) {
_kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes");
}
}
/* check local and per-principal anonymous ticket issuance policy */
if (is_anon_tgs_request_p(b, tgt)) {
ret = _kdc_check_anon_policy(priv);
if (ret)
goto out;
}
/*
* If this is an referral, add server referral data to the
* auth_data reply .
*/
if (ref_realm) {
PA_DATA pa;
krb5_crypto crypto;
kdc_log(context, config, 3,
"Adding server referral to %s", ref_realm);
ret = krb5_crypto_init(context, &sessionkey, 0, &crypto);
if (ret)
goto out;
ret = build_server_referral(context, config, crypto, ref_realm,
NULL, s, &pa.padata_value);
krb5_crypto_destroy(context, crypto);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv, "Referral build failed");
kdc_log(context, config, 4,
"Failed building server referral");
goto out;
}
pa.padata_type = KRB5_PADATA_SERVER_REFERRAL;
ret = add_METHOD_DATA(&enc_pa_data, &pa);
krb5_data_free(&pa.padata_value);
if (ret) {
kdc_log(context, config, 4,
"Add server referral METHOD-DATA failed");
goto out;
}
}
/*
*
*/
ret = tgs_make_reply(priv,
tp,
tgt,
replykey,
rk_is_subkey,
ekey,
&sessionkey,
kvno,
*auth_data,
server,
rsp,
client,
cp,
tgt_realm,
krbtgt_out,
tkey_sign->key.keytype,
spp,
&rspac,
&enc_pa_data);
out:
if (tpn != cpn)
free(tpn);
free(dpn);
free(krbtgt_out_n);
_krb5_free_capath(context, capath);
krb5_data_free(&rspac);
krb5_free_keyblock_contents(context, &sessionkey);
if(krbtgt_out)
_kdc_free_ent(context, krbtgt_out);
if(server)
_kdc_free_ent(context, server);
if(client)
_kdc_free_ent(context, client);
if(s4u2self_impersonated_client)
_kdc_free_ent(context, s4u2self_impersonated_client);
if (tp && tp != cp)
krb5_free_principal(context, tp);
krb5_free_principal(context, cp);
krb5_free_principal(context, dp);
krb5_free_principal(context, sp);
krb5_free_principal(context, krbtgt_out_principal);
free(ref_realm);
free_METHOD_DATA(&enc_pa_data);
free_EncTicketPart(&adtkt);
return ret;
}
|
196356477365064545945564048418819765006
|
None
|
CWE-476
|
CVE-2021-3671
|
A null pointer de-reference was found in the way samba kerberos server handled missing sname in TGS-REQ (Ticket Granting Server - Request). An authenticated user could use this flaw to crash the samba server.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-3671
|
|
208,522
|
unbound
|
02080f6b180232f43b77f403d0c038e9360a460f
|
https://github.com/NLnetLabs/unbound
|
https://github.com/NLnetLabs/unbound/commit/02080f6b180232f43b77f403d0c038e9360a460f
|
- Fix Integer Overflows in Size Calculations,
reported by X41 D-Sec.
| 1
|
dnsc_load_local_data(struct dnsc_env* dnscenv, struct config_file *cfg)
{
size_t i, j;
// Insert 'local-zone: "2.dnscrypt-cert.example.com" deny'
if(!cfg_str2list_insert(&cfg->local_zones,
strdup(dnscenv->provider_name),
strdup("deny"))) {
log_err("Could not load dnscrypt local-zone: %s deny",
dnscenv->provider_name);
return -1;
}
// Add local data entry of type:
// 2.dnscrypt-cert.example.com 86400 IN TXT "DNSC......"
for(i=0; i<dnscenv->signed_certs_count; i++) {
const char *ttl_class_type = " 86400 IN TXT \"";
int rotated_cert = 0;
uint32_t serial;
uint16_t rrlen;
char* rr;
struct SignedCert *cert = dnscenv->signed_certs + i;
// Check if the certificate is being rotated and should not be published
for(j=0; j<dnscenv->rotated_certs_count; j++){
if(cert == dnscenv->rotated_certs[j]) {
rotated_cert = 1;
break;
}
}
memcpy(&serial, cert->serial, sizeof serial);
serial = htonl(serial);
if(rotated_cert) {
verbose(VERB_OPS,
"DNSCrypt: not adding cert with serial #%"
PRIu32
" to local-data as it is rotated",
serial
);
continue;
}
rrlen = strlen(dnscenv->provider_name) +
strlen(ttl_class_type) +
4 * sizeof(struct SignedCert) + // worst case scenario
1 + // trailing double quote
1;
rr = malloc(rrlen);
if(!rr) {
log_err("Could not allocate memory");
return -2;
}
snprintf(rr, rrlen - 1, "%s 86400 IN TXT \"", dnscenv->provider_name);
for(j=0; j<sizeof(struct SignedCert); j++) {
int c = (int)*((const uint8_t *) cert + j);
if (isprint(c) && c != '"' && c != '\\') {
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "%c", c);
} else {
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "\\%03d", c);
}
}
verbose(VERB_OPS,
"DNSCrypt: adding cert with serial #%"
PRIu32
" to local-data to config: %s",
serial, rr
);
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "\"");
cfg_strlist_insert(&cfg->local_data, strdup(rr));
free(rr);
}
return dnscenv->signed_certs_count;
}
|
44451332163685602086826854088983200257
|
dnscrypt.c
|
338731906376917706393921999097571082291
|
CWE-190
|
CVE-2019-25038
|
Unbound before 1.9.5 allows an integer overflow in a size calculation in dnscrypt/dnscrypt.c. NOTE: The vendor disputes that this is a vulnerability. Although the code may be vulnerable, a running Unbound installation cannot be remotely or locally exploited
|
https://nvd.nist.gov/vuln/detail/CVE-2019-25038
|
412,117
|
unbound
|
02080f6b180232f43b77f403d0c038e9360a460f
|
https://github.com/NLnetLabs/unbound
|
https://github.com/NLnetLabs/unbound/commit/02080f6b180232f43b77f403d0c038e9360a460f
|
- Fix Integer Overflows in Size Calculations,
reported by X41 D-Sec.
| 0
|
dnsc_load_local_data(struct dnsc_env* dnscenv, struct config_file *cfg)
{
size_t i, j;
// Insert 'local-zone: "2.dnscrypt-cert.example.com" deny'
if(!cfg_str2list_insert(&cfg->local_zones,
strdup(dnscenv->provider_name),
strdup("deny"))) {
log_err("Could not load dnscrypt local-zone: %s deny",
dnscenv->provider_name);
return -1;
}
// Add local data entry of type:
// 2.dnscrypt-cert.example.com 86400 IN TXT "DNSC......"
for(i=0; i<dnscenv->signed_certs_count; i++) {
const char *ttl_class_type = " 86400 IN TXT \"";
int rotated_cert = 0;
uint32_t serial;
uint16_t rrlen;
char* rr;
struct SignedCert *cert = dnscenv->signed_certs + i;
// Check if the certificate is being rotated and should not be published
for(j=0; j<dnscenv->rotated_certs_count; j++){
if(cert == dnscenv->rotated_certs[j]) {
rotated_cert = 1;
break;
}
}
memcpy(&serial, cert->serial, sizeof serial);
serial = htonl(serial);
if(rotated_cert) {
verbose(VERB_OPS,
"DNSCrypt: not adding cert with serial #%"
PRIu32
" to local-data as it is rotated",
serial
);
continue;
}
if((unsigned)strlen(dnscenv->provider_name) >= (unsigned)0xffff0000) {
/* guard against integer overflow in rrlen calculation */
verbose(VERB_OPS, "cert #%" PRIu32 " is too long", serial);
continue
}
rrlen = strlen(dnscenv->provider_name) +
strlen(ttl_class_type) +
4 * sizeof(struct SignedCert) + // worst case scenario
1 + // trailing double quote
1;
rr = malloc(rrlen);
if(!rr) {
log_err("Could not allocate memory");
return -2;
}
snprintf(rr, rrlen - 1, "%s 86400 IN TXT \"", dnscenv->provider_name);
for(j=0; j<sizeof(struct SignedCert); j++) {
int c = (int)*((const uint8_t *) cert + j);
if (isprint(c) && c != '"' && c != '\\') {
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "%c", c);
} else {
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "\\%03d", c);
}
}
verbose(VERB_OPS,
"DNSCrypt: adding cert with serial #%"
PRIu32
" to local-data to config: %s",
serial, rr
);
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "\"");
cfg_strlist_insert(&cfg->local_data, strdup(rr));
free(rr);
}
return dnscenv->signed_certs_count;
}
|
220864762997315196932796822660985000469
|
dnscrypt.c
|
151631660973156645492009635074477412124
|
CWE-190
|
CVE-2019-25038
|
Unbound before 1.9.5 allows an integer overflow in a size calculation in dnscrypt/dnscrypt.c. NOTE: The vendor disputes that this is a vulnerability. Although the code may be vulnerable, a running Unbound installation cannot be remotely or locally exploited
|
https://nvd.nist.gov/vuln/detail/CVE-2019-25038
|
208,525
|
vim
|
6046aded8da002b08d380db29de2ba0268b6616e
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/6046aded8da002b08d380db29de2ba0268b6616e
|
patch 8.2.5148: invalid memory access when using expression on command line
Problem: Invalid memory access when using an expression on the command line.
Solution: Make sure the position does not go negative.
| 1
|
cmdline_insert_reg(int *gotesc UNUSED)
{
int i;
int c;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; // disallow scrolling here
#endif
putcmdline('"', TRUE);
++no_mapping;
++allow_keys;
i = c = plain_vgetc(); // CTRL-R <char>
if (i == Ctrl_O)
i = Ctrl_R; // CTRL-R CTRL-O == CTRL-R CTRL-R
if (i == Ctrl_R)
c = plain_vgetc(); // CTRL-R CTRL-R <char>
extra_char = NUL;
--no_mapping;
--allow_keys;
#ifdef FEAT_EVAL
/*
* Insert the result of an expression.
* Need to save the current command line, to be able to enter
* a new one...
*/
new_cmdpos = -1;
if (c == '=')
{
if (ccline.cmdfirstc == '=' // can't do this recursively
|| cmdline_star > 0) // or when typing a password
{
beep_flush();
c = ESC;
}
else
c = get_expr_register();
}
#endif
if (c != ESC) // use ESC to cancel inserting register
{
cmdline_paste(c, i == Ctrl_R, FALSE);
#ifdef FEAT_EVAL
// When there was a serious error abort getting the
// command line.
if (aborting())
{
*gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
return GOTO_NORMAL_MODE;
}
#endif
KeyTyped = FALSE; // Don't do p_wc completion.
#ifdef FEAT_EVAL
if (new_cmdpos >= 0)
{
// set_cmdline_pos() was used
if (new_cmdpos > ccline.cmdlen)
ccline.cmdpos = ccline.cmdlen;
else
ccline.cmdpos = new_cmdpos;
}
#endif
}
// remove the double quote
redrawcmd();
// The text has been stuffed, the command line didn't change yet.
return CMDLINE_NOT_CHANGED;
}
|
167804329878727127060395714139665031179
|
ex_getln.c
|
269509646770853684376504137864854849552
|
CWE-787
|
CVE-2022-2175
|
Buffer Over-read in GitHub repository vim/vim prior to 8.2.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2175
|
412,190
|
vim
|
6046aded8da002b08d380db29de2ba0268b6616e
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/6046aded8da002b08d380db29de2ba0268b6616e
|
patch 8.2.5148: invalid memory access when using expression on command line
Problem: Invalid memory access when using an expression on the command line.
Solution: Make sure the position does not go negative.
| 0
|
cmdline_insert_reg(int *gotesc UNUSED)
{
int i;
int c;
int save_new_cmdpos = new_cmdpos;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; // disallow scrolling here
#endif
putcmdline('"', TRUE);
++no_mapping;
++allow_keys;
i = c = plain_vgetc(); // CTRL-R <char>
if (i == Ctrl_O)
i = Ctrl_R; // CTRL-R CTRL-O == CTRL-R CTRL-R
if (i == Ctrl_R)
c = plain_vgetc(); // CTRL-R CTRL-R <char>
extra_char = NUL;
--no_mapping;
--allow_keys;
#ifdef FEAT_EVAL
/*
* Insert the result of an expression.
*/
new_cmdpos = -1;
if (c == '=')
{
if (ccline.cmdfirstc == '=' // can't do this recursively
|| cmdline_star > 0) // or when typing a password
{
beep_flush();
c = ESC;
}
else
c = get_expr_register();
}
#endif
if (c != ESC) // use ESC to cancel inserting register
{
cmdline_paste(c, i == Ctrl_R, FALSE);
#ifdef FEAT_EVAL
// When there was a serious error abort getting the
// command line.
if (aborting())
{
*gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
return GOTO_NORMAL_MODE;
}
#endif
KeyTyped = FALSE; // Don't do p_wc completion.
#ifdef FEAT_EVAL
if (new_cmdpos >= 0)
{
// set_cmdline_pos() was used
if (new_cmdpos > ccline.cmdlen)
ccline.cmdpos = ccline.cmdlen;
else
ccline.cmdpos = new_cmdpos;
}
#endif
}
new_cmdpos = save_new_cmdpos;
// remove the double quote
redrawcmd();
// The text has been stuffed, the command line didn't change yet.
return CMDLINE_NOT_CHANGED;
}
|
5421090615610689574320991257810194043
|
ex_getln.c
|
9575536184258751931455824501169284802
|
CWE-787
|
CVE-2022-2175
|
Buffer Over-read in GitHub repository vim/vim prior to 8.2.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2175
|
208,535
|
rizin
|
58926dffbe819fe9ebf5062f7130e026351cae01
|
https://github.com/rizinorg/rizin
|
https://github.com/rizinorg/rizin/commit/58926dffbe819fe9ebf5062f7130e026351cae01
|
fix #2964 - double-free in bin_qnx.c
| 1
|
static RzList *relocs(RzBinFile *bf) {
rz_return_val_if_fail(bf && bf->o, NULL);
QnxObj *qo = bf->o->bin_obj;
return rz_list_clone(qo->fixups);
}
|
41829514855496977293704373413382810445
|
bin_qnx.c
|
327448367050510652704729380638932181720
|
CWE-415
|
CVE-2022-36043
|
Rizin is a UNIX-like reverse engineering framework and command-line toolset. Versions 0.4.0 and prior are vulnerable to a double free in bobj.c:rz_bin_reloc_storage_free() when freeing relocations generated from qnx binary plugin. A user opening a malicious qnx binary could be affected by this vulnerability, allowing an attacker to execute code on the user's machine. Commit number a3d50c1ea185f3f642f2d8180715f82d98840784 contains a patch for this issue.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-36043
|
412,332
|
rizin
|
58926dffbe819fe9ebf5062f7130e026351cae01
|
https://github.com/rizinorg/rizin
|
https://github.com/rizinorg/rizin/commit/58926dffbe819fe9ebf5062f7130e026351cae01
|
fix #2964 - double-free in bin_qnx.c
| 0
|
static RzList *maps(RzBinFile *bf) {
rz_return_val_if_fail(bf && bf->o, NULL);
QnxObj *qo = bf->o->bin_obj;
return rz_list_clone(qo->maps);
}
|
19242058764705601713784045996495740023
|
bin_qnx.c
|
19463219798062548086589627833690645590
|
CWE-415
|
CVE-2022-36043
|
Rizin is a UNIX-like reverse engineering framework and command-line toolset. Versions 0.4.0 and prior are vulnerable to a double free in bobj.c:rz_bin_reloc_storage_free() when freeing relocations generated from qnx binary plugin. A user opening a malicious qnx binary could be affected by this vulnerability, allowing an attacker to execute code on the user's machine. Commit number a3d50c1ea185f3f642f2d8180715f82d98840784 contains a patch for this issue.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-36043
|
208,654
|
php-src
|
cab1c3b3708eead315e033359d07049b23b147a3
|
https://github.com/php/php-src
|
http://git.php.net/?p=php-src.git;a=commit;h=cab1c3b3708eead315e033359d07049b23b147a3
|
Fixed bug #72479 - same as #72434
| 1
|
PHP_MINIT_FUNCTION(snmp)
{
netsnmp_log_handler *logh;
zend_class_entry ce, cex;
le_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number);
init_snmp("snmpapp");
#ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE
/* Prevent update of the snmpapp.conf file */
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);
#endif
/* Disable logging, use exit status'es and related variabled to detect errors */
shutdown_snmp_logging();
logh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR);
if (logh) {
logh->pri_max = LOG_ERR;
}
memcpy(&php_snmp_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
php_snmp_object_handlers.read_property = php_snmp_read_property;
php_snmp_object_handlers.write_property = php_snmp_write_property;
php_snmp_object_handlers.has_property = php_snmp_has_property;
php_snmp_object_handlers.get_properties = php_snmp_get_properties;
/* Register SNMP Class */
INIT_CLASS_ENTRY(ce, "SNMP", php_snmp_class_methods);
ce.create_object = php_snmp_object_new;
php_snmp_object_handlers.clone_obj = NULL;
php_snmp_ce = zend_register_internal_class(&ce TSRMLS_CC);
/* Register SNMP Class properties */
zend_hash_init(&php_snmp_properties, 0, NULL, NULL, 1);
PHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_SUFFIX", NETSNMP_OID_OUTPUT_SUFFIX, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_MODULE", NETSNMP_OID_OUTPUT_MODULE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_FULL", NETSNMP_OID_OUTPUT_FULL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NUMERIC", NETSNMP_OID_OUTPUT_NUMERIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_UCD", NETSNMP_OID_OUTPUT_UCD, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NONE", NETSNMP_OID_OUTPUT_NONE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_LIBRARY", SNMP_VALUE_LIBRARY, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_PLAIN", SNMP_VALUE_PLAIN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_OBJECT", SNMP_VALUE_OBJECT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_BIT_STR", ASN_BIT_STR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OCTET_STR", ASN_OCTET_STR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OPAQUE", ASN_OPAQUE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_NULL", ASN_NULL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OBJECT_ID", ASN_OBJECT_ID, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_IPADDRESS", ASN_IPADDRESS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_COUNTER", ASN_GAUGE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_UNSIGNED", ASN_UNSIGNED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_TIMETICKS", ASN_TIMETICKS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_UINTEGER", ASN_UINTEGER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_INTEGER", ASN_INTEGER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_COUNTER64", ASN_COUNTER64, CONST_CS | CONST_PERSISTENT);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_1", SNMP_VERSION_1);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2c", SNMP_VERSION_2c);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2C", SNMP_VERSION_2c);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_3", SNMP_VERSION_3);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_NOERROR", PHP_SNMP_ERRNO_NOERROR);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ANY", PHP_SNMP_ERRNO_ANY);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_GENERIC", PHP_SNMP_ERRNO_GENERIC);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_TIMEOUT", PHP_SNMP_ERRNO_TIMEOUT);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ERROR_IN_REPLY", PHP_SNMP_ERRNO_ERROR_IN_REPLY);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_NOT_INCREASING", PHP_SNMP_ERRNO_OID_NOT_INCREASING);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_PARSING_ERROR", PHP_SNMP_ERRNO_OID_PARSING_ERROR);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_MULTIPLE_SET_QUERIES", PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES);
/* Register SNMPException class */
INIT_CLASS_ENTRY(cex, "SNMPException", NULL);
#ifdef HAVE_SPL
php_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException, NULL TSRMLS_CC);
#else
php_snmp_exception_ce = zend_register_internal_class_ex(&cex, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
#endif
return SUCCESS;
}
|
67376393539603801542933710123087364670
|
snmp.c
|
23932759773432740913613151934817775847
|
CWE-416
|
CVE-2016-6295
|
ext/snmp/snmp.c in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9 improperly interacts with the unserialize implementation and garbage collection, which allows remote attackers to cause a denial of service (use-after-free and application crash) or possibly have unspecified other impact via crafted serialized data, a related issue to CVE-2016-5773.
|
https://nvd.nist.gov/vuln/detail/CVE-2016-6295
|
413,339
|
php-src
|
cab1c3b3708eead315e033359d07049b23b147a3
|
https://github.com/php/php-src
|
http://git.php.net/?p=php-src.git;a=commit;h=cab1c3b3708eead315e033359d07049b23b147a3
|
Fixed bug #72479 - same as #72434
| 0
|
PHP_MINIT_FUNCTION(snmp)
{
netsnmp_log_handler *logh;
zend_class_entry ce, cex;
le_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number);
init_snmp("snmpapp");
#ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE
/* Prevent update of the snmpapp.conf file */
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);
#endif
/* Disable logging, use exit status'es and related variabled to detect errors */
shutdown_snmp_logging();
logh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR);
if (logh) {
logh->pri_max = LOG_ERR;
}
memcpy(&php_snmp_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
php_snmp_object_handlers.read_property = php_snmp_read_property;
php_snmp_object_handlers.write_property = php_snmp_write_property;
php_snmp_object_handlers.has_property = php_snmp_has_property;
php_snmp_object_handlers.get_properties = php_snmp_get_properties;
php_snmp_object_handlers.get_gc = php_snmp_get_gc;
/* Register SNMP Class */
INIT_CLASS_ENTRY(ce, "SNMP", php_snmp_class_methods);
ce.create_object = php_snmp_object_new;
php_snmp_object_handlers.clone_obj = NULL;
php_snmp_ce = zend_register_internal_class(&ce TSRMLS_CC);
/* Register SNMP Class properties */
zend_hash_init(&php_snmp_properties, 0, NULL, NULL, 1);
PHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_SUFFIX", NETSNMP_OID_OUTPUT_SUFFIX, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_MODULE", NETSNMP_OID_OUTPUT_MODULE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_FULL", NETSNMP_OID_OUTPUT_FULL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NUMERIC", NETSNMP_OID_OUTPUT_NUMERIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_UCD", NETSNMP_OID_OUTPUT_UCD, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NONE", NETSNMP_OID_OUTPUT_NONE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_LIBRARY", SNMP_VALUE_LIBRARY, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_PLAIN", SNMP_VALUE_PLAIN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_OBJECT", SNMP_VALUE_OBJECT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_BIT_STR", ASN_BIT_STR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OCTET_STR", ASN_OCTET_STR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OPAQUE", ASN_OPAQUE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_NULL", ASN_NULL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OBJECT_ID", ASN_OBJECT_ID, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_IPADDRESS", ASN_IPADDRESS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_COUNTER", ASN_GAUGE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_UNSIGNED", ASN_UNSIGNED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_TIMETICKS", ASN_TIMETICKS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_UINTEGER", ASN_UINTEGER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_INTEGER", ASN_INTEGER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_COUNTER64", ASN_COUNTER64, CONST_CS | CONST_PERSISTENT);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_1", SNMP_VERSION_1);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2c", SNMP_VERSION_2c);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2C", SNMP_VERSION_2c);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_3", SNMP_VERSION_3);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_NOERROR", PHP_SNMP_ERRNO_NOERROR);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ANY", PHP_SNMP_ERRNO_ANY);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_GENERIC", PHP_SNMP_ERRNO_GENERIC);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_TIMEOUT", PHP_SNMP_ERRNO_TIMEOUT);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ERROR_IN_REPLY", PHP_SNMP_ERRNO_ERROR_IN_REPLY);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_NOT_INCREASING", PHP_SNMP_ERRNO_OID_NOT_INCREASING);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_PARSING_ERROR", PHP_SNMP_ERRNO_OID_PARSING_ERROR);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_MULTIPLE_SET_QUERIES", PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES);
/* Register SNMPException class */
INIT_CLASS_ENTRY(cex, "SNMPException", NULL);
#ifdef HAVE_SPL
php_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException, NULL TSRMLS_CC);
#else
php_snmp_exception_ce = zend_register_internal_class_ex(&cex, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
#endif
return SUCCESS;
}
|
61841669860685177602281773654543637365
|
snmp.c
|
195062314366498303509175847868002620782
|
CWE-416
|
CVE-2016-6295
|
ext/snmp/snmp.c in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9 improperly interacts with the unserialize implementation and garbage collection, which allows remote attackers to cause a denial of service (use-after-free and application crash) or possibly have unspecified other impact via crafted serialized data, a related issue to CVE-2016-5773.
|
https://nvd.nist.gov/vuln/detail/CVE-2016-6295
|
208,680
|
radare2
|
10517e3ff0e609697eb8cde60ec8dc999ee5ea24
|
https://github.com/radare/radare2
|
https://github.com/radareorg/radare2/commit/10517e3ff0e609697eb8cde60ec8dc999ee5ea24
|
aaef on arm/thumb switches causes uaf ##crash
* Reported by peacock-doris via huntr.dev
* Reproducer: poc_uaf_r_reg_get
| 1
|
R_API void r_core_anal_esil(RCore *core, const char *str, const char *target) {
bool cfg_anal_strings = r_config_get_i (core->config, "anal.strings");
bool emu_lazy = r_config_get_i (core->config, "emu.lazy");
bool gp_fixed = r_config_get_i (core->config, "anal.gpfixed");
RAnalEsil *ESIL = core->anal->esil;
ut64 refptr = 0LL;
const char *pcname;
RAnalOp op = R_EMPTY;
ut8 *buf = NULL;
bool end_address_set = false;
int iend;
int minopsize = 4; // XXX this depends on asm->mininstrsize
bool archIsArm = false;
ut64 addr = core->offset;
ut64 start = addr;
ut64 end = 0LL;
ut64 cur;
if (esil_anal_stop || r_cons_is_breaked ()) {
// faster ^C
return;
}
mycore = core;
if (!strcmp (str, "?")) {
eprintf ("Usage: aae[f] [len] [addr] - analyze refs in function, section or len bytes with esil\n");
eprintf (" aae $SS @ $S - analyze the whole section\n");
eprintf (" aae $SS str.Hello @ $S - find references for str.Hellow\n");
eprintf (" aaef - analyze functions discovered with esil\n");
return;
}
#define CHECKREF(x) ((refptr && (x) == refptr) || !refptr)
if (target) {
const char *expr = r_str_trim_head_ro (target);
if (*expr) {
refptr = ntarget = r_num_math (core->num, expr);
if (!refptr) {
ntarget = refptr = addr;
}
} else {
ntarget = UT64_MAX;
refptr = 0LL;
}
} else {
ntarget = UT64_MAX;
refptr = 0LL;
}
RAnalFunction *fcn = NULL;
if (!strcmp (str, "f")) {
fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
if (fcn) {
start = r_anal_function_min_addr (fcn);
addr = fcn->addr;
end = r_anal_function_max_addr (fcn);
end_address_set = true;
}
}
if (!end_address_set) {
if (str[0] == ' ') {
end = addr + r_num_math (core->num, str + 1);
} else {
RIOMap *map = r_io_map_get_at (core->io, addr);
if (map) {
end = r_io_map_end (map);
} else {
end = addr + core->blocksize;
}
}
}
iend = end - start;
if (iend < 0) {
return;
}
if (iend > MAX_SCAN_SIZE) {
eprintf ("Warning: Not going to analyze 0x%08"PFMT64x" bytes.\n", (ut64)iend);
return;
}
buf = malloc ((size_t)iend + 2);
if (!buf) {
perror ("malloc");
return;
}
esilbreak_last_read = UT64_MAX;
r_io_read_at (core->io, start, buf, iend + 1);
if (!ESIL) {
r_core_cmd0 (core, "aei");
ESIL = core->anal->esil;
if (!ESIL) {
eprintf ("ESIL not initialized\n");
return;
}
r_core_cmd0 (core, "aeim");
ESIL = core->anal->esil;
}
const char *spname = r_reg_get_name (core->anal->reg, R_REG_NAME_SP);
if (!spname) {
eprintf ("Error: No =SP defined in the reg profile.\n");
return;
}
EsilBreakCtx ctx = {
&op,
fcn,
spname,
r_reg_getv (core->anal->reg, spname)
};
ESIL->cb.hook_reg_write = &esilbreak_reg_write;
//this is necessary for the hook to read the id of analop
ESIL->user = &ctx;
ESIL->cb.hook_mem_read = &esilbreak_mem_read;
ESIL->cb.hook_mem_write = &esilbreak_mem_write;
if (fcn && fcn->reg_save_area) {
r_reg_setv (core->anal->reg, ctx.spname, ctx.initial_sp - fcn->reg_save_area);
}
//eprintf ("Analyzing ESIL refs from 0x%"PFMT64x" - 0x%"PFMT64x"\n", addr, end);
// TODO: backup/restore register state before/after analysis
pcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
if (!pcname || !*pcname) {
eprintf ("Cannot find program counter register in the current profile.\n");
return;
}
esil_anal_stop = false;
r_cons_break_push (cccb, core);
int arch = -1;
if (!strcmp (core->anal->cur->arch, "arm")) {
switch (core->anal->cur->bits) {
case 64: arch = R2_ARCH_ARM64; break;
case 32: arch = R2_ARCH_ARM32; break;
case 16: arch = R2_ARCH_THUMB; break;
}
archIsArm = true;
}
ut64 gp = r_config_get_i (core->config, "anal.gp");
const char *gp_reg = NULL;
if (!strcmp (core->anal->cur->arch, "mips")) {
gp_reg = "gp";
arch = R2_ARCH_MIPS;
}
const char *sn = r_reg_get_name (core->anal->reg, R_REG_NAME_SN);
if (!sn) {
eprintf ("Warning: No SN reg alias for current architecture.\n");
}
r_reg_arena_push (core->anal->reg);
IterCtx ictx = { start, end, fcn, NULL };
size_t i = addr - start;
size_t i_old = 0;
do {
if (esil_anal_stop || r_cons_is_breaked ()) {
break;
}
cur = start + i;
if (!r_io_is_valid_offset (core->io, cur, 0)) {
break;
}
#if 0
// disabled because it causes some tests to fail
{
RPVector *list = r_meta_get_all_in (core->anal, cur, R_META_TYPE_ANY);
void **it;
r_pvector_foreach (list, it) {
RIntervalNode *node = *it;
RAnalMetaItem *meta = node->data;
switch (meta->type) {
case R_META_TYPE_DATA:
case R_META_TYPE_STRING:
case R_META_TYPE_FORMAT:
#if 0
{
int msz = r_meta_get_size (core->anal, meta->type);
i += (msz > 0)? msz: minopsize;
}
r_pvector_free (list);
goto loopback;
#elif 0
{
int msz = r_meta_get_size (core->anal, meta->type);
i += (msz > 0)? msz: minopsize;
i--;
}
#else
i += 4;
goto repeat;
#endif
default:
break;
}
}
r_pvector_free (list);
}
#endif
/* realign address if needed */
r_core_seek_arch_bits (core, cur);
int opalign = core->anal->pcalign;
if (opalign > 0) {
cur -= (cur % opalign);
}
r_anal_op_fini (&op);
r_asm_set_pc (core->rasm, cur);
i_old = i;
#if 1
if (i > iend) {
goto repeat;
}
#endif
if (!r_anal_op (core->anal, &op, cur, buf + i, iend - i, R_ANAL_OP_MASK_ESIL | R_ANAL_OP_MASK_VAL | R_ANAL_OP_MASK_HINT)) {
i += minopsize - 1; // XXX dupe in op.size below
}
if (op.type == R_ANAL_OP_TYPE_ILL || op.type == R_ANAL_OP_TYPE_UNK) {
// i += 2
r_anal_op_fini (&op);
goto repeat;
}
//we need to check again i because buf+i may goes beyond its boundaries
//because of i+= minopsize - 1
if (op.size < 1) {
i += minopsize - 1;
goto repeat;
}
if (emu_lazy) {
if (op.type & R_ANAL_OP_TYPE_REP) {
i += op.size - 1;
goto repeat;
}
switch (op.type & R_ANAL_OP_TYPE_MASK) {
case R_ANAL_OP_TYPE_JMP:
case R_ANAL_OP_TYPE_CJMP:
case R_ANAL_OP_TYPE_CALL:
case R_ANAL_OP_TYPE_RET:
case R_ANAL_OP_TYPE_ILL:
case R_ANAL_OP_TYPE_NOP:
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_IO:
case R_ANAL_OP_TYPE_LEAVE:
case R_ANAL_OP_TYPE_CRYPTO:
case R_ANAL_OP_TYPE_CPL:
case R_ANAL_OP_TYPE_SYNC:
case R_ANAL_OP_TYPE_SWI:
case R_ANAL_OP_TYPE_CMP:
case R_ANAL_OP_TYPE_ACMP:
case R_ANAL_OP_TYPE_NULL:
case R_ANAL_OP_TYPE_CSWI:
case R_ANAL_OP_TYPE_TRAP:
i += op.size - 1;
goto repeat;
// those require write support
case R_ANAL_OP_TYPE_PUSH:
case R_ANAL_OP_TYPE_POP:
i += op.size - 1;
goto repeat;
}
}
if (sn && op.type == R_ANAL_OP_TYPE_SWI) {
r_strf_buffer (64);
r_flag_space_set (core->flags, R_FLAGS_FS_SYSCALLS);
int snv = (arch == R2_ARCH_THUMB)? op.val: (int)r_reg_getv (core->anal->reg, sn);
RSyscallItem *si = r_syscall_get (core->anal->syscall, snv, -1);
if (si) {
// eprintf ("0x%08"PFMT64x" SYSCALL %-4d %s\n", cur, snv, si->name);
r_flag_set_next (core->flags, r_strf ("syscall.%s", si->name), cur, 1);
} else {
//todo were doing less filtering up top because we can't match against 80 on all platforms
// might get too many of this path now..
// eprintf ("0x%08"PFMT64x" SYSCALL %d\n", cur, snv);
r_flag_set_next (core->flags, r_strf ("syscall.%d", snv), cur, 1);
}
r_flag_space_set (core->flags, NULL);
r_syscall_item_free (si);
}
const char *esilstr = R_STRBUF_SAFEGET (&op.esil);
i += op.size - 1;
if (R_STR_ISEMPTY (esilstr)) {
goto repeat;
}
r_anal_esil_set_pc (ESIL, cur);
r_reg_setv (core->anal->reg, pcname, cur + op.size);
if (gp_fixed && gp_reg) {
r_reg_setv (core->anal->reg, gp_reg, gp);
}
(void)r_anal_esil_parse (ESIL, esilstr);
// looks like ^C is handled by esil_parse !!!!
//r_anal_esil_dumpstack (ESIL);
//r_anal_esil_stack_free (ESIL);
switch (op.type) {
case R_ANAL_OP_TYPE_LEA:
// arm64
if (core->anal->cur && arch == R2_ARCH_ARM64) {
if (CHECKREF (ESIL->cur)) {
r_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);
}
} else if ((target && op.ptr == ntarget) || !target) {
if (CHECKREF (ESIL->cur)) {
if (op.ptr && r_io_is_valid_offset (core->io, op.ptr, !core->anal->opt.noncode)) {
r_anal_xrefs_set (core->anal, cur, op.ptr, R_ANAL_REF_TYPE_STRING);
} else {
r_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);
}
}
}
if (cfg_anal_strings) {
add_string_ref (core, op.addr, op.ptr);
}
break;
case R_ANAL_OP_TYPE_ADD:
/* TODO: test if this is valid for other archs too */
if (core->anal->cur && archIsArm) {
/* This code is known to work on Thumb, ARM and ARM64 */
ut64 dst = ESIL->cur;
if ((target && dst == ntarget) || !target) {
if (CHECKREF (dst)) {
int type = core_type_by_addr (core, dst); // R_ANAL_REF_TYPE_DATA;
r_anal_xrefs_set (core->anal, cur, dst, type);
}
}
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
} else if ((core->anal->bits == 32 && core->anal->cur && arch == R2_ARCH_MIPS)) {
ut64 dst = ESIL->cur;
if (!op.src[0] || !op.src[0]->reg || !op.src[0]->reg->name) {
break;
}
if (!strcmp (op.src[0]->reg->name, "sp")) {
break;
}
if (!strcmp (op.src[0]->reg->name, "zero")) {
break;
}
if ((target && dst == ntarget) || !target) {
if (dst > 0xffff && op.src[1] && (dst & 0xffff) == (op.src[1]->imm & 0xffff) && myvalid (mycore->io, dst)) {
RFlagItem *f;
char *str;
if (CHECKREF (dst) || CHECKREF (cur)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
if ((f = r_core_flag_get_by_spaces (core->flags, dst))) {
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, f->name);
} else if ((str = is_string_at (mycore, dst, NULL))) {
char *str2 = r_str_newf ("esilref: '%s'", str);
// HACK avoid format string inside string used later as format
// string crashes disasm inside agf under some conditions.
// https://github.com/radareorg/radare2/issues/6937
r_str_replace_char (str2, '%', '&');
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, str2);
free (str2);
free (str);
}
}
}
}
}
break;
case R_ANAL_OP_TYPE_LOAD:
{
ut64 dst = esilbreak_last_read;
if (dst != UT64_MAX && CHECKREF (dst)) {
if (myvalid (mycore->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
}
}
dst = esilbreak_last_data;
if (dst != UT64_MAX && CHECKREF (dst)) {
if (myvalid (mycore->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
}
}
}
break;
case R_ANAL_OP_TYPE_JMP:
{
ut64 dst = op.jump;
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CODE);
}
}
}
break;
case R_ANAL_OP_TYPE_CALL:
{
ut64 dst = op.jump;
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CALL);
}
ESIL->old = cur + op.size;
getpcfromstack (core, ESIL);
}
}
break;
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_UCALL:
case R_ANAL_OP_TYPE_ICALL:
case R_ANAL_OP_TYPE_RCALL:
case R_ANAL_OP_TYPE_IRCALL:
case R_ANAL_OP_TYPE_MJMP:
{
ut64 dst = core->anal->esil->jump_target;
if (dst == 0 || dst == UT64_MAX) {
dst = r_reg_getv (core->anal->reg, pcname);
}
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
RAnalRefType ref =
(op.type & R_ANAL_OP_TYPE_MASK) == R_ANAL_OP_TYPE_UCALL
? R_ANAL_REF_TYPE_CALL
: R_ANAL_REF_TYPE_CODE;
r_anal_xrefs_set (core->anal, cur, dst, ref);
r_core_anal_fcn (core, dst, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1);
// analyze function here
#if 0
if (op.type == R_ANAL_OP_TYPE_UCALL || op.type == R_ANAL_OP_TYPE_RCALL) {
eprintf ("0x%08"PFMT64x" RCALL TO %llx\n", cur, dst);
}
#endif
}
}
}
break;
default:
break;
}
r_anal_esil_stack_free (ESIL);
repeat:
if (!r_anal_get_block_at (core->anal, cur)) {
size_t fcn_i;
for (fcn_i = i_old + 1; fcn_i <= i; fcn_i++) {
if (r_anal_get_function_at (core->anal, start + fcn_i)) {
i = fcn_i - 1;
break;
}
}
}
if (i >= iend) {
break;
}
} while (get_next_i (&ictx, &i));
r_list_free (ictx.bbl);
r_list_free (ictx.path);
r_list_free (ictx.switch_path);
free (buf);
ESIL->cb.hook_mem_read = NULL;
ESIL->cb.hook_mem_write = NULL;
ESIL->cb.hook_reg_write = NULL;
ESIL->user = NULL;
r_anal_op_fini (&op);
r_cons_break_pop ();
// restore register
r_reg_arena_pop (core->anal->reg);
}
|
25949004488581343936391059714889689262
|
None
|
CWE-416
|
CVE-2022-0849
|
Use After Free in r_reg_get_name_idx in GitHub repository radareorg/radare2 prior to 5.6.6.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0849
|
|
413,623
|
radare2
|
10517e3ff0e609697eb8cde60ec8dc999ee5ea24
|
https://github.com/radare/radare2
|
https://github.com/radareorg/radare2/commit/10517e3ff0e609697eb8cde60ec8dc999ee5ea24
|
aaef on arm/thumb switches causes uaf ##crash
* Reported by peacock-doris via huntr.dev
* Reproducer: poc_uaf_r_reg_get
| 0
|
R_API void r_core_anal_esil(RCore *core, const char *str, const char *target) {
bool cfg_anal_strings = r_config_get_i (core->config, "anal.strings");
bool emu_lazy = r_config_get_i (core->config, "emu.lazy");
bool gp_fixed = r_config_get_i (core->config, "anal.gpfixed");
RAnalEsil *ESIL = core->anal->esil;
ut64 refptr = 0LL;
char *pcname = NULL;
RAnalOp op = R_EMPTY;
ut8 *buf = NULL;
bool end_address_set = false;
int iend;
int minopsize = 4; // XXX this depends on asm->mininstrsize
bool archIsArm = false;
ut64 addr = core->offset;
ut64 start = addr;
ut64 end = 0LL;
ut64 cur;
if (esil_anal_stop || r_cons_is_breaked ()) {
// faster ^C
return;
}
mycore = core;
if (!strcmp (str, "?")) {
eprintf ("Usage: aae[f] [len] [addr] - analyze refs in function, section or len bytes with esil\n");
eprintf (" aae $SS @ $S - analyze the whole section\n");
eprintf (" aae $SS str.Hello @ $S - find references for str.Hellow\n");
eprintf (" aaef - analyze functions discovered with esil\n");
return;
}
#define CHECKREF(x) ((refptr && (x) == refptr) || !refptr)
if (target) {
const char *expr = r_str_trim_head_ro (target);
if (*expr) {
refptr = ntarget = r_num_math (core->num, expr);
if (!refptr) {
ntarget = refptr = addr;
}
} else {
ntarget = UT64_MAX;
refptr = 0LL;
}
} else {
ntarget = UT64_MAX;
refptr = 0LL;
}
RAnalFunction *fcn = NULL;
if (!strcmp (str, "f")) {
fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
if (fcn) {
start = r_anal_function_min_addr (fcn);
addr = fcn->addr;
end = r_anal_function_max_addr (fcn);
end_address_set = true;
}
}
if (!end_address_set) {
if (str[0] == ' ') {
end = addr + r_num_math (core->num, str + 1);
} else {
RIOMap *map = r_io_map_get_at (core->io, addr);
if (map) {
end = r_io_map_end (map);
} else {
end = addr + core->blocksize;
}
}
}
iend = end - start;
if (iend < 0) {
return;
}
if (iend > MAX_SCAN_SIZE) {
eprintf ("Warning: Not going to analyze 0x%08"PFMT64x" bytes.\n", (ut64)iend);
return;
}
buf = malloc ((size_t)iend + 2);
if (!buf) {
perror ("malloc");
return;
}
esilbreak_last_read = UT64_MAX;
r_io_read_at (core->io, start, buf, iend + 1);
if (!ESIL) {
r_core_cmd0 (core, "aei");
ESIL = core->anal->esil;
if (!ESIL) {
eprintf ("ESIL not initialized\n");
return;
}
r_core_cmd0 (core, "aeim");
ESIL = core->anal->esil;
}
const char *kspname = r_reg_get_name (core->anal->reg, R_REG_NAME_SP);
if (R_STR_ISEMPTY (kspname)) {
eprintf ("Error: No =SP defined in the reg profile.\n");
return;
}
char *spname = strdup (kspname);
EsilBreakCtx ctx = {
&op,
fcn,
spname,
r_reg_getv (core->anal->reg, spname)
};
ESIL->cb.hook_reg_write = &esilbreak_reg_write;
//this is necessary for the hook to read the id of analop
ESIL->user = &ctx;
ESIL->cb.hook_mem_read = &esilbreak_mem_read;
ESIL->cb.hook_mem_write = &esilbreak_mem_write;
if (fcn && fcn->reg_save_area) {
r_reg_setv (core->anal->reg, ctx.spname, ctx.initial_sp - fcn->reg_save_area);
}
//eprintf ("Analyzing ESIL refs from 0x%"PFMT64x" - 0x%"PFMT64x"\n", addr, end);
// TODO: backup/restore register state before/after analysis
const char *kpcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
if (!kpcname || !*kpcname) {
eprintf ("Cannot find program counter register in the current profile.\n");
return;
}
pcname = strdup (kpcname);
esil_anal_stop = false;
r_cons_break_push (cccb, core);
int arch = -1;
if (!strcmp (core->anal->cur->arch, "arm")) {
switch (core->anal->cur->bits) {
case 64: arch = R2_ARCH_ARM64; break;
case 32: arch = R2_ARCH_ARM32; break;
case 16: arch = R2_ARCH_THUMB; break;
}
archIsArm = true;
}
ut64 gp = r_config_get_i (core->config, "anal.gp");
const char *gp_reg = NULL;
if (!strcmp (core->anal->cur->arch, "mips")) {
gp_reg = "gp";
arch = R2_ARCH_MIPS;
}
const char *sn = r_reg_get_name (core->anal->reg, R_REG_NAME_SN);
if (!sn) {
eprintf ("Warning: No SN reg alias for current architecture.\n");
}
r_reg_arena_push (core->anal->reg);
IterCtx ictx = { start, end, fcn, NULL };
size_t i = addr - start;
size_t i_old = 0;
do {
if (esil_anal_stop || r_cons_is_breaked ()) {
break;
}
cur = start + i;
if (!r_io_is_valid_offset (core->io, cur, 0)) {
break;
}
#if 0
// disabled because it causes some tests to fail
{
RPVector *list = r_meta_get_all_in (core->anal, cur, R_META_TYPE_ANY);
void **it;
r_pvector_foreach (list, it) {
RIntervalNode *node = *it;
RAnalMetaItem *meta = node->data;
switch (meta->type) {
case R_META_TYPE_DATA:
case R_META_TYPE_STRING:
case R_META_TYPE_FORMAT:
#if 0
{
int msz = r_meta_get_size (core->anal, meta->type);
i += (msz > 0)? msz: minopsize;
}
r_pvector_free (list);
goto loopback;
#elif 0
{
int msz = r_meta_get_size (core->anal, meta->type);
i += (msz > 0)? msz: minopsize;
i--;
}
#else
i += 4;
goto repeat;
#endif
default:
break;
}
}
r_pvector_free (list);
}
#endif
/* realign address if needed */
r_core_seek_arch_bits (core, cur);
int opalign = core->anal->pcalign;
if (opalign > 0) {
cur -= (cur % opalign);
}
r_anal_op_fini (&op);
r_asm_set_pc (core->rasm, cur);
i_old = i;
if (i > iend) {
goto repeat;
}
if (!r_anal_op (core->anal, &op, cur, buf + i, iend - i, R_ANAL_OP_MASK_ESIL | R_ANAL_OP_MASK_VAL | R_ANAL_OP_MASK_HINT)) {
i += minopsize - 1; // XXX dupe in op.size below
}
if (op.type == R_ANAL_OP_TYPE_ILL || op.type == R_ANAL_OP_TYPE_UNK) {
// i += 2
r_anal_op_fini (&op);
goto repeat;
}
//we need to check again i because buf+i may goes beyond its boundaries
//because of i+= minopsize - 1
if (op.size < 1) {
i += minopsize - 1;
goto repeat;
}
if (emu_lazy) {
if (op.type & R_ANAL_OP_TYPE_REP) {
i += op.size - 1;
goto repeat;
}
switch (op.type & R_ANAL_OP_TYPE_MASK) {
case R_ANAL_OP_TYPE_JMP:
case R_ANAL_OP_TYPE_CJMP:
case R_ANAL_OP_TYPE_CALL:
case R_ANAL_OP_TYPE_RET:
case R_ANAL_OP_TYPE_ILL:
case R_ANAL_OP_TYPE_NOP:
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_IO:
case R_ANAL_OP_TYPE_LEAVE:
case R_ANAL_OP_TYPE_CRYPTO:
case R_ANAL_OP_TYPE_CPL:
case R_ANAL_OP_TYPE_SYNC:
case R_ANAL_OP_TYPE_SWI:
case R_ANAL_OP_TYPE_CMP:
case R_ANAL_OP_TYPE_ACMP:
case R_ANAL_OP_TYPE_NULL:
case R_ANAL_OP_TYPE_CSWI:
case R_ANAL_OP_TYPE_TRAP:
i += op.size - 1;
goto repeat;
// those require write support
case R_ANAL_OP_TYPE_PUSH:
case R_ANAL_OP_TYPE_POP:
i += op.size - 1;
goto repeat;
}
}
if (sn && op.type == R_ANAL_OP_TYPE_SWI) {
r_strf_buffer (64);
r_flag_space_set (core->flags, R_FLAGS_FS_SYSCALLS);
int snv = (arch == R2_ARCH_THUMB)? op.val: (int)r_reg_getv (core->anal->reg, sn);
RSyscallItem *si = r_syscall_get (core->anal->syscall, snv, -1);
if (si) {
// eprintf ("0x%08"PFMT64x" SYSCALL %-4d %s\n", cur, snv, si->name);
r_flag_set_next (core->flags, r_strf ("syscall.%s", si->name), cur, 1);
} else {
//todo were doing less filtering up top because we can't match against 80 on all platforms
// might get too many of this path now..
// eprintf ("0x%08"PFMT64x" SYSCALL %d\n", cur, snv);
r_flag_set_next (core->flags, r_strf ("syscall.%d", snv), cur, 1);
}
r_flag_space_set (core->flags, NULL);
r_syscall_item_free (si);
}
const char *esilstr = R_STRBUF_SAFEGET (&op.esil);
i += op.size - 1;
if (R_STR_ISEMPTY (esilstr)) {
goto repeat;
}
r_anal_esil_set_pc (ESIL, cur);
r_reg_setv (core->anal->reg, pcname, cur + op.size);
if (gp_fixed && gp_reg) {
r_reg_setv (core->anal->reg, gp_reg, gp);
}
(void)r_anal_esil_parse (ESIL, esilstr);
// looks like ^C is handled by esil_parse !!!!
//r_anal_esil_dumpstack (ESIL);
//r_anal_esil_stack_free (ESIL);
switch (op.type) {
case R_ANAL_OP_TYPE_LEA:
// arm64
if (core->anal->cur && arch == R2_ARCH_ARM64) {
if (CHECKREF (ESIL->cur)) {
r_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);
}
} else if ((target && op.ptr == ntarget) || !target) {
if (CHECKREF (ESIL->cur)) {
if (op.ptr && r_io_is_valid_offset (core->io, op.ptr, !core->anal->opt.noncode)) {
r_anal_xrefs_set (core->anal, cur, op.ptr, R_ANAL_REF_TYPE_STRING);
} else {
r_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);
}
}
}
if (cfg_anal_strings) {
add_string_ref (core, op.addr, op.ptr);
}
break;
case R_ANAL_OP_TYPE_ADD:
/* TODO: test if this is valid for other archs too */
if (core->anal->cur && archIsArm) {
/* This code is known to work on Thumb, ARM and ARM64 */
ut64 dst = ESIL->cur;
if ((target && dst == ntarget) || !target) {
if (CHECKREF (dst)) {
int type = core_type_by_addr (core, dst); // R_ANAL_REF_TYPE_DATA;
r_anal_xrefs_set (core->anal, cur, dst, type);
}
}
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
} else if ((core->anal->bits == 32 && core->anal->cur && arch == R2_ARCH_MIPS)) {
ut64 dst = ESIL->cur;
if (!op.src[0] || !op.src[0]->reg || !op.src[0]->reg->name) {
break;
}
if (!strcmp (op.src[0]->reg->name, "sp")) {
break;
}
if (!strcmp (op.src[0]->reg->name, "zero")) {
break;
}
if ((target && dst == ntarget) || !target) {
if (dst > 0xffff && op.src[1] && (dst & 0xffff) == (op.src[1]->imm & 0xffff) && myvalid (mycore->io, dst)) {
RFlagItem *f;
char *str;
if (CHECKREF (dst) || CHECKREF (cur)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
if ((f = r_core_flag_get_by_spaces (core->flags, dst))) {
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, f->name);
} else if ((str = is_string_at (mycore, dst, NULL))) {
char *str2 = r_str_newf ("esilref: '%s'", str);
// HACK avoid format string inside string used later as format
// string crashes disasm inside agf under some conditions.
// https://github.com/radareorg/radare2/issues/6937
r_str_replace_char (str2, '%', '&');
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, str2);
free (str2);
free (str);
}
}
}
}
}
break;
case R_ANAL_OP_TYPE_LOAD:
{
ut64 dst = esilbreak_last_read;
if (dst != UT64_MAX && CHECKREF (dst)) {
if (myvalid (mycore->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
}
}
dst = esilbreak_last_data;
if (dst != UT64_MAX && CHECKREF (dst)) {
if (myvalid (mycore->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
}
}
}
break;
case R_ANAL_OP_TYPE_JMP:
{
ut64 dst = op.jump;
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CODE);
}
}
}
break;
case R_ANAL_OP_TYPE_CALL:
{
ut64 dst = op.jump;
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CALL);
}
ESIL->old = cur + op.size;
getpcfromstack (core, ESIL);
}
}
break;
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_UCALL:
case R_ANAL_OP_TYPE_ICALL:
case R_ANAL_OP_TYPE_RCALL:
case R_ANAL_OP_TYPE_IRCALL:
case R_ANAL_OP_TYPE_MJMP:
{
ut64 dst = core->anal->esil->jump_target;
if (dst == 0 || dst == UT64_MAX) {
dst = r_reg_getv (core->anal->reg, pcname);
}
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
RAnalRefType ref =
(op.type & R_ANAL_OP_TYPE_MASK) == R_ANAL_OP_TYPE_UCALL
? R_ANAL_REF_TYPE_CALL
: R_ANAL_REF_TYPE_CODE;
r_anal_xrefs_set (core->anal, cur, dst, ref);
r_core_anal_fcn (core, dst, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1);
// analyze function here
#if 0
if (op.type == R_ANAL_OP_TYPE_UCALL || op.type == R_ANAL_OP_TYPE_RCALL) {
eprintf ("0x%08"PFMT64x" RCALL TO %llx\n", cur, dst);
}
#endif
}
}
}
break;
default:
break;
}
r_anal_esil_stack_free (ESIL);
repeat:
if (!r_anal_get_block_at (core->anal, cur)) {
size_t fcn_i;
for (fcn_i = i_old + 1; fcn_i <= i; fcn_i++) {
if (r_anal_get_function_at (core->anal, start + fcn_i)) {
i = fcn_i - 1;
break;
}
}
}
if (i >= iend) {
break;
}
} while (get_next_i (&ictx, &i));
free (pcname);
free (spname);
r_list_free (ictx.bbl);
r_list_free (ictx.path);
r_list_free (ictx.switch_path);
free (buf);
ESIL->cb.hook_mem_read = NULL;
ESIL->cb.hook_mem_write = NULL;
ESIL->cb.hook_reg_write = NULL;
ESIL->user = NULL;
r_anal_op_fini (&op);
r_cons_break_pop ();
// restore register
r_reg_arena_pop (core->anal->reg);
}
|
238488437783667654322031890485445145764
|
None
|
CWE-416
|
CVE-2022-0849
|
Use After Free in r_reg_get_name_idx in GitHub repository radareorg/radare2 prior to 5.6.6.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-0849
|
|
208,912
|
vim
|
1c3dd8ddcba63c1af5112e567215b3cec2de11d0
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/1c3dd8ddcba63c1af5112e567215b3cec2de11d0
|
patch 9.0.0490: using freed memory with cmdwin and BufEnter autocmd
Problem: Using freed memory with cmdwin and BufEnter autocmd.
Solution: Make sure pointer to b_p_iminsert is still valid.
| 1
|
getcmdline_int(
int firstc,
long count UNUSED, // only used for incremental search
int indent, // indent for inside conditionals
int clear_ccline) // clear ccline first
{
static int depth = 0; // call depth
int c;
int i;
int j;
int gotesc = FALSE; // TRUE when <ESC> just typed
int do_abbr; // when TRUE check for abbr.
char_u *lookfor = NULL; // string to match
int hiscnt; // current history line in use
int histype; // history type to be used
#ifdef FEAT_SEARCH_EXTRA
incsearch_state_T is_state;
#endif
int did_wild_list = FALSE; // did wild_list() recently
int wim_index = 0; // index in wim_flags[]
int res;
int save_msg_scroll = msg_scroll;
int save_State = State; // remember State when called
int some_key_typed = FALSE; // one of the keys was typed
// mouse drag and release events are ignored, unless they are
// preceded with a mouse down event
int ignore_drag_release = TRUE;
#ifdef FEAT_EVAL
int break_ctrl_c = FALSE;
#endif
expand_T xpc;
long *b_im_ptr = NULL;
cmdline_info_T save_ccline;
int did_save_ccline = FALSE;
int cmdline_type;
int wild_type;
// one recursion level deeper
++depth;
if (ccline.cmdbuff != NULL)
{
// Being called recursively. Since ccline is global, we need to save
// the current buffer and restore it when returning.
save_cmdline(&save_ccline);
did_save_ccline = TRUE;
}
if (clear_ccline)
CLEAR_FIELD(ccline);
#ifdef FEAT_EVAL
if (firstc == -1)
{
firstc = NUL;
break_ctrl_c = TRUE;
}
#endif
#ifdef FEAT_RIGHTLEFT
// start without Hebrew mapping for a command line
if (firstc == ':' || firstc == '=' || firstc == '>')
cmd_hkmap = 0;
#endif
#ifdef FEAT_SEARCH_EXTRA
init_incsearch_state(&is_state);
#endif
if (init_ccline(firstc, indent) != OK)
goto theend; // out of memory
if (depth == 50)
{
// Somehow got into a loop recursively calling getcmdline(), bail out.
emsg(_(e_command_too_recursive));
goto theend;
}
ExpandInit(&xpc);
ccline.xpc = &xpc;
#ifdef FEAT_RIGHTLEFT
if (curwin->w_p_rl && *curwin->w_p_rlc == 's'
&& (firstc == '/' || firstc == '?'))
cmdmsg_rl = TRUE;
else
cmdmsg_rl = FALSE;
#endif
redir_off = TRUE; // don't redirect the typed command
if (!cmd_silent)
{
i = msg_scrolled;
msg_scrolled = 0; // avoid wait_return() message
gotocmdline(TRUE);
msg_scrolled += i;
redrawcmdprompt(); // draw prompt or indent
set_cmdspos();
}
xpc.xp_context = EXPAND_NOTHING;
xpc.xp_backslash = XP_BS_NONE;
#ifndef BACKSLASH_IN_FILENAME
xpc.xp_shell = FALSE;
#endif
#if defined(FEAT_EVAL)
if (ccline.input_fn)
{
xpc.xp_context = ccline.xp_context;
xpc.xp_pattern = ccline.cmdbuff;
xpc.xp_arg = ccline.xp_arg;
}
#endif
/*
* Avoid scrolling when called by a recursive do_cmdline(), e.g. when
* doing ":@0" when register 0 doesn't contain a CR.
*/
msg_scroll = FALSE;
State = MODE_CMDLINE;
if (firstc == '/' || firstc == '?' || firstc == '@')
{
// Use ":lmap" mappings for search pattern and input().
if (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)
b_im_ptr = &curbuf->b_p_iminsert;
else
b_im_ptr = &curbuf->b_p_imsearch;
if (*b_im_ptr == B_IMODE_LMAP)
State |= MODE_LANGMAP;
#ifdef HAVE_INPUT_METHOD
im_set_active(*b_im_ptr == B_IMODE_IM);
#endif
}
#ifdef HAVE_INPUT_METHOD
else if (p_imcmdline)
im_set_active(TRUE);
#endif
setmouse();
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
// When inside an autocommand for writing "exiting" may be set and
// terminal mode set to cooked. Need to set raw mode here then.
settmode(TMODE_RAW);
// Trigger CmdlineEnter autocommands.
cmdline_type = firstc == NUL ? '-' : firstc;
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINEENTER);
#ifdef FEAT_EVAL
if (!debug_mode)
may_trigger_modechanged();
#endif
init_history();
hiscnt = get_hislen(); // set hiscnt to impossible history value
histype = hist_char2type(firstc);
#ifdef FEAT_DIGRAPHS
do_digraph(-1); // init digraph typeahead
#endif
// If something above caused an error, reset the flags, we do want to type
// and execute commands. Display may be messed up a bit.
if (did_emsg)
redrawcmd();
#ifdef FEAT_STL_OPT
// Redraw the statusline in case it uses the current mode using the mode()
// function.
if (!cmd_silent && msg_scrolled == 0)
{
int found_one = FALSE;
win_T *wp;
FOR_ALL_WINDOWS(wp)
if (*p_stl != NUL || *wp->w_p_stl != NUL)
{
wp->w_redr_status = TRUE;
found_one = TRUE;
}
if (*p_tal != NUL)
{
redraw_tabline = TRUE;
found_one = TRUE;
}
if (found_one)
redraw_statuslines();
}
#endif
did_emsg = FALSE;
got_int = FALSE;
/*
* Collect the command string, handling editing keys.
*/
for (;;)
{
int trigger_cmdlinechanged = TRUE;
int end_wildmenu;
redir_off = TRUE; // Don't redirect the typed command.
// Repeated, because a ":redir" inside
// completion may switch it on.
#ifdef USE_ON_FLY_SCROLL
dont_scroll = FALSE; // allow scrolling here
#endif
quit_more = FALSE; // reset after CTRL-D which had a more-prompt
did_emsg = FALSE; // There can't really be a reason why an error
// that occurs while typing a command should
// cause the command not to be executed.
// Trigger SafeState if nothing is pending.
may_trigger_safestate(xpc.xp_numfiles <= 0);
// Get a character. Ignore K_IGNORE and K_NOP, they should not do
// anything, such as stop completion.
do
{
cursorcmd(); // set the cursor on the right spot
c = safe_vgetc();
} while (c == K_IGNORE || c == K_NOP);
if (c == K_COMMAND || c == K_SCRIPT_COMMAND)
{
int clen = ccline.cmdlen;
if (do_cmdkey_command(c, DOCMD_NOWAIT) == OK)
{
if (clen == ccline.cmdlen)
trigger_cmdlinechanged = FALSE;
goto cmdline_changed;
}
}
if (KeyTyped)
{
some_key_typed = TRUE;
#ifdef FEAT_RIGHTLEFT
if (cmd_hkmap)
c = hkmap(c);
if (cmdmsg_rl && !KeyStuffed)
{
// Invert horizontal movements and operations. Only when
// typed by the user directly, not when the result of a
// mapping.
switch (c)
{
case K_RIGHT: c = K_LEFT; break;
case K_S_RIGHT: c = K_S_LEFT; break;
case K_C_RIGHT: c = K_C_LEFT; break;
case K_LEFT: c = K_RIGHT; break;
case K_S_LEFT: c = K_S_RIGHT; break;
case K_C_LEFT: c = K_C_RIGHT; break;
}
}
#endif
}
/*
* Ignore got_int when CTRL-C was typed here.
* Don't ignore it in :global, we really need to break then, e.g., for
* ":g/pat/normal /pat" (without the <CR>).
* Don't ignore it for the input() function.
*/
if ((c == Ctrl_C
#ifdef UNIX
|| c == intr_char
#endif
)
#if defined(FEAT_EVAL) || defined(FEAT_CRYPT)
&& firstc != '@'
#endif
#ifdef FEAT_EVAL
// do clear got_int in Ex mode to avoid infinite Ctrl-C loop
&& (!break_ctrl_c || exmode_active)
#endif
&& !global_busy)
got_int = FALSE;
// free old command line when finished moving around in the history
// list
if (lookfor != NULL
&& c != K_S_DOWN && c != K_S_UP
&& c != K_DOWN && c != K_UP
&& c != K_PAGEDOWN && c != K_PAGEUP
&& c != K_KPAGEDOWN && c != K_KPAGEUP
&& c != K_LEFT && c != K_RIGHT
&& (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))
VIM_CLEAR(lookfor);
/*
* When there are matching completions to select <S-Tab> works like
* CTRL-P (unless 'wc' is <S-Tab>).
*/
if (c != p_wc && c == K_S_TAB && xpc.xp_numfiles > 0)
c = Ctrl_P;
if (p_wmnu)
c = wildmenu_translate_key(&ccline, c, &xpc, did_wild_list);
if (cmdline_pum_active())
{
// Ctrl-Y: Accept the current selection and close the popup menu.
// Ctrl-E: cancel the cmdline popup menu and return the original
// text.
if (c == Ctrl_E || c == Ctrl_Y)
{
wild_type = (c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY;
if (nextwild(&xpc, wild_type, WILD_NO_BEEP,
firstc != '@') == FAIL)
break;
c = Ctrl_E;
}
}
// The wildmenu is cleared if the pressed key is not used for
// navigating the wild menu (i.e. the key is not 'wildchar' or
// 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L).
// If the popup menu is displayed, then PageDown and PageUp keys are
// also used to navigate the menu.
end_wildmenu = (!(c == p_wc && KeyTyped) && c != p_wcm
&& c != Ctrl_N && c != Ctrl_P && c != Ctrl_A && c != Ctrl_L);
end_wildmenu = end_wildmenu && (!cmdline_pum_active() ||
(c != K_PAGEDOWN && c != K_PAGEUP
&& c != K_KPAGEDOWN && c != K_KPAGEUP));
// free expanded names when finished walking through matches
if (end_wildmenu)
{
if (cmdline_pum_active())
cmdline_pum_remove();
if (xpc.xp_numfiles != -1)
(void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
did_wild_list = FALSE;
if (!p_wmnu || (c != K_UP && c != K_DOWN))
xpc.xp_context = EXPAND_NOTHING;
wim_index = 0;
wildmenu_cleanup(&ccline);
}
if (p_wmnu)
c = wildmenu_process_key(&ccline, c, &xpc);
// CTRL-\ CTRL-N goes to Normal mode, CTRL-\ CTRL-G goes to Insert
// mode when 'insertmode' is set, CTRL-\ e prompts for an expression.
if (c == Ctrl_BSL)
{
res = cmdline_handle_backslash_key(c, &gotesc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
else if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd; // back to cmd mode
c = Ctrl_BSL; // backslash key not processed by
// cmdline_handle_backslash_key()
}
#ifdef FEAT_CMDWIN
if (c == cedit_key || c == K_CMDWIN)
{
// TODO: why is ex_normal_busy checked here?
if ((c == K_CMDWIN || ex_normal_busy == 0) && got_int == FALSE)
{
/*
* Open a window to edit the command line (and history).
*/
c = open_cmdwin();
some_key_typed = TRUE;
}
}
# ifdef FEAT_DIGRAPHS
else
# endif
#endif
#ifdef FEAT_DIGRAPHS
c = do_digraph(c);
#endif
if (c == '\n' || c == '\r' || c == K_KENTER || (c == ESC
&& (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))
{
// In Ex mode a backslash escapes a newline.
if (exmode_active
&& c != ESC
&& ccline.cmdpos == ccline.cmdlen
&& ccline.cmdpos > 0
&& ccline.cmdbuff[ccline.cmdpos - 1] == '\\')
{
if (c == K_KENTER)
c = '\n';
}
else
{
gotesc = FALSE; // Might have typed ESC previously, don't
// truncate the cmdline now.
if (ccheck_abbr(c + ABBR_OFF))
goto cmdline_changed;
if (!cmd_silent)
{
windgoto(msg_row, 0);
out_flush();
}
break;
}
}
// Completion for 'wildchar' or 'wildcharm' key.
if ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)
{
res = cmdline_wildchar_complete(c, firstc != '@', &did_wild_list,
&wim_index, &xpc, &gotesc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
}
gotesc = FALSE;
// <S-Tab> goes to last match, in a clumsy way
if (c == K_S_TAB && KeyTyped)
{
if (nextwild(&xpc, WILD_EXPAND_KEEP, 0, firstc != '@') == OK)
{
if (xpc.xp_numfiles > 1
&& ((!did_wild_list && (wim_flags[wim_index] & WIM_LIST))
|| p_wmnu))
{
// Trigger the popup menu when wildoptions=pum
showmatches(&xpc, p_wmnu
&& ((wim_flags[wim_index] & WIM_LIST) == 0));
}
if (nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK
&& nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK)
goto cmdline_changed;
}
}
if (c == NUL || c == K_ZERO) // NUL is stored as NL
c = NL;
do_abbr = TRUE; // default: check for abbreviation
/*
* Big switch for a typed command line character.
*/
switch (c)
{
case K_BS:
case Ctrl_H:
case K_DEL:
case K_KDEL:
case Ctrl_W:
res = cmdline_erase_chars(c, indent
#ifdef FEAT_SEARCH_EXTRA
, &is_state
#endif
);
if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd; // back to cmd mode
goto cmdline_changed;
case K_INS:
case K_KINS:
ccline.overstrike = !ccline.overstrike;
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
goto cmdline_not_changed;
case Ctrl_HAT:
cmdline_toggle_langmap(b_im_ptr);
goto cmdline_not_changed;
// case '@': only in very old vi
case Ctrl_U:
// delete all characters left of the cursor
j = ccline.cmdpos;
ccline.cmdlen -= j;
i = ccline.cmdpos = 0;
while (i < ccline.cmdlen)
ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
// Truncate at the end, required for multi-byte chars.
ccline.cmdbuff[ccline.cmdlen] = NUL;
#ifdef FEAT_SEARCH_EXTRA
if (ccline.cmdlen == 0)
is_state.search_start = is_state.save_cursor;
#endif
redrawcmd();
goto cmdline_changed;
#ifdef FEAT_CLIPBOARD
case Ctrl_Y:
// Copy the modeless selection, if there is one.
if (clip_star.state != SELECT_CLEARED)
{
if (clip_star.state == SELECT_DONE)
clip_copy_modeless_selection(TRUE);
goto cmdline_not_changed;
}
break;
#endif
case ESC: // get here if p_wc != ESC or when ESC typed twice
case Ctrl_C:
// In exmode it doesn't make sense to return. Except when
// ":normal" runs out of characters.
if (exmode_active
&& (ex_normal_busy == 0 || typebuf.tb_len > 0))
goto cmdline_not_changed;
gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
goto returncmd; // back to cmd mode
case Ctrl_R: // insert register
res = cmdline_insert_reg(&gotesc);
if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd;
goto cmdline_changed;
case Ctrl_D:
if (showmatches(&xpc, FALSE) == EXPAND_NOTHING)
break; // Use ^D as normal char instead
redrawcmd();
continue; // don't do incremental search now
case K_RIGHT:
case K_S_RIGHT:
case K_C_RIGHT:
do
{
if (ccline.cmdpos >= ccline.cmdlen)
break;
i = cmdline_charsize(ccline.cmdpos);
if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)
break;
ccline.cmdspos += i;
if (has_mbyte)
ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
+ ccline.cmdpos);
else
++ccline.cmdpos;
}
while ((c == K_S_RIGHT || c == K_C_RIGHT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos] != ' ');
if (has_mbyte)
set_cmdspos_cursor();
goto cmdline_not_changed;
case K_LEFT:
case K_S_LEFT:
case K_C_LEFT:
if (ccline.cmdpos == 0)
goto cmdline_not_changed;
do
{
--ccline.cmdpos;
if (has_mbyte) // move to first byte of char
ccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,
ccline.cmdbuff + ccline.cmdpos);
ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
}
while (ccline.cmdpos > 0
&& (c == K_S_LEFT || c == K_C_LEFT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos - 1] != ' ');
if (has_mbyte)
set_cmdspos_cursor();
goto cmdline_not_changed;
case K_IGNORE:
// Ignore mouse event or open_cmdwin() result.
goto cmdline_not_changed;
#ifdef FEAT_GUI_MSWIN
// On MS-Windows ignore <M-F4>, we get it when closing the window
// was cancelled.
case K_F4:
if (mod_mask == MOD_MASK_ALT)
{
redrawcmd(); // somehow the cmdline is cleared
goto cmdline_not_changed;
}
break;
#endif
case K_MIDDLEDRAG:
case K_MIDDLERELEASE:
goto cmdline_not_changed; // Ignore mouse
case K_MIDDLEMOUSE:
# ifdef FEAT_GUI
// When GUI is active, also paste when 'mouse' is empty
if (!gui.in_use)
# endif
if (!mouse_has(MOUSE_COMMAND))
goto cmdline_not_changed; // Ignore mouse
# ifdef FEAT_CLIPBOARD
if (clip_star.available)
cmdline_paste('*', TRUE, TRUE);
else
# endif
cmdline_paste(0, TRUE, TRUE);
redrawcmd();
goto cmdline_changed;
# ifdef FEAT_DND
case K_DROP:
cmdline_paste('~', TRUE, FALSE);
redrawcmd();
goto cmdline_changed;
# endif
case K_LEFTDRAG:
case K_LEFTRELEASE:
case K_RIGHTDRAG:
case K_RIGHTRELEASE:
// Ignore drag and release events when the button-down wasn't
// seen before.
if (ignore_drag_release)
goto cmdline_not_changed;
// FALLTHROUGH
case K_LEFTMOUSE:
case K_RIGHTMOUSE:
cmdline_left_right_mouse(c, &ignore_drag_release);
goto cmdline_not_changed;
// Mouse scroll wheel: ignored here
case K_MOUSEDOWN:
case K_MOUSEUP:
case K_MOUSELEFT:
case K_MOUSERIGHT:
// Alternate buttons ignored here
case K_X1MOUSE:
case K_X1DRAG:
case K_X1RELEASE:
case K_X2MOUSE:
case K_X2DRAG:
case K_X2RELEASE:
case K_MOUSEMOVE:
goto cmdline_not_changed;
#ifdef FEAT_GUI
case K_LEFTMOUSE_NM: // mousefocus click, ignored
case K_LEFTRELEASE_NM:
goto cmdline_not_changed;
case K_VER_SCROLLBAR:
if (msg_scrolled == 0)
{
gui_do_scroll();
redrawcmd();
}
goto cmdline_not_changed;
case K_HOR_SCROLLBAR:
if (msg_scrolled == 0)
{
gui_do_horiz_scroll(scrollbar_value, FALSE);
redrawcmd();
}
goto cmdline_not_changed;
#endif
#ifdef FEAT_GUI_TABLINE
case K_TABLINE:
case K_TABMENU:
// Don't want to change any tabs here. Make sure the same tab
// is still selected.
if (gui_use_tabline())
gui_mch_set_curtab(tabpage_index(curtab));
goto cmdline_not_changed;
#endif
case K_SELECT: // end of Select mode mapping - ignore
goto cmdline_not_changed;
case Ctrl_B: // begin of command line
case K_HOME:
case K_KHOME:
case K_S_HOME:
case K_C_HOME:
ccline.cmdpos = 0;
set_cmdspos();
goto cmdline_not_changed;
case Ctrl_E: // end of command line
case K_END:
case K_KEND:
case K_S_END:
case K_C_END:
ccline.cmdpos = ccline.cmdlen;
set_cmdspos_cursor();
goto cmdline_not_changed;
case Ctrl_A: // all matches
if (cmdline_pum_active())
// As Ctrl-A completes all the matches, close the popup
// menu (if present)
cmdline_pum_cleanup(&ccline);
if (nextwild(&xpc, WILD_ALL, 0, firstc != '@') == FAIL)
break;
xpc.xp_context = EXPAND_NOTHING;
did_wild_list = FALSE;
goto cmdline_changed;
case Ctrl_L:
#ifdef FEAT_SEARCH_EXTRA
if (may_add_char_to_search(firstc, &c, &is_state) == OK)
goto cmdline_not_changed;
#endif
// completion: longest common part
if (nextwild(&xpc, WILD_LONGEST, 0, firstc != '@') == FAIL)
break;
goto cmdline_changed;
case Ctrl_N: // next match
case Ctrl_P: // previous match
if (xpc.xp_numfiles > 0)
{
wild_type = (c == Ctrl_P) ? WILD_PREV : WILD_NEXT;
if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)
break;
goto cmdline_not_changed;
}
// FALLTHROUGH
case K_UP:
case K_DOWN:
case K_S_UP:
case K_S_DOWN:
case K_PAGEUP:
case K_KPAGEUP:
case K_PAGEDOWN:
case K_KPAGEDOWN:
if (cmdline_pum_active()
&& (c == K_PAGEUP || c == K_PAGEDOWN ||
c == K_KPAGEUP || c == K_KPAGEDOWN))
{
// If the popup menu is displayed, then PageUp and PageDown
// are used to scroll the menu.
wild_type = WILD_PAGEUP;
if (c == K_PAGEDOWN || c == K_KPAGEDOWN)
wild_type = WILD_PAGEDOWN;
if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)
break;
goto cmdline_not_changed;
}
else
{
res = cmdline_browse_history(c, firstc, &lookfor, histype,
&hiscnt, &xpc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd;
}
goto cmdline_not_changed;
#ifdef FEAT_SEARCH_EXTRA
case Ctrl_G: // next match
case Ctrl_T: // previous match
if (may_adjust_incsearch_highlighting(
firstc, count, &is_state, c) == FAIL)
goto cmdline_not_changed;
break;
#endif
case Ctrl_V:
case Ctrl_Q:
{
ignore_drag_release = TRUE;
putcmdline('^', TRUE);
// Get next (two) character(s). Do not change any
// modifyOtherKeys ESC sequence to a normal key for
// CTRL-SHIFT-V.
c = get_literal(mod_mask & MOD_MASK_SHIFT);
do_abbr = FALSE; // don't do abbreviation now
extra_char = NUL;
// may need to remove ^ when composing char was typed
if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)
{
draw_cmdline(ccline.cmdpos,
ccline.cmdlen - ccline.cmdpos);
msg_putchar(' ');
cursorcmd();
}
}
break;
#ifdef FEAT_DIGRAPHS
case Ctrl_K:
ignore_drag_release = TRUE;
putcmdline('?', TRUE);
# ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; // disallow scrolling here
# endif
c = get_digraph(TRUE);
extra_char = NUL;
if (c != NUL)
break;
redrawcmd();
goto cmdline_not_changed;
#endif // FEAT_DIGRAPHS
#ifdef FEAT_RIGHTLEFT
case Ctrl__: // CTRL-_: switch language mode
if (!p_ari)
break;
cmd_hkmap = !cmd_hkmap;
goto cmdline_not_changed;
#endif
case K_PS:
bracketed_paste(PASTE_CMDLINE, FALSE, NULL);
goto cmdline_changed;
default:
#ifdef UNIX
if (c == intr_char)
{
gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
goto returncmd; // back to Normal mode
}
#endif
/*
* Normal character with no special meaning. Just set mod_mask
* to 0x0 so that typing Shift-Space in the GUI doesn't enter
* the string <S-Space>. This should only happen after ^V.
*/
if (!IS_SPECIAL(c))
mod_mask = 0x0;
break;
}
/*
* End of switch on command line character.
* We come here if we have a normal character.
*/
if (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c))
&& (ccheck_abbr(
// Add ABBR_OFF for characters above 0x100, this is
// what check_abbr() expects.
(has_mbyte && c >= 0x100) ? (c + ABBR_OFF) : c)
|| c == Ctrl_RSB))
goto cmdline_changed;
/*
* put the character in the command line
*/
if (IS_SPECIAL(c) || mod_mask != 0)
put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);
else
{
if (has_mbyte)
{
j = (*mb_char2bytes)(c, IObuff);
IObuff[j] = NUL; // exclude composing chars
put_on_cmdline(IObuff, j, TRUE);
}
else
{
IObuff[0] = c;
put_on_cmdline(IObuff, 1, TRUE);
}
}
goto cmdline_changed;
/*
* This part implements incremental searches for "/" and "?"
* Jump to cmdline_not_changed when a character has been read but the command
* line did not change. Then we only search and redraw if something changed in
* the past.
* Jump to cmdline_changed when the command line did change.
* (Sorry for the goto's, I know it is ugly).
*/
cmdline_not_changed:
#ifdef FEAT_SEARCH_EXTRA
if (!is_state.incsearch_postponed)
continue;
#endif
cmdline_changed:
#ifdef FEAT_SEARCH_EXTRA
// If the window changed incremental search state is not valid.
if (is_state.winid != curwin->w_id)
init_incsearch_state(&is_state);
#endif
if (trigger_cmdlinechanged)
// Trigger CmdlineChanged autocommands.
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINECHANGED);
#ifdef FEAT_SEARCH_EXTRA
if (xpc.xp_context == EXPAND_NOTHING && (KeyTyped || vpeekc() == NUL))
may_do_incsearch_highlighting(firstc, count, &is_state);
#endif
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl
# ifdef FEAT_ARABIC
|| (p_arshape && !p_tbidi
&& cmdline_has_arabic(0, ccline.cmdlen))
# endif
)
// Always redraw the whole command line to fix shaping and
// right-left typing. Not efficient, but it works.
// Do it only when there are no characters left to read
// to avoid useless intermediate redraws.
if (vpeekc() == NUL)
redrawcmd();
#endif
}
returncmd:
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl = FALSE;
#endif
ExpandCleanup(&xpc);
ccline.xpc = NULL;
#ifdef FEAT_SEARCH_EXTRA
finish_incsearch_highlighting(gotesc, &is_state, FALSE);
#endif
if (ccline.cmdbuff != NULL)
{
/*
* Put line in history buffer (":" and "=" only when it was typed).
*/
if (ccline.cmdlen && firstc != NUL
&& (some_key_typed || histype == HIST_SEARCH))
{
add_to_history(histype, ccline.cmdbuff, TRUE,
histype == HIST_SEARCH ? firstc : NUL);
if (firstc == ':')
{
vim_free(new_last_cmdline);
new_last_cmdline = vim_strsave(ccline.cmdbuff);
}
}
if (gotesc)
abandon_cmdline();
}
/*
* If the screen was shifted up, redraw the whole screen (later).
* If the line is too long, clear it, so ruler and shown command do
* not get printed in the middle of it.
*/
msg_check();
msg_scroll = save_msg_scroll;
redir_off = FALSE;
// When the command line was typed, no need for a wait-return prompt.
if (some_key_typed)
need_wait_return = FALSE;
// Trigger CmdlineLeave autocommands.
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINELEAVE);
State = save_State;
#ifdef FEAT_EVAL
if (!debug_mode)
may_trigger_modechanged();
#endif
#ifdef HAVE_INPUT_METHOD
if (b_im_ptr != NULL && *b_im_ptr != B_IMODE_LMAP)
im_save_status(b_im_ptr);
im_set_active(FALSE);
#endif
setmouse();
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
sb_text_end_cmdline();
theend:
{
char_u *p = ccline.cmdbuff;
--depth;
if (did_save_ccline)
restore_cmdline(&save_ccline);
else
ccline.cmdbuff = NULL;
return p;
}
}
|
318420655328659351378249069297989245289
|
ex_getln.c
|
35630205531070235041879855338965504689
|
CWE-416
|
CVE-2022-3235
|
Use After Free in GitHub repository vim/vim prior to 9.0.0490.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-3235
|
416,366
|
vim
|
1c3dd8ddcba63c1af5112e567215b3cec2de11d0
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/1c3dd8ddcba63c1af5112e567215b3cec2de11d0
|
patch 9.0.0490: using freed memory with cmdwin and BufEnter autocmd
Problem: Using freed memory with cmdwin and BufEnter autocmd.
Solution: Make sure pointer to b_p_iminsert is still valid.
| 0
|
getcmdline_int(
int firstc,
long count UNUSED, // only used for incremental search
int indent, // indent for inside conditionals
int clear_ccline) // clear ccline first
{
static int depth = 0; // call depth
int c;
int i;
int j;
int gotesc = FALSE; // TRUE when <ESC> just typed
int do_abbr; // when TRUE check for abbr.
char_u *lookfor = NULL; // string to match
int hiscnt; // current history line in use
int histype; // history type to be used
#ifdef FEAT_SEARCH_EXTRA
incsearch_state_T is_state;
#endif
int did_wild_list = FALSE; // did wild_list() recently
int wim_index = 0; // index in wim_flags[]
int res;
int save_msg_scroll = msg_scroll;
int save_State = State; // remember State when called
int some_key_typed = FALSE; // one of the keys was typed
// mouse drag and release events are ignored, unless they are
// preceded with a mouse down event
int ignore_drag_release = TRUE;
#ifdef FEAT_EVAL
int break_ctrl_c = FALSE;
#endif
expand_T xpc;
long *b_im_ptr = NULL;
buf_T *b_im_ptr_buf = NULL; // buffer where b_im_ptr is valid
cmdline_info_T save_ccline;
int did_save_ccline = FALSE;
int cmdline_type;
int wild_type;
// one recursion level deeper
++depth;
if (ccline.cmdbuff != NULL)
{
// Being called recursively. Since ccline is global, we need to save
// the current buffer and restore it when returning.
save_cmdline(&save_ccline);
did_save_ccline = TRUE;
}
if (clear_ccline)
CLEAR_FIELD(ccline);
#ifdef FEAT_EVAL
if (firstc == -1)
{
firstc = NUL;
break_ctrl_c = TRUE;
}
#endif
#ifdef FEAT_RIGHTLEFT
// start without Hebrew mapping for a command line
if (firstc == ':' || firstc == '=' || firstc == '>')
cmd_hkmap = 0;
#endif
#ifdef FEAT_SEARCH_EXTRA
init_incsearch_state(&is_state);
#endif
if (init_ccline(firstc, indent) != OK)
goto theend; // out of memory
if (depth == 50)
{
// Somehow got into a loop recursively calling getcmdline(), bail out.
emsg(_(e_command_too_recursive));
goto theend;
}
ExpandInit(&xpc);
ccline.xpc = &xpc;
#ifdef FEAT_RIGHTLEFT
if (curwin->w_p_rl && *curwin->w_p_rlc == 's'
&& (firstc == '/' || firstc == '?'))
cmdmsg_rl = TRUE;
else
cmdmsg_rl = FALSE;
#endif
redir_off = TRUE; // don't redirect the typed command
if (!cmd_silent)
{
i = msg_scrolled;
msg_scrolled = 0; // avoid wait_return() message
gotocmdline(TRUE);
msg_scrolled += i;
redrawcmdprompt(); // draw prompt or indent
set_cmdspos();
}
xpc.xp_context = EXPAND_NOTHING;
xpc.xp_backslash = XP_BS_NONE;
#ifndef BACKSLASH_IN_FILENAME
xpc.xp_shell = FALSE;
#endif
#if defined(FEAT_EVAL)
if (ccline.input_fn)
{
xpc.xp_context = ccline.xp_context;
xpc.xp_pattern = ccline.cmdbuff;
xpc.xp_arg = ccline.xp_arg;
}
#endif
/*
* Avoid scrolling when called by a recursive do_cmdline(), e.g. when
* doing ":@0" when register 0 doesn't contain a CR.
*/
msg_scroll = FALSE;
State = MODE_CMDLINE;
if (firstc == '/' || firstc == '?' || firstc == '@')
{
// Use ":lmap" mappings for search pattern and input().
if (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)
b_im_ptr = &curbuf->b_p_iminsert;
else
b_im_ptr = &curbuf->b_p_imsearch;
b_im_ptr_buf = curbuf;
if (*b_im_ptr == B_IMODE_LMAP)
State |= MODE_LANGMAP;
#ifdef HAVE_INPUT_METHOD
im_set_active(*b_im_ptr == B_IMODE_IM);
#endif
}
#ifdef HAVE_INPUT_METHOD
else if (p_imcmdline)
im_set_active(TRUE);
#endif
setmouse();
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
// When inside an autocommand for writing "exiting" may be set and
// terminal mode set to cooked. Need to set raw mode here then.
settmode(TMODE_RAW);
// Trigger CmdlineEnter autocommands.
cmdline_type = firstc == NUL ? '-' : firstc;
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINEENTER);
#ifdef FEAT_EVAL
if (!debug_mode)
may_trigger_modechanged();
#endif
init_history();
hiscnt = get_hislen(); // set hiscnt to impossible history value
histype = hist_char2type(firstc);
#ifdef FEAT_DIGRAPHS
do_digraph(-1); // init digraph typeahead
#endif
// If something above caused an error, reset the flags, we do want to type
// and execute commands. Display may be messed up a bit.
if (did_emsg)
redrawcmd();
#ifdef FEAT_STL_OPT
// Redraw the statusline in case it uses the current mode using the mode()
// function.
if (!cmd_silent && msg_scrolled == 0)
{
int found_one = FALSE;
win_T *wp;
FOR_ALL_WINDOWS(wp)
if (*p_stl != NUL || *wp->w_p_stl != NUL)
{
wp->w_redr_status = TRUE;
found_one = TRUE;
}
if (*p_tal != NUL)
{
redraw_tabline = TRUE;
found_one = TRUE;
}
if (found_one)
redraw_statuslines();
}
#endif
did_emsg = FALSE;
got_int = FALSE;
/*
* Collect the command string, handling editing keys.
*/
for (;;)
{
int trigger_cmdlinechanged = TRUE;
int end_wildmenu;
redir_off = TRUE; // Don't redirect the typed command.
// Repeated, because a ":redir" inside
// completion may switch it on.
#ifdef USE_ON_FLY_SCROLL
dont_scroll = FALSE; // allow scrolling here
#endif
quit_more = FALSE; // reset after CTRL-D which had a more-prompt
did_emsg = FALSE; // There can't really be a reason why an error
// that occurs while typing a command should
// cause the command not to be executed.
// Trigger SafeState if nothing is pending.
may_trigger_safestate(xpc.xp_numfiles <= 0);
// Get a character. Ignore K_IGNORE and K_NOP, they should not do
// anything, such as stop completion.
do
{
cursorcmd(); // set the cursor on the right spot
c = safe_vgetc();
} while (c == K_IGNORE || c == K_NOP);
if (c == K_COMMAND || c == K_SCRIPT_COMMAND)
{
int clen = ccline.cmdlen;
if (do_cmdkey_command(c, DOCMD_NOWAIT) == OK)
{
if (clen == ccline.cmdlen)
trigger_cmdlinechanged = FALSE;
goto cmdline_changed;
}
}
if (KeyTyped)
{
some_key_typed = TRUE;
#ifdef FEAT_RIGHTLEFT
if (cmd_hkmap)
c = hkmap(c);
if (cmdmsg_rl && !KeyStuffed)
{
// Invert horizontal movements and operations. Only when
// typed by the user directly, not when the result of a
// mapping.
switch (c)
{
case K_RIGHT: c = K_LEFT; break;
case K_S_RIGHT: c = K_S_LEFT; break;
case K_C_RIGHT: c = K_C_LEFT; break;
case K_LEFT: c = K_RIGHT; break;
case K_S_LEFT: c = K_S_RIGHT; break;
case K_C_LEFT: c = K_C_RIGHT; break;
}
}
#endif
}
/*
* Ignore got_int when CTRL-C was typed here.
* Don't ignore it in :global, we really need to break then, e.g., for
* ":g/pat/normal /pat" (without the <CR>).
* Don't ignore it for the input() function.
*/
if ((c == Ctrl_C
#ifdef UNIX
|| c == intr_char
#endif
)
#if defined(FEAT_EVAL) || defined(FEAT_CRYPT)
&& firstc != '@'
#endif
#ifdef FEAT_EVAL
// do clear got_int in Ex mode to avoid infinite Ctrl-C loop
&& (!break_ctrl_c || exmode_active)
#endif
&& !global_busy)
got_int = FALSE;
// free old command line when finished moving around in the history
// list
if (lookfor != NULL
&& c != K_S_DOWN && c != K_S_UP
&& c != K_DOWN && c != K_UP
&& c != K_PAGEDOWN && c != K_PAGEUP
&& c != K_KPAGEDOWN && c != K_KPAGEUP
&& c != K_LEFT && c != K_RIGHT
&& (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))
VIM_CLEAR(lookfor);
/*
* When there are matching completions to select <S-Tab> works like
* CTRL-P (unless 'wc' is <S-Tab>).
*/
if (c != p_wc && c == K_S_TAB && xpc.xp_numfiles > 0)
c = Ctrl_P;
if (p_wmnu)
c = wildmenu_translate_key(&ccline, c, &xpc, did_wild_list);
if (cmdline_pum_active())
{
// Ctrl-Y: Accept the current selection and close the popup menu.
// Ctrl-E: cancel the cmdline popup menu and return the original
// text.
if (c == Ctrl_E || c == Ctrl_Y)
{
wild_type = (c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY;
if (nextwild(&xpc, wild_type, WILD_NO_BEEP,
firstc != '@') == FAIL)
break;
c = Ctrl_E;
}
}
// The wildmenu is cleared if the pressed key is not used for
// navigating the wild menu (i.e. the key is not 'wildchar' or
// 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L).
// If the popup menu is displayed, then PageDown and PageUp keys are
// also used to navigate the menu.
end_wildmenu = (!(c == p_wc && KeyTyped) && c != p_wcm
&& c != Ctrl_N && c != Ctrl_P && c != Ctrl_A && c != Ctrl_L);
end_wildmenu = end_wildmenu && (!cmdline_pum_active() ||
(c != K_PAGEDOWN && c != K_PAGEUP
&& c != K_KPAGEDOWN && c != K_KPAGEUP));
// free expanded names when finished walking through matches
if (end_wildmenu)
{
if (cmdline_pum_active())
cmdline_pum_remove();
if (xpc.xp_numfiles != -1)
(void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
did_wild_list = FALSE;
if (!p_wmnu || (c != K_UP && c != K_DOWN))
xpc.xp_context = EXPAND_NOTHING;
wim_index = 0;
wildmenu_cleanup(&ccline);
}
if (p_wmnu)
c = wildmenu_process_key(&ccline, c, &xpc);
// CTRL-\ CTRL-N goes to Normal mode, CTRL-\ CTRL-G goes to Insert
// mode when 'insertmode' is set, CTRL-\ e prompts for an expression.
if (c == Ctrl_BSL)
{
res = cmdline_handle_backslash_key(c, &gotesc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
else if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd; // back to cmd mode
c = Ctrl_BSL; // backslash key not processed by
// cmdline_handle_backslash_key()
}
#ifdef FEAT_CMDWIN
if (c == cedit_key || c == K_CMDWIN)
{
// TODO: why is ex_normal_busy checked here?
if ((c == K_CMDWIN || ex_normal_busy == 0) && got_int == FALSE)
{
/*
* Open a window to edit the command line (and history).
*/
c = open_cmdwin();
some_key_typed = TRUE;
}
}
# ifdef FEAT_DIGRAPHS
else
# endif
#endif
#ifdef FEAT_DIGRAPHS
c = do_digraph(c);
#endif
if (c == '\n' || c == '\r' || c == K_KENTER || (c == ESC
&& (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))
{
// In Ex mode a backslash escapes a newline.
if (exmode_active
&& c != ESC
&& ccline.cmdpos == ccline.cmdlen
&& ccline.cmdpos > 0
&& ccline.cmdbuff[ccline.cmdpos - 1] == '\\')
{
if (c == K_KENTER)
c = '\n';
}
else
{
gotesc = FALSE; // Might have typed ESC previously, don't
// truncate the cmdline now.
if (ccheck_abbr(c + ABBR_OFF))
goto cmdline_changed;
if (!cmd_silent)
{
windgoto(msg_row, 0);
out_flush();
}
break;
}
}
// Completion for 'wildchar' or 'wildcharm' key.
if ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)
{
res = cmdline_wildchar_complete(c, firstc != '@', &did_wild_list,
&wim_index, &xpc, &gotesc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
}
gotesc = FALSE;
// <S-Tab> goes to last match, in a clumsy way
if (c == K_S_TAB && KeyTyped)
{
if (nextwild(&xpc, WILD_EXPAND_KEEP, 0, firstc != '@') == OK)
{
if (xpc.xp_numfiles > 1
&& ((!did_wild_list && (wim_flags[wim_index] & WIM_LIST))
|| p_wmnu))
{
// Trigger the popup menu when wildoptions=pum
showmatches(&xpc, p_wmnu
&& ((wim_flags[wim_index] & WIM_LIST) == 0));
}
if (nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK
&& nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK)
goto cmdline_changed;
}
}
if (c == NUL || c == K_ZERO) // NUL is stored as NL
c = NL;
do_abbr = TRUE; // default: check for abbreviation
/*
* Big switch for a typed command line character.
*/
switch (c)
{
case K_BS:
case Ctrl_H:
case K_DEL:
case K_KDEL:
case Ctrl_W:
res = cmdline_erase_chars(c, indent
#ifdef FEAT_SEARCH_EXTRA
, &is_state
#endif
);
if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd; // back to cmd mode
goto cmdline_changed;
case K_INS:
case K_KINS:
ccline.overstrike = !ccline.overstrike;
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
goto cmdline_not_changed;
case Ctrl_HAT:
cmdline_toggle_langmap(
buf_valid(b_im_ptr_buf) ? b_im_ptr : NULL);
goto cmdline_not_changed;
// case '@': only in very old vi
case Ctrl_U:
// delete all characters left of the cursor
j = ccline.cmdpos;
ccline.cmdlen -= j;
i = ccline.cmdpos = 0;
while (i < ccline.cmdlen)
ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
// Truncate at the end, required for multi-byte chars.
ccline.cmdbuff[ccline.cmdlen] = NUL;
#ifdef FEAT_SEARCH_EXTRA
if (ccline.cmdlen == 0)
is_state.search_start = is_state.save_cursor;
#endif
redrawcmd();
goto cmdline_changed;
#ifdef FEAT_CLIPBOARD
case Ctrl_Y:
// Copy the modeless selection, if there is one.
if (clip_star.state != SELECT_CLEARED)
{
if (clip_star.state == SELECT_DONE)
clip_copy_modeless_selection(TRUE);
goto cmdline_not_changed;
}
break;
#endif
case ESC: // get here if p_wc != ESC or when ESC typed twice
case Ctrl_C:
// In exmode it doesn't make sense to return. Except when
// ":normal" runs out of characters.
if (exmode_active
&& (ex_normal_busy == 0 || typebuf.tb_len > 0))
goto cmdline_not_changed;
gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
goto returncmd; // back to cmd mode
case Ctrl_R: // insert register
res = cmdline_insert_reg(&gotesc);
if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd;
goto cmdline_changed;
case Ctrl_D:
if (showmatches(&xpc, FALSE) == EXPAND_NOTHING)
break; // Use ^D as normal char instead
redrawcmd();
continue; // don't do incremental search now
case K_RIGHT:
case K_S_RIGHT:
case K_C_RIGHT:
do
{
if (ccline.cmdpos >= ccline.cmdlen)
break;
i = cmdline_charsize(ccline.cmdpos);
if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)
break;
ccline.cmdspos += i;
if (has_mbyte)
ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
+ ccline.cmdpos);
else
++ccline.cmdpos;
}
while ((c == K_S_RIGHT || c == K_C_RIGHT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos] != ' ');
if (has_mbyte)
set_cmdspos_cursor();
goto cmdline_not_changed;
case K_LEFT:
case K_S_LEFT:
case K_C_LEFT:
if (ccline.cmdpos == 0)
goto cmdline_not_changed;
do
{
--ccline.cmdpos;
if (has_mbyte) // move to first byte of char
ccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,
ccline.cmdbuff + ccline.cmdpos);
ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
}
while (ccline.cmdpos > 0
&& (c == K_S_LEFT || c == K_C_LEFT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos - 1] != ' ');
if (has_mbyte)
set_cmdspos_cursor();
goto cmdline_not_changed;
case K_IGNORE:
// Ignore mouse event or open_cmdwin() result.
goto cmdline_not_changed;
#ifdef FEAT_GUI_MSWIN
// On MS-Windows ignore <M-F4>, we get it when closing the window
// was cancelled.
case K_F4:
if (mod_mask == MOD_MASK_ALT)
{
redrawcmd(); // somehow the cmdline is cleared
goto cmdline_not_changed;
}
break;
#endif
case K_MIDDLEDRAG:
case K_MIDDLERELEASE:
goto cmdline_not_changed; // Ignore mouse
case K_MIDDLEMOUSE:
# ifdef FEAT_GUI
// When GUI is active, also paste when 'mouse' is empty
if (!gui.in_use)
# endif
if (!mouse_has(MOUSE_COMMAND))
goto cmdline_not_changed; // Ignore mouse
# ifdef FEAT_CLIPBOARD
if (clip_star.available)
cmdline_paste('*', TRUE, TRUE);
else
# endif
cmdline_paste(0, TRUE, TRUE);
redrawcmd();
goto cmdline_changed;
# ifdef FEAT_DND
case K_DROP:
cmdline_paste('~', TRUE, FALSE);
redrawcmd();
goto cmdline_changed;
# endif
case K_LEFTDRAG:
case K_LEFTRELEASE:
case K_RIGHTDRAG:
case K_RIGHTRELEASE:
// Ignore drag and release events when the button-down wasn't
// seen before.
if (ignore_drag_release)
goto cmdline_not_changed;
// FALLTHROUGH
case K_LEFTMOUSE:
case K_RIGHTMOUSE:
cmdline_left_right_mouse(c, &ignore_drag_release);
goto cmdline_not_changed;
// Mouse scroll wheel: ignored here
case K_MOUSEDOWN:
case K_MOUSEUP:
case K_MOUSELEFT:
case K_MOUSERIGHT:
// Alternate buttons ignored here
case K_X1MOUSE:
case K_X1DRAG:
case K_X1RELEASE:
case K_X2MOUSE:
case K_X2DRAG:
case K_X2RELEASE:
case K_MOUSEMOVE:
goto cmdline_not_changed;
#ifdef FEAT_GUI
case K_LEFTMOUSE_NM: // mousefocus click, ignored
case K_LEFTRELEASE_NM:
goto cmdline_not_changed;
case K_VER_SCROLLBAR:
if (msg_scrolled == 0)
{
gui_do_scroll();
redrawcmd();
}
goto cmdline_not_changed;
case K_HOR_SCROLLBAR:
if (msg_scrolled == 0)
{
gui_do_horiz_scroll(scrollbar_value, FALSE);
redrawcmd();
}
goto cmdline_not_changed;
#endif
#ifdef FEAT_GUI_TABLINE
case K_TABLINE:
case K_TABMENU:
// Don't want to change any tabs here. Make sure the same tab
// is still selected.
if (gui_use_tabline())
gui_mch_set_curtab(tabpage_index(curtab));
goto cmdline_not_changed;
#endif
case K_SELECT: // end of Select mode mapping - ignore
goto cmdline_not_changed;
case Ctrl_B: // begin of command line
case K_HOME:
case K_KHOME:
case K_S_HOME:
case K_C_HOME:
ccline.cmdpos = 0;
set_cmdspos();
goto cmdline_not_changed;
case Ctrl_E: // end of command line
case K_END:
case K_KEND:
case K_S_END:
case K_C_END:
ccline.cmdpos = ccline.cmdlen;
set_cmdspos_cursor();
goto cmdline_not_changed;
case Ctrl_A: // all matches
if (cmdline_pum_active())
// As Ctrl-A completes all the matches, close the popup
// menu (if present)
cmdline_pum_cleanup(&ccline);
if (nextwild(&xpc, WILD_ALL, 0, firstc != '@') == FAIL)
break;
xpc.xp_context = EXPAND_NOTHING;
did_wild_list = FALSE;
goto cmdline_changed;
case Ctrl_L:
#ifdef FEAT_SEARCH_EXTRA
if (may_add_char_to_search(firstc, &c, &is_state) == OK)
goto cmdline_not_changed;
#endif
// completion: longest common part
if (nextwild(&xpc, WILD_LONGEST, 0, firstc != '@') == FAIL)
break;
goto cmdline_changed;
case Ctrl_N: // next match
case Ctrl_P: // previous match
if (xpc.xp_numfiles > 0)
{
wild_type = (c == Ctrl_P) ? WILD_PREV : WILD_NEXT;
if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)
break;
goto cmdline_not_changed;
}
// FALLTHROUGH
case K_UP:
case K_DOWN:
case K_S_UP:
case K_S_DOWN:
case K_PAGEUP:
case K_KPAGEUP:
case K_PAGEDOWN:
case K_KPAGEDOWN:
if (cmdline_pum_active()
&& (c == K_PAGEUP || c == K_PAGEDOWN ||
c == K_KPAGEUP || c == K_KPAGEDOWN))
{
// If the popup menu is displayed, then PageUp and PageDown
// are used to scroll the menu.
wild_type = WILD_PAGEUP;
if (c == K_PAGEDOWN || c == K_KPAGEDOWN)
wild_type = WILD_PAGEDOWN;
if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)
break;
goto cmdline_not_changed;
}
else
{
res = cmdline_browse_history(c, firstc, &lookfor, histype,
&hiscnt, &xpc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd;
}
goto cmdline_not_changed;
#ifdef FEAT_SEARCH_EXTRA
case Ctrl_G: // next match
case Ctrl_T: // previous match
if (may_adjust_incsearch_highlighting(
firstc, count, &is_state, c) == FAIL)
goto cmdline_not_changed;
break;
#endif
case Ctrl_V:
case Ctrl_Q:
{
ignore_drag_release = TRUE;
putcmdline('^', TRUE);
// Get next (two) character(s). Do not change any
// modifyOtherKeys ESC sequence to a normal key for
// CTRL-SHIFT-V.
c = get_literal(mod_mask & MOD_MASK_SHIFT);
do_abbr = FALSE; // don't do abbreviation now
extra_char = NUL;
// may need to remove ^ when composing char was typed
if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)
{
draw_cmdline(ccline.cmdpos,
ccline.cmdlen - ccline.cmdpos);
msg_putchar(' ');
cursorcmd();
}
}
break;
#ifdef FEAT_DIGRAPHS
case Ctrl_K:
ignore_drag_release = TRUE;
putcmdline('?', TRUE);
# ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; // disallow scrolling here
# endif
c = get_digraph(TRUE);
extra_char = NUL;
if (c != NUL)
break;
redrawcmd();
goto cmdline_not_changed;
#endif // FEAT_DIGRAPHS
#ifdef FEAT_RIGHTLEFT
case Ctrl__: // CTRL-_: switch language mode
if (!p_ari)
break;
cmd_hkmap = !cmd_hkmap;
goto cmdline_not_changed;
#endif
case K_PS:
bracketed_paste(PASTE_CMDLINE, FALSE, NULL);
goto cmdline_changed;
default:
#ifdef UNIX
if (c == intr_char)
{
gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
goto returncmd; // back to Normal mode
}
#endif
/*
* Normal character with no special meaning. Just set mod_mask
* to 0x0 so that typing Shift-Space in the GUI doesn't enter
* the string <S-Space>. This should only happen after ^V.
*/
if (!IS_SPECIAL(c))
mod_mask = 0x0;
break;
}
/*
* End of switch on command line character.
* We come here if we have a normal character.
*/
if (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c))
&& (ccheck_abbr(
// Add ABBR_OFF for characters above 0x100, this is
// what check_abbr() expects.
(has_mbyte && c >= 0x100) ? (c + ABBR_OFF) : c)
|| c == Ctrl_RSB))
goto cmdline_changed;
/*
* put the character in the command line
*/
if (IS_SPECIAL(c) || mod_mask != 0)
put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);
else
{
if (has_mbyte)
{
j = (*mb_char2bytes)(c, IObuff);
IObuff[j] = NUL; // exclude composing chars
put_on_cmdline(IObuff, j, TRUE);
}
else
{
IObuff[0] = c;
put_on_cmdline(IObuff, 1, TRUE);
}
}
goto cmdline_changed;
/*
* This part implements incremental searches for "/" and "?"
* Jump to cmdline_not_changed when a character has been read but the command
* line did not change. Then we only search and redraw if something changed in
* the past.
* Jump to cmdline_changed when the command line did change.
* (Sorry for the goto's, I know it is ugly).
*/
cmdline_not_changed:
#ifdef FEAT_SEARCH_EXTRA
if (!is_state.incsearch_postponed)
continue;
#endif
cmdline_changed:
#ifdef FEAT_SEARCH_EXTRA
// If the window changed incremental search state is not valid.
if (is_state.winid != curwin->w_id)
init_incsearch_state(&is_state);
#endif
if (trigger_cmdlinechanged)
// Trigger CmdlineChanged autocommands.
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINECHANGED);
#ifdef FEAT_SEARCH_EXTRA
if (xpc.xp_context == EXPAND_NOTHING && (KeyTyped || vpeekc() == NUL))
may_do_incsearch_highlighting(firstc, count, &is_state);
#endif
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl
# ifdef FEAT_ARABIC
|| (p_arshape && !p_tbidi
&& cmdline_has_arabic(0, ccline.cmdlen))
# endif
)
// Always redraw the whole command line to fix shaping and
// right-left typing. Not efficient, but it works.
// Do it only when there are no characters left to read
// to avoid useless intermediate redraws.
if (vpeekc() == NUL)
redrawcmd();
#endif
}
returncmd:
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl = FALSE;
#endif
ExpandCleanup(&xpc);
ccline.xpc = NULL;
#ifdef FEAT_SEARCH_EXTRA
finish_incsearch_highlighting(gotesc, &is_state, FALSE);
#endif
if (ccline.cmdbuff != NULL)
{
/*
* Put line in history buffer (":" and "=" only when it was typed).
*/
if (ccline.cmdlen && firstc != NUL
&& (some_key_typed || histype == HIST_SEARCH))
{
add_to_history(histype, ccline.cmdbuff, TRUE,
histype == HIST_SEARCH ? firstc : NUL);
if (firstc == ':')
{
vim_free(new_last_cmdline);
new_last_cmdline = vim_strsave(ccline.cmdbuff);
}
}
if (gotesc)
abandon_cmdline();
}
/*
* If the screen was shifted up, redraw the whole screen (later).
* If the line is too long, clear it, so ruler and shown command do
* not get printed in the middle of it.
*/
msg_check();
msg_scroll = save_msg_scroll;
redir_off = FALSE;
// When the command line was typed, no need for a wait-return prompt.
if (some_key_typed)
need_wait_return = FALSE;
// Trigger CmdlineLeave autocommands.
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINELEAVE);
State = save_State;
#ifdef FEAT_EVAL
if (!debug_mode)
may_trigger_modechanged();
#endif
#ifdef HAVE_INPUT_METHOD
if (b_im_ptr != NULL && buf_valid(b_im_ptr_buf)
&& *b_im_ptr != B_IMODE_LMAP)
im_save_status(b_im_ptr);
im_set_active(FALSE);
#endif
setmouse();
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
sb_text_end_cmdline();
theend:
{
char_u *p = ccline.cmdbuff;
--depth;
if (did_save_ccline)
restore_cmdline(&save_ccline);
else
ccline.cmdbuff = NULL;
return p;
}
}
|
287277157755538522084742430465983420799
|
ex_getln.c
|
200105240926561396065075027208565202210
|
CWE-416
|
CVE-2022-3235
|
Use After Free in GitHub repository vim/vim prior to 9.0.0490.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-3235
|
208,987
|
MilkyTracker
|
7afd55c42ad80d01a339197a2d8b5461d214edaf
|
https://github.com/milkytracker/MilkyTracker
|
https://github.com/milkytracker/MilkyTracker/commit/7afd55c42ad80d01a339197a2d8b5461d214edaf
|
Fix use-after-free in PlayerGeneric destructor
| 1
|
PlayerGeneric::~PlayerGeneric()
{
if (mixer)
delete mixer;
if (player)
{
if (mixer->isActive() && !mixer->isDeviceRemoved(player))
mixer->removeDevice(player);
delete player;
}
delete[] audioDriverName;
delete listener;
}
|
259737108889128783455987997759442352236
|
PlayerGeneric.cpp
|
257439638235883999405270646373445692221
|
CWE-416
|
CVE-2020-15569
|
PlayerGeneric.cpp in MilkyTracker through 1.02.00 has a use-after-free in the PlayerGeneric destructor.
|
https://nvd.nist.gov/vuln/detail/CVE-2020-15569
|
417,093
|
MilkyTracker
|
7afd55c42ad80d01a339197a2d8b5461d214edaf
|
https://github.com/milkytracker/MilkyTracker
|
https://github.com/milkytracker/MilkyTracker/commit/7afd55c42ad80d01a339197a2d8b5461d214edaf
|
Fix use-after-free in PlayerGeneric destructor
| 0
|
PlayerGeneric::~PlayerGeneric()
{
if (player)
{
if (mixer && mixer->isActive() && !mixer->isDeviceRemoved(player))
mixer->removeDevice(player);
delete player;
}
if (mixer)
delete mixer;
delete[] audioDriverName;
delete listener;
}
|
322349041921925160891638302386197132402
|
PlayerGeneric.cpp
|
114108410020377773864246355219706856245
|
CWE-416
|
CVE-2020-15569
|
PlayerGeneric.cpp in MilkyTracker through 1.02.00 has a use-after-free in the PlayerGeneric destructor.
|
https://nvd.nist.gov/vuln/detail/CVE-2020-15569
|
209,026
|
libvirt
|
4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a
|
https://github.com/libvirt/libvirt
|
https://gitlab.com/libvirt/libvirt/-/commit/4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a
|
conf: Fix segfault when parsing mdev types
Commit f1b0890 introduced a potential crash due to incorrect operator
precedence when accessing an element from a pointer to an array.
Backtrace below:
#0 virNodeDeviceGetMdevTypesCaps (sysfspath=0x7fff801661e0 "/sys/devices/pci0000:00/0000:00:02.0", mdev_types=0x7fff801c9b40, nmdev_types=0x7fff801c9b48) at ../src/conf/node_device_conf.c:2676
#1 0x00007ffff7caf53d in virNodeDeviceGetPCIDynamicCaps (sysfsPath=0x7fff801661e0 "/sys/devices/pci0000:00/0000:00:02.0", pci_dev=0x7fff801c9ac8) at ../src/conf/node_device_conf.c:2705
#2 0x00007ffff7cae38f in virNodeDeviceUpdateCaps (def=0x7fff80168a10) at ../src/conf/node_device_conf.c:2342
#3 0x00007ffff7cb11c0 in virNodeDeviceObjMatch (obj=0x7fff84002e50, flags=0) at ../src/conf/virnodedeviceobj.c:850
#4 0x00007ffff7cb153d in virNodeDeviceObjListExportCallback (payload=0x7fff84002e50, name=0x7fff801cbc20 "pci_0000_00_02_0", opaque=0x7fffe2ffc6a0) at ../src/conf/virnodedeviceobj.c:909
#5 0x00007ffff7b69146 in virHashForEach (table=0x7fff9814b700 = {...}, iter=0x7ffff7cb149e <virNodeDeviceObjListExportCallback>, opaque=0x7fffe2ffc6a0) at ../src/util/virhash.c:394
#6 0x00007ffff7cb1694 in virNodeDeviceObjListExport (conn=0x7fff98013170, devs=0x7fff98154430, devices=0x7fffe2ffc798, filter=0x7ffff7cf47a1 <virConnectListAllNodeDevicesCheckACL>, flags=0)
at ../src/conf/virnodedeviceobj.c:943
#7 0x00007fffe00694b2 in nodeConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/node_device/node_device_driver.c:228
#8 0x00007ffff7e703aa in virConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/libvirt-nodedev.c:130
#9 0x000055555557f796 in remoteDispatchConnectListAllNodeDevices (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)
at src/remote/remote_daemon_dispatch_stubs.h:1613
#10 0x000055555557f6f9 in remoteDispatchConnectListAllNodeDevicesHelper (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)
at src/remote/remote_daemon_dispatch_stubs.h:1591
#11 0x00007ffff7ce9542 in virNetServerProgramDispatchCall (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:428
#12 0x00007ffff7ce90bd in virNetServerProgramDispatch (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:302
#13 0x00007ffff7cf042b in virNetServerProcessMsg (srv=0x555555627080, client=0x5555556bf050, prog=0x555555690c10, msg=0x5555556c0000) at ../src/rpc/virnetserver.c:137
#14 0x00007ffff7cf04eb in virNetServerHandleJob (jobOpaque=0x5555556b66b0, opaque=0x555555627080) at ../src/rpc/virnetserver.c:154
#15 0x00007ffff7bd912f in virThreadPoolWorker (opaque=0x55555562bc70) at ../src/util/virthreadpool.c:163
#16 0x00007ffff7bd8645 in virThreadHelper (data=0x55555562bc90) at ../src/util/virthread.c:233
#17 0x00007ffff6d90432 in start_thread () at /lib64/libpthread.so.0
#18 0x00007ffff75c5913 in clone () at /lib64/libc.so.6
Signed-off-by: Jonathon Jongsma <[email protected]>
Reviewed-by: Ján Tomko <[email protected]>
Signed-off-by: Ján Tomko <[email protected]>
| 1
|
virNodeDeviceGetMdevTypesCaps(const char *sysfspath,
virMediatedDeviceTypePtr **mdev_types,
size_t *nmdev_types)
{
virMediatedDeviceTypePtr *types = NULL;
size_t ntypes = 0;
size_t i;
/* this could be a refresh, so clear out the old data */
for (i = 0; i < *nmdev_types; i++)
virMediatedDeviceTypeFree(*mdev_types[i]);
VIR_FREE(*mdev_types);
*nmdev_types = 0;
if (virMediatedDeviceGetMdevTypes(sysfspath, &types, &ntypes) < 0)
return -1;
*mdev_types = g_steal_pointer(&types);
*nmdev_types = ntypes;
return 0;
}
|
87286221830836043224209896676991521270
|
node_device_conf.c
|
38019949320953450079385512587806047567
|
CWE-119
|
CVE-2021-3559
|
A flaw was found in libvirt in the virConnectListAllNodeDevices API in versions before 7.0.0. It only affects hosts with a PCI device and driver that supports mediated devices (e.g., GRID driver). This flaw could be used by an unprivileged client with a read-only connection to crash the libvirt daemon by executing the 'nodedev-list' virsh command. The highest threat from this vulnerability is to system availability.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-3559
|
417,472
|
libvirt
|
4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a
|
https://github.com/libvirt/libvirt
|
https://gitlab.com/libvirt/libvirt/-/commit/4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a
|
conf: Fix segfault when parsing mdev types
Commit f1b0890 introduced a potential crash due to incorrect operator
precedence when accessing an element from a pointer to an array.
Backtrace below:
#0 virNodeDeviceGetMdevTypesCaps (sysfspath=0x7fff801661e0 "/sys/devices/pci0000:00/0000:00:02.0", mdev_types=0x7fff801c9b40, nmdev_types=0x7fff801c9b48) at ../src/conf/node_device_conf.c:2676
#1 0x00007ffff7caf53d in virNodeDeviceGetPCIDynamicCaps (sysfsPath=0x7fff801661e0 "/sys/devices/pci0000:00/0000:00:02.0", pci_dev=0x7fff801c9ac8) at ../src/conf/node_device_conf.c:2705
#2 0x00007ffff7cae38f in virNodeDeviceUpdateCaps (def=0x7fff80168a10) at ../src/conf/node_device_conf.c:2342
#3 0x00007ffff7cb11c0 in virNodeDeviceObjMatch (obj=0x7fff84002e50, flags=0) at ../src/conf/virnodedeviceobj.c:850
#4 0x00007ffff7cb153d in virNodeDeviceObjListExportCallback (payload=0x7fff84002e50, name=0x7fff801cbc20 "pci_0000_00_02_0", opaque=0x7fffe2ffc6a0) at ../src/conf/virnodedeviceobj.c:909
#5 0x00007ffff7b69146 in virHashForEach (table=0x7fff9814b700 = {...}, iter=0x7ffff7cb149e <virNodeDeviceObjListExportCallback>, opaque=0x7fffe2ffc6a0) at ../src/util/virhash.c:394
#6 0x00007ffff7cb1694 in virNodeDeviceObjListExport (conn=0x7fff98013170, devs=0x7fff98154430, devices=0x7fffe2ffc798, filter=0x7ffff7cf47a1 <virConnectListAllNodeDevicesCheckACL>, flags=0)
at ../src/conf/virnodedeviceobj.c:943
#7 0x00007fffe00694b2 in nodeConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/node_device/node_device_driver.c:228
#8 0x00007ffff7e703aa in virConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/libvirt-nodedev.c:130
#9 0x000055555557f796 in remoteDispatchConnectListAllNodeDevices (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)
at src/remote/remote_daemon_dispatch_stubs.h:1613
#10 0x000055555557f6f9 in remoteDispatchConnectListAllNodeDevicesHelper (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)
at src/remote/remote_daemon_dispatch_stubs.h:1591
#11 0x00007ffff7ce9542 in virNetServerProgramDispatchCall (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:428
#12 0x00007ffff7ce90bd in virNetServerProgramDispatch (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:302
#13 0x00007ffff7cf042b in virNetServerProcessMsg (srv=0x555555627080, client=0x5555556bf050, prog=0x555555690c10, msg=0x5555556c0000) at ../src/rpc/virnetserver.c:137
#14 0x00007ffff7cf04eb in virNetServerHandleJob (jobOpaque=0x5555556b66b0, opaque=0x555555627080) at ../src/rpc/virnetserver.c:154
#15 0x00007ffff7bd912f in virThreadPoolWorker (opaque=0x55555562bc70) at ../src/util/virthreadpool.c:163
#16 0x00007ffff7bd8645 in virThreadHelper (data=0x55555562bc90) at ../src/util/virthread.c:233
#17 0x00007ffff6d90432 in start_thread () at /lib64/libpthread.so.0
#18 0x00007ffff75c5913 in clone () at /lib64/libc.so.6
Signed-off-by: Jonathon Jongsma <[email protected]>
Reviewed-by: Ján Tomko <[email protected]>
Signed-off-by: Ján Tomko <[email protected]>
| 0
|
virNodeDeviceGetMdevTypesCaps(const char *sysfspath,
virMediatedDeviceTypePtr **mdev_types,
size_t *nmdev_types)
{
virMediatedDeviceTypePtr *types = NULL;
size_t ntypes = 0;
size_t i;
/* this could be a refresh, so clear out the old data */
for (i = 0; i < *nmdev_types; i++)
virMediatedDeviceTypeFree((*mdev_types)[i]);
VIR_FREE(*mdev_types);
*nmdev_types = 0;
if (virMediatedDeviceGetMdevTypes(sysfspath, &types, &ntypes) < 0)
return -1;
*mdev_types = g_steal_pointer(&types);
*nmdev_types = ntypes;
return 0;
}
|
41677585075086071603512617130977145017
|
node_device_conf.c
|
190835973650812059595485281579904597762
|
CWE-119
|
CVE-2021-3559
|
A flaw was found in libvirt in the virConnectListAllNodeDevices API in versions before 7.0.0. It only affects hosts with a PCI device and driver that supports mediated devices (e.g., GRID driver). This flaw could be used by an unprivileged client with a read-only connection to crash the libvirt daemon by executing the 'nodedev-list' virsh command. The highest threat from this vulnerability is to system availability.
|
https://nvd.nist.gov/vuln/detail/CVE-2021-3559
|
209,102
|
vim
|
80525751c5ce9ed82c41d83faf9ef38667bf61b1
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1
|
patch 9.0.0259: crash with mouse click when not initialized
Problem: Crash with mouse click when not initialized.
Solution: Check TabPageIdxs[] is not NULL.
| 1
|
do_mouse(
oparg_T *oap, // operator argument, can be NULL
int c, // K_LEFTMOUSE, etc
int dir, // Direction to 'put' if necessary
long count,
int fixindent) // PUT_FIXINDENT if fixing indent necessary
{
static int do_always = FALSE; // ignore 'mouse' setting next time
static int got_click = FALSE; // got a click some time back
int which_button; // MOUSE_LEFT, _MIDDLE or _RIGHT
int is_click = FALSE; // If FALSE it's a drag or release event
int is_drag = FALSE; // If TRUE it's a drag event
int jump_flags = 0; // flags for jump_to_mouse()
pos_T start_visual;
int moved; // Has cursor moved?
int in_status_line; // mouse in status line
static int in_tab_line = FALSE; // mouse clicked in tab line
int in_sep_line; // mouse in vertical separator line
int c1, c2;
#if defined(FEAT_FOLDING)
pos_T save_cursor;
#endif
win_T *old_curwin = curwin;
static pos_T orig_cursor;
colnr_T leftcol, rightcol;
pos_T end_visual;
int diff;
int old_active = VIsual_active;
int old_mode = VIsual_mode;
int regname;
#if defined(FEAT_FOLDING)
save_cursor = curwin->w_cursor;
#endif
// When GUI is active, always recognize mouse events, otherwise:
// - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.
// - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.
// - For command line and insert mode 'mouse' is checked before calling
// do_mouse().
if (do_always)
do_always = FALSE;
else
#ifdef FEAT_GUI
if (!gui.in_use)
#endif
{
if (VIsual_active)
{
if (!mouse_has(MOUSE_VISUAL))
return FALSE;
}
else if (State == MODE_NORMAL && !mouse_has(MOUSE_NORMAL))
return FALSE;
}
for (;;)
{
which_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);
if (is_drag)
{
// If the next character is the same mouse event then use that
// one. Speeds up dragging the status line.
// Note: Since characters added to the stuff buffer in the code
// below need to come before the next character, do not do this
// when the current character was stuffed.
if (!KeyStuffed && vpeekc() != NUL)
{
int nc;
int save_mouse_row = mouse_row;
int save_mouse_col = mouse_col;
// Need to get the character, peeking doesn't get the actual
// one.
nc = safe_vgetc();
if (c == nc)
continue;
vungetc(nc);
mouse_row = save_mouse_row;
mouse_col = save_mouse_col;
}
}
break;
}
if (c == K_MOUSEMOVE)
{
// Mouse moved without a button pressed.
#ifdef FEAT_BEVAL_TERM
ui_may_remove_balloon();
if (p_bevalterm)
{
profile_setlimit(p_bdlay, &bevalexpr_due);
bevalexpr_due_set = TRUE;
}
#endif
#ifdef FEAT_PROP_POPUP
popup_handle_mouse_moved();
#endif
return FALSE;
}
#ifdef FEAT_MOUSESHAPE
// May have stopped dragging the status or separator line. The pointer is
// most likely still on the status or separator line.
if (!is_drag && drag_status_line)
{
drag_status_line = FALSE;
update_mouseshape(SHAPE_IDX_STATUS);
}
if (!is_drag && drag_sep_line)
{
drag_sep_line = FALSE;
update_mouseshape(SHAPE_IDX_VSEP);
}
#endif
// Ignore drag and release events if we didn't get a click.
if (is_click)
got_click = TRUE;
else
{
if (!got_click) // didn't get click, ignore
return FALSE;
if (!is_drag) // release, reset got_click
{
got_click = FALSE;
if (in_tab_line)
{
in_tab_line = FALSE;
return FALSE;
}
}
}
// CTRL right mouse button does CTRL-T
if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)
{
if (State & MODE_INSERT)
stuffcharReadbuff(Ctrl_O);
if (count > 1)
stuffnumReadbuff(count);
stuffcharReadbuff(Ctrl_T);
got_click = FALSE; // ignore drag&release now
return FALSE;
}
// CTRL only works with left mouse button
if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)
return FALSE;
// When a modifier is down, ignore drag and release events, as well as
// multiple clicks and the middle mouse button.
// Accept shift-leftmouse drags when 'mousemodel' is "popup.*".
if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT
| MOD_MASK_META))
&& (!is_click
|| (mod_mask & MOD_MASK_MULTI_CLICK)
|| which_button == MOUSE_MIDDLE)
&& !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))
&& mouse_model_popup()
&& which_button == MOUSE_LEFT)
&& !((mod_mask & MOD_MASK_ALT)
&& !mouse_model_popup()
&& which_button == MOUSE_RIGHT)
)
return FALSE;
// If the button press was used as the movement command for an operator
// (eg "d<MOUSE>"), or it is the middle button that is held down, ignore
// drag/release events.
if (!is_click && which_button == MOUSE_MIDDLE)
return FALSE;
if (oap != NULL)
regname = oap->regname;
else
regname = 0;
// Middle mouse button does a 'put' of the selected text
if (which_button == MOUSE_MIDDLE)
{
if (State == MODE_NORMAL)
{
// If an operator was pending, we don't know what the user wanted
// to do. Go back to normal mode: Clear the operator and beep().
if (oap != NULL && oap->op_type != OP_NOP)
{
clearopbeep(oap);
return FALSE;
}
// If visual was active, yank the highlighted text and put it
// before the mouse pointer position.
// In Select mode replace the highlighted text with the clipboard.
if (VIsual_active)
{
if (VIsual_select)
{
stuffcharReadbuff(Ctrl_G);
stuffReadbuff((char_u *)"\"+p");
}
else
{
stuffcharReadbuff('y');
stuffcharReadbuff(K_MIDDLEMOUSE);
}
do_always = TRUE; // ignore 'mouse' setting next time
return FALSE;
}
// The rest is below jump_to_mouse()
}
else if ((State & MODE_INSERT) == 0)
return FALSE;
// Middle click in insert mode doesn't move the mouse, just insert the
// contents of a register. '.' register is special, can't insert that
// with do_put().
// Also paste at the cursor if the current mode isn't in 'mouse' (only
// happens for the GUI).
if ((State & MODE_INSERT) || !mouse_has(MOUSE_NORMAL))
{
if (regname == '.')
insert_reg(regname, TRUE);
else
{
#ifdef FEAT_CLIPBOARD
if (clip_star.available && regname == 0)
regname = '*';
#endif
if ((State & REPLACE_FLAG) && !yank_register_mline(regname))
insert_reg(regname, TRUE);
else
{
do_put(regname, NULL, BACKWARD, 1L,
fixindent | PUT_CURSEND);
// Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r
AppendCharToRedobuff(Ctrl_R);
AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);
AppendCharToRedobuff(regname == 0 ? '"' : regname);
}
}
return FALSE;
}
}
// When dragging or button-up stay in the same window.
if (!is_click)
jump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;
start_visual.lnum = 0;
// Check for clicking in the tab page line.
if (mouse_row == 0 && firstwin->w_winrow > 0)
{
if (is_drag)
{
if (in_tab_line)
{
c1 = TabPageIdxs[mouse_col];
tabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)
? c1 - 1 : c1);
}
return FALSE;
}
// click in a tab selects that tab page
if (is_click
# ifdef FEAT_CMDWIN
&& cmdwin_type == 0
# endif
&& mouse_col < Columns)
{
in_tab_line = TRUE;
c1 = TabPageIdxs[mouse_col];
if (c1 >= 0)
{
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
// double click opens new page
end_visual_mode_keep_button();
tabpage_new();
tabpage_move(c1 == 0 ? 9999 : c1 - 1);
}
else
{
// Go to specified tab page, or next one if not clicking
// on a label.
goto_tabpage(c1);
// It's like clicking on the status line of a window.
if (curwin != old_curwin)
end_visual_mode_keep_button();
}
}
else
{
tabpage_T *tp;
// Close the current or specified tab page.
if (c1 == -999)
tp = curtab;
else
tp = find_tabpage(-c1);
if (tp == curtab)
{
if (first_tabpage->tp_next != NULL)
tabpage_close(FALSE);
}
else if (tp != NULL)
tabpage_close_other(tp, FALSE);
}
}
return TRUE;
}
else if (is_drag && in_tab_line)
{
c1 = TabPageIdxs[mouse_col];
tabpage_move(c1 <= 0 ? 9999 : c1 - 1);
return FALSE;
}
// When 'mousemodel' is "popup" or "popup_setpos", translate mouse events:
// right button up -> pop-up menu
// shift-left button -> right button
// alt-left button -> alt-right button
if (mouse_model_popup())
{
if (which_button == MOUSE_RIGHT
&& !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
{
#ifdef USE_POPUP_SETPOS
# ifdef FEAT_GUI
if (gui.in_use)
{
# if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
|| defined(FEAT_GUI_PHOTON)
if (!is_click)
// Ignore right button release events, only shows the popup
// menu on the button down event.
return FALSE;
# endif
# if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_HAIKU)
if (is_click || is_drag)
// Ignore right button down and drag mouse events. Windows
// only shows the popup menu on the button up event.
return FALSE;
# endif
}
# endif
# if defined(FEAT_GUI) && defined(FEAT_TERM_POPUP_MENU)
else
# endif
# if defined(FEAT_TERM_POPUP_MENU)
if (!is_click)
// Ignore right button release events, only shows the popup
// menu on the button down event.
return FALSE;
#endif
jump_flags = 0;
if (STRCMP(p_mousem, "popup_setpos") == 0)
{
// First set the cursor position before showing the popup
// menu.
if (VIsual_active)
{
pos_T m_pos;
// set MOUSE_MAY_STOP_VIS if we are outside the
// selection or the current window (might have false
// negative here)
if (mouse_row < curwin->w_winrow
|| mouse_row
> (curwin->w_winrow + curwin->w_height))
jump_flags = MOUSE_MAY_STOP_VIS;
else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)
jump_flags = MOUSE_MAY_STOP_VIS;
else
{
if ((LT_POS(curwin->w_cursor, VIsual)
&& (LT_POS(m_pos, curwin->w_cursor)
|| LT_POS(VIsual, m_pos)))
|| (LT_POS(VIsual, curwin->w_cursor)
&& (LT_POS(m_pos, VIsual)
|| LT_POS(curwin->w_cursor, m_pos))))
{
jump_flags = MOUSE_MAY_STOP_VIS;
}
else if (VIsual_mode == Ctrl_V)
{
getvcols(curwin, &curwin->w_cursor, &VIsual,
&leftcol, &rightcol);
getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);
if (m_pos.col < leftcol || m_pos.col > rightcol)
jump_flags = MOUSE_MAY_STOP_VIS;
}
}
}
else
jump_flags = MOUSE_MAY_STOP_VIS;
}
if (jump_flags)
{
jump_flags = jump_to_mouse(jump_flags, NULL, which_button);
update_curbuf(VIsual_active ? UPD_INVERTED : UPD_VALID);
setcursor();
out_flush(); // Update before showing popup menu
}
# ifdef FEAT_MENU
show_popupmenu();
got_click = FALSE; // ignore release events
# endif
return (jump_flags & CURSOR_MOVED) != 0;
#else
return FALSE;
#endif
}
if (which_button == MOUSE_LEFT
&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))
{
which_button = MOUSE_RIGHT;
mod_mask &= ~MOD_MASK_SHIFT;
}
}
if ((State & (MODE_NORMAL | MODE_INSERT))
&& !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
{
if (which_button == MOUSE_LEFT)
{
if (is_click)
{
// stop Visual mode for a left click in a window, but not when
// on a status line
if (VIsual_active)
jump_flags |= MOUSE_MAY_STOP_VIS;
}
else if (mouse_has(MOUSE_VISUAL))
jump_flags |= MOUSE_MAY_VIS;
}
else if (which_button == MOUSE_RIGHT)
{
if (is_click && VIsual_active)
{
// Remember the start and end of visual before moving the
// cursor.
if (LT_POS(curwin->w_cursor, VIsual))
{
start_visual = curwin->w_cursor;
end_visual = VIsual;
}
else
{
start_visual = VIsual;
end_visual = curwin->w_cursor;
}
}
jump_flags |= MOUSE_FOCUS;
if (mouse_has(MOUSE_VISUAL))
jump_flags |= MOUSE_MAY_VIS;
}
}
// If an operator is pending, ignore all drags and releases until the
// next mouse click.
if (!is_drag && oap != NULL && oap->op_type != OP_NOP)
{
got_click = FALSE;
oap->motion_type = MCHAR;
}
// When releasing the button let jump_to_mouse() know.
if (!is_click && !is_drag)
jump_flags |= MOUSE_RELEASED;
// JUMP!
jump_flags = jump_to_mouse(jump_flags,
oap == NULL ? NULL : &(oap->inclusive), which_button);
#ifdef FEAT_MENU
// A click in the window toolbar has no side effects.
if (jump_flags & MOUSE_WINBAR)
return FALSE;
#endif
moved = (jump_flags & CURSOR_MOVED);
in_status_line = (jump_flags & IN_STATUS_LINE);
in_sep_line = (jump_flags & IN_SEP_LINE);
#ifdef FEAT_NETBEANS_INTG
if (isNetbeansBuffer(curbuf)
&& !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))
{
int key = KEY2TERMCAP1(c);
if (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE
|| key == (int)KE_RIGHTRELEASE)
netbeans_button_release(which_button);
}
#endif
// When jumping to another window, clear a pending operator. That's a bit
// friendlier than beeping and not jumping to that window.
if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)
clearop(oap);
#ifdef FEAT_FOLDING
if (mod_mask == 0
&& !is_drag
&& (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))
&& which_button == MOUSE_LEFT)
{
// open or close a fold at this line
if (jump_flags & MOUSE_FOLD_OPEN)
openFold(curwin->w_cursor.lnum, 1L);
else
closeFold(curwin->w_cursor.lnum, 1L);
// don't move the cursor if still in the same window
if (curwin == old_curwin)
curwin->w_cursor = save_cursor;
}
#endif
#if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)
if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)
{
clip_modeless(which_button, is_click, is_drag);
return FALSE;
}
#endif
// Set global flag that we are extending the Visual area with mouse
// dragging; temporarily minimize 'scrolloff'.
if (VIsual_active && is_drag && get_scrolloff_value())
{
// In the very first line, allow scrolling one line
if (mouse_row == 0)
mouse_dragging = 2;
else
mouse_dragging = 1;
}
// When dragging the mouse above the window, scroll down.
if (is_drag && mouse_row < 0 && !in_status_line)
{
scroll_redraw(FALSE, 1L);
mouse_row = 0;
}
if (start_visual.lnum) // right click in visual mode
{
// When ALT is pressed make Visual mode blockwise.
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
// In Visual-block mode, divide the area in four, pick up the corner
// that is in the quarter that the cursor is in.
if (VIsual_mode == Ctrl_V)
{
getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);
if (curwin->w_curswant > (leftcol + rightcol) / 2)
end_visual.col = leftcol;
else
end_visual.col = rightcol;
if (curwin->w_cursor.lnum >=
(start_visual.lnum + end_visual.lnum) / 2)
end_visual.lnum = start_visual.lnum;
// move VIsual to the right column
start_visual = curwin->w_cursor; // save the cursor pos
curwin->w_cursor = end_visual;
coladvance(end_visual.col);
VIsual = curwin->w_cursor;
curwin->w_cursor = start_visual; // restore the cursor
}
else
{
// If the click is before the start of visual, change the start.
// If the click is after the end of visual, change the end. If
// the click is inside the visual, change the closest side.
if (LT_POS(curwin->w_cursor, start_visual))
VIsual = end_visual;
else if (LT_POS(end_visual, curwin->w_cursor))
VIsual = start_visual;
else
{
// In the same line, compare column number
if (end_visual.lnum == start_visual.lnum)
{
if (curwin->w_cursor.col - start_visual.col >
end_visual.col - curwin->w_cursor.col)
VIsual = start_visual;
else
VIsual = end_visual;
}
// In different lines, compare line number
else
{
diff = (curwin->w_cursor.lnum - start_visual.lnum) -
(end_visual.lnum - curwin->w_cursor.lnum);
if (diff > 0) // closest to end
VIsual = start_visual;
else if (diff < 0) // closest to start
VIsual = end_visual;
else // in the middle line
{
if (curwin->w_cursor.col <
(start_visual.col + end_visual.col) / 2)
VIsual = end_visual;
else
VIsual = start_visual;
}
}
}
}
}
// If Visual mode started in insert mode, execute "CTRL-O"
else if ((State & MODE_INSERT) && VIsual_active)
stuffcharReadbuff(Ctrl_O);
// Middle mouse click: Put text before cursor.
if (which_button == MOUSE_MIDDLE)
{
#ifdef FEAT_CLIPBOARD
if (clip_star.available && regname == 0)
regname = '*';
#endif
if (yank_register_mline(regname))
{
if (mouse_past_bottom)
dir = FORWARD;
}
else if (mouse_past_eol)
dir = FORWARD;
if (fixindent)
{
c1 = (dir == BACKWARD) ? '[' : ']';
c2 = 'p';
}
else
{
c1 = (dir == FORWARD) ? 'p' : 'P';
c2 = NUL;
}
prep_redo(regname, count, NUL, c1, NUL, c2, NUL);
// Remember where the paste started, so in edit() Insstart can be set
// to this position
if (restart_edit != 0)
where_paste_started = curwin->w_cursor;
do_put(regname, NULL, dir, count, fixindent | PUT_CURSEND);
}
#if defined(FEAT_QUICKFIX)
// Ctrl-Mouse click or double click in a quickfix window jumps to the
// error under the mouse pointer.
else if (((mod_mask & MOD_MASK_CTRL)
|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
&& bt_quickfix(curbuf))
{
if (curwin->w_llist_ref == NULL) // quickfix window
do_cmdline_cmd((char_u *)".cc");
else // location list window
do_cmdline_cmd((char_u *)".ll");
got_click = FALSE; // ignore drag&release now
}
#endif
// Ctrl-Mouse click (or double click in a help window) jumps to the tag
// under the mouse pointer.
else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help
&& (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))
{
if (State & MODE_INSERT)
stuffcharReadbuff(Ctrl_O);
stuffcharReadbuff(Ctrl_RSB);
got_click = FALSE; // ignore drag&release now
}
// Shift-Mouse click searches for the next occurrence of the word under
// the mouse pointer
else if ((mod_mask & MOD_MASK_SHIFT))
{
if ((State & MODE_INSERT) || (VIsual_active && VIsual_select))
stuffcharReadbuff(Ctrl_O);
if (which_button == MOUSE_LEFT)
stuffcharReadbuff('*');
else // MOUSE_RIGHT
stuffcharReadbuff('#');
}
// Handle double clicks, unless on status line
else if (in_status_line)
{
#ifdef FEAT_MOUSESHAPE
if ((is_drag || is_click) && !drag_status_line)
{
drag_status_line = TRUE;
update_mouseshape(-1);
}
#endif
}
else if (in_sep_line)
{
#ifdef FEAT_MOUSESHAPE
if ((is_drag || is_click) && !drag_sep_line)
{
drag_sep_line = TRUE;
update_mouseshape(-1);
}
#endif
}
else if ((mod_mask & MOD_MASK_MULTI_CLICK)
&& (State & (MODE_NORMAL | MODE_INSERT))
&& mouse_has(MOUSE_VISUAL))
{
if (is_click || !VIsual_active)
{
if (VIsual_active)
orig_cursor = VIsual;
else
{
check_visual_highlight();
VIsual = curwin->w_cursor;
orig_cursor = VIsual;
VIsual_active = TRUE;
VIsual_reselect = TRUE;
// start Select mode if 'selectmode' contains "mouse"
may_start_select('o');
setmouse();
}
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
// Double click with ALT pressed makes it blockwise.
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
else
VIsual_mode = 'v';
}
else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)
VIsual_mode = 'V';
else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)
VIsual_mode = Ctrl_V;
#ifdef FEAT_CLIPBOARD
// Make sure the clipboard gets updated. Needed because start and
// end may still be the same, and the selection needs to be owned
clip_star.vmode = NUL;
#endif
}
// A double click selects a word or a block.
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
pos_T *pos = NULL;
int gc;
if (is_click)
{
// If the character under the cursor (skipping white space) is
// not a word character, try finding a match and select a (),
// {}, [], #if/#endif, etc. block.
end_visual = curwin->w_cursor;
while (gc = gchar_pos(&end_visual), VIM_ISWHITE(gc))
inc(&end_visual);
if (oap != NULL)
oap->motion_type = MCHAR;
if (oap != NULL
&& VIsual_mode == 'v'
&& !vim_iswordc(gchar_pos(&end_visual))
&& EQUAL_POS(curwin->w_cursor, VIsual)
&& (pos = findmatch(oap, NUL)) != NULL)
{
curwin->w_cursor = *pos;
if (oap->motion_type == MLINE)
VIsual_mode = 'V';
else if (*p_sel == 'e')
{
if (LT_POS(curwin->w_cursor, VIsual))
++VIsual.col;
else
++curwin->w_cursor.col;
}
}
}
if (pos == NULL && (is_click || is_drag))
{
// When not found a match or when dragging: extend to include
// a word.
if (LT_POS(curwin->w_cursor, orig_cursor))
{
find_start_of_word(&curwin->w_cursor);
find_end_of_word(&VIsual);
}
else
{
find_start_of_word(&VIsual);
if (*p_sel == 'e' && *ml_get_cursor() != NUL)
curwin->w_cursor.col +=
(*mb_ptr2len)(ml_get_cursor());
find_end_of_word(&curwin->w_cursor);
}
}
curwin->w_set_curswant = TRUE;
}
if (is_click)
redraw_curbuf_later(UPD_INVERTED); // update the inversion
}
else if (VIsual_active && !old_active)
{
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
else
VIsual_mode = 'v';
}
// If Visual mode changed show it later.
if ((!VIsual_active && old_active && mode_displayed)
|| (VIsual_active && p_smd && msg_silent == 0
&& (!old_active || VIsual_mode != old_mode)))
redraw_cmdline = TRUE;
return moved;
}
|
230981879452824566126490545559038336652
|
mouse.c
|
48030859742909908779392834945640503907
|
CWE-703
|
CVE-2022-2980
|
NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2980
|
418,795
|
vim
|
80525751c5ce9ed82c41d83faf9ef38667bf61b1
|
https://github.com/vim/vim
|
https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1
|
patch 9.0.0259: crash with mouse click when not initialized
Problem: Crash with mouse click when not initialized.
Solution: Check TabPageIdxs[] is not NULL.
| 0
|
do_mouse(
oparg_T *oap, // operator argument, can be NULL
int c, // K_LEFTMOUSE, etc
int dir, // Direction to 'put' if necessary
long count,
int fixindent) // PUT_FIXINDENT if fixing indent necessary
{
static int do_always = FALSE; // ignore 'mouse' setting next time
static int got_click = FALSE; // got a click some time back
int which_button; // MOUSE_LEFT, _MIDDLE or _RIGHT
int is_click = FALSE; // If FALSE it's a drag or release event
int is_drag = FALSE; // If TRUE it's a drag event
int jump_flags = 0; // flags for jump_to_mouse()
pos_T start_visual;
int moved; // Has cursor moved?
int in_status_line; // mouse in status line
static int in_tab_line = FALSE; // mouse clicked in tab line
int in_sep_line; // mouse in vertical separator line
int c1, c2;
#if defined(FEAT_FOLDING)
pos_T save_cursor;
#endif
win_T *old_curwin = curwin;
static pos_T orig_cursor;
colnr_T leftcol, rightcol;
pos_T end_visual;
int diff;
int old_active = VIsual_active;
int old_mode = VIsual_mode;
int regname;
#if defined(FEAT_FOLDING)
save_cursor = curwin->w_cursor;
#endif
// When GUI is active, always recognize mouse events, otherwise:
// - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.
// - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.
// - For command line and insert mode 'mouse' is checked before calling
// do_mouse().
if (do_always)
do_always = FALSE;
else
#ifdef FEAT_GUI
if (!gui.in_use)
#endif
{
if (VIsual_active)
{
if (!mouse_has(MOUSE_VISUAL))
return FALSE;
}
else if (State == MODE_NORMAL && !mouse_has(MOUSE_NORMAL))
return FALSE;
}
for (;;)
{
which_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);
if (is_drag)
{
// If the next character is the same mouse event then use that
// one. Speeds up dragging the status line.
// Note: Since characters added to the stuff buffer in the code
// below need to come before the next character, do not do this
// when the current character was stuffed.
if (!KeyStuffed && vpeekc() != NUL)
{
int nc;
int save_mouse_row = mouse_row;
int save_mouse_col = mouse_col;
// Need to get the character, peeking doesn't get the actual
// one.
nc = safe_vgetc();
if (c == nc)
continue;
vungetc(nc);
mouse_row = save_mouse_row;
mouse_col = save_mouse_col;
}
}
break;
}
if (c == K_MOUSEMOVE)
{
// Mouse moved without a button pressed.
#ifdef FEAT_BEVAL_TERM
ui_may_remove_balloon();
if (p_bevalterm)
{
profile_setlimit(p_bdlay, &bevalexpr_due);
bevalexpr_due_set = TRUE;
}
#endif
#ifdef FEAT_PROP_POPUP
popup_handle_mouse_moved();
#endif
return FALSE;
}
#ifdef FEAT_MOUSESHAPE
// May have stopped dragging the status or separator line. The pointer is
// most likely still on the status or separator line.
if (!is_drag && drag_status_line)
{
drag_status_line = FALSE;
update_mouseshape(SHAPE_IDX_STATUS);
}
if (!is_drag && drag_sep_line)
{
drag_sep_line = FALSE;
update_mouseshape(SHAPE_IDX_VSEP);
}
#endif
// Ignore drag and release events if we didn't get a click.
if (is_click)
got_click = TRUE;
else
{
if (!got_click) // didn't get click, ignore
return FALSE;
if (!is_drag) // release, reset got_click
{
got_click = FALSE;
if (in_tab_line)
{
in_tab_line = FALSE;
return FALSE;
}
}
}
// CTRL right mouse button does CTRL-T
if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)
{
if (State & MODE_INSERT)
stuffcharReadbuff(Ctrl_O);
if (count > 1)
stuffnumReadbuff(count);
stuffcharReadbuff(Ctrl_T);
got_click = FALSE; // ignore drag&release now
return FALSE;
}
// CTRL only works with left mouse button
if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)
return FALSE;
// When a modifier is down, ignore drag and release events, as well as
// multiple clicks and the middle mouse button.
// Accept shift-leftmouse drags when 'mousemodel' is "popup.*".
if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT
| MOD_MASK_META))
&& (!is_click
|| (mod_mask & MOD_MASK_MULTI_CLICK)
|| which_button == MOUSE_MIDDLE)
&& !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))
&& mouse_model_popup()
&& which_button == MOUSE_LEFT)
&& !((mod_mask & MOD_MASK_ALT)
&& !mouse_model_popup()
&& which_button == MOUSE_RIGHT)
)
return FALSE;
// If the button press was used as the movement command for an operator
// (eg "d<MOUSE>"), or it is the middle button that is held down, ignore
// drag/release events.
if (!is_click && which_button == MOUSE_MIDDLE)
return FALSE;
if (oap != NULL)
regname = oap->regname;
else
regname = 0;
// Middle mouse button does a 'put' of the selected text
if (which_button == MOUSE_MIDDLE)
{
if (State == MODE_NORMAL)
{
// If an operator was pending, we don't know what the user wanted
// to do. Go back to normal mode: Clear the operator and beep().
if (oap != NULL && oap->op_type != OP_NOP)
{
clearopbeep(oap);
return FALSE;
}
// If visual was active, yank the highlighted text and put it
// before the mouse pointer position.
// In Select mode replace the highlighted text with the clipboard.
if (VIsual_active)
{
if (VIsual_select)
{
stuffcharReadbuff(Ctrl_G);
stuffReadbuff((char_u *)"\"+p");
}
else
{
stuffcharReadbuff('y');
stuffcharReadbuff(K_MIDDLEMOUSE);
}
do_always = TRUE; // ignore 'mouse' setting next time
return FALSE;
}
// The rest is below jump_to_mouse()
}
else if ((State & MODE_INSERT) == 0)
return FALSE;
// Middle click in insert mode doesn't move the mouse, just insert the
// contents of a register. '.' register is special, can't insert that
// with do_put().
// Also paste at the cursor if the current mode isn't in 'mouse' (only
// happens for the GUI).
if ((State & MODE_INSERT) || !mouse_has(MOUSE_NORMAL))
{
if (regname == '.')
insert_reg(regname, TRUE);
else
{
#ifdef FEAT_CLIPBOARD
if (clip_star.available && regname == 0)
regname = '*';
#endif
if ((State & REPLACE_FLAG) && !yank_register_mline(regname))
insert_reg(regname, TRUE);
else
{
do_put(regname, NULL, BACKWARD, 1L,
fixindent | PUT_CURSEND);
// Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r
AppendCharToRedobuff(Ctrl_R);
AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);
AppendCharToRedobuff(regname == 0 ? '"' : regname);
}
}
return FALSE;
}
}
// When dragging or button-up stay in the same window.
if (!is_click)
jump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;
start_visual.lnum = 0;
if (TabPageIdxs != NULL) // only when initialized
{
// Check for clicking in the tab page line.
if (mouse_row == 0 && firstwin->w_winrow > 0)
{
if (is_drag)
{
if (in_tab_line)
{
c1 = TabPageIdxs[mouse_col];
tabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)
? c1 - 1 : c1);
}
return FALSE;
}
// click in a tab selects that tab page
if (is_click
# ifdef FEAT_CMDWIN
&& cmdwin_type == 0
# endif
&& mouse_col < Columns)
{
in_tab_line = TRUE;
c1 = TabPageIdxs[mouse_col];
if (c1 >= 0)
{
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
// double click opens new page
end_visual_mode_keep_button();
tabpage_new();
tabpage_move(c1 == 0 ? 9999 : c1 - 1);
}
else
{
// Go to specified tab page, or next one if not clicking
// on a label.
goto_tabpage(c1);
// It's like clicking on the status line of a window.
if (curwin != old_curwin)
end_visual_mode_keep_button();
}
}
else
{
tabpage_T *tp;
// Close the current or specified tab page.
if (c1 == -999)
tp = curtab;
else
tp = find_tabpage(-c1);
if (tp == curtab)
{
if (first_tabpage->tp_next != NULL)
tabpage_close(FALSE);
}
else if (tp != NULL)
tabpage_close_other(tp, FALSE);
}
}
return TRUE;
}
else if (is_drag && in_tab_line)
{
c1 = TabPageIdxs[mouse_col];
tabpage_move(c1 <= 0 ? 9999 : c1 - 1);
return FALSE;
}
}
// When 'mousemodel' is "popup" or "popup_setpos", translate mouse events:
// right button up -> pop-up menu
// shift-left button -> right button
// alt-left button -> alt-right button
if (mouse_model_popup())
{
if (which_button == MOUSE_RIGHT
&& !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
{
#ifdef USE_POPUP_SETPOS
# ifdef FEAT_GUI
if (gui.in_use)
{
# if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
|| defined(FEAT_GUI_PHOTON)
if (!is_click)
// Ignore right button release events, only shows the popup
// menu on the button down event.
return FALSE;
# endif
# if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_HAIKU)
if (is_click || is_drag)
// Ignore right button down and drag mouse events. Windows
// only shows the popup menu on the button up event.
return FALSE;
# endif
}
# endif
# if defined(FEAT_GUI) && defined(FEAT_TERM_POPUP_MENU)
else
# endif
# if defined(FEAT_TERM_POPUP_MENU)
if (!is_click)
// Ignore right button release events, only shows the popup
// menu on the button down event.
return FALSE;
#endif
jump_flags = 0;
if (STRCMP(p_mousem, "popup_setpos") == 0)
{
// First set the cursor position before showing the popup
// menu.
if (VIsual_active)
{
pos_T m_pos;
// set MOUSE_MAY_STOP_VIS if we are outside the
// selection or the current window (might have false
// negative here)
if (mouse_row < curwin->w_winrow
|| mouse_row
> (curwin->w_winrow + curwin->w_height))
jump_flags = MOUSE_MAY_STOP_VIS;
else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)
jump_flags = MOUSE_MAY_STOP_VIS;
else
{
if ((LT_POS(curwin->w_cursor, VIsual)
&& (LT_POS(m_pos, curwin->w_cursor)
|| LT_POS(VIsual, m_pos)))
|| (LT_POS(VIsual, curwin->w_cursor)
&& (LT_POS(m_pos, VIsual)
|| LT_POS(curwin->w_cursor, m_pos))))
{
jump_flags = MOUSE_MAY_STOP_VIS;
}
else if (VIsual_mode == Ctrl_V)
{
getvcols(curwin, &curwin->w_cursor, &VIsual,
&leftcol, &rightcol);
getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);
if (m_pos.col < leftcol || m_pos.col > rightcol)
jump_flags = MOUSE_MAY_STOP_VIS;
}
}
}
else
jump_flags = MOUSE_MAY_STOP_VIS;
}
if (jump_flags)
{
jump_flags = jump_to_mouse(jump_flags, NULL, which_button);
update_curbuf(VIsual_active ? UPD_INVERTED : UPD_VALID);
setcursor();
out_flush(); // Update before showing popup menu
}
# ifdef FEAT_MENU
show_popupmenu();
got_click = FALSE; // ignore release events
# endif
return (jump_flags & CURSOR_MOVED) != 0;
#else
return FALSE;
#endif
}
if (which_button == MOUSE_LEFT
&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))
{
which_button = MOUSE_RIGHT;
mod_mask &= ~MOD_MASK_SHIFT;
}
}
if ((State & (MODE_NORMAL | MODE_INSERT))
&& !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
{
if (which_button == MOUSE_LEFT)
{
if (is_click)
{
// stop Visual mode for a left click in a window, but not when
// on a status line
if (VIsual_active)
jump_flags |= MOUSE_MAY_STOP_VIS;
}
else if (mouse_has(MOUSE_VISUAL))
jump_flags |= MOUSE_MAY_VIS;
}
else if (which_button == MOUSE_RIGHT)
{
if (is_click && VIsual_active)
{
// Remember the start and end of visual before moving the
// cursor.
if (LT_POS(curwin->w_cursor, VIsual))
{
start_visual = curwin->w_cursor;
end_visual = VIsual;
}
else
{
start_visual = VIsual;
end_visual = curwin->w_cursor;
}
}
jump_flags |= MOUSE_FOCUS;
if (mouse_has(MOUSE_VISUAL))
jump_flags |= MOUSE_MAY_VIS;
}
}
// If an operator is pending, ignore all drags and releases until the
// next mouse click.
if (!is_drag && oap != NULL && oap->op_type != OP_NOP)
{
got_click = FALSE;
oap->motion_type = MCHAR;
}
// When releasing the button let jump_to_mouse() know.
if (!is_click && !is_drag)
jump_flags |= MOUSE_RELEASED;
// JUMP!
jump_flags = jump_to_mouse(jump_flags,
oap == NULL ? NULL : &(oap->inclusive), which_button);
#ifdef FEAT_MENU
// A click in the window toolbar has no side effects.
if (jump_flags & MOUSE_WINBAR)
return FALSE;
#endif
moved = (jump_flags & CURSOR_MOVED);
in_status_line = (jump_flags & IN_STATUS_LINE);
in_sep_line = (jump_flags & IN_SEP_LINE);
#ifdef FEAT_NETBEANS_INTG
if (isNetbeansBuffer(curbuf)
&& !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))
{
int key = KEY2TERMCAP1(c);
if (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE
|| key == (int)KE_RIGHTRELEASE)
netbeans_button_release(which_button);
}
#endif
// When jumping to another window, clear a pending operator. That's a bit
// friendlier than beeping and not jumping to that window.
if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)
clearop(oap);
#ifdef FEAT_FOLDING
if (mod_mask == 0
&& !is_drag
&& (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))
&& which_button == MOUSE_LEFT)
{
// open or close a fold at this line
if (jump_flags & MOUSE_FOLD_OPEN)
openFold(curwin->w_cursor.lnum, 1L);
else
closeFold(curwin->w_cursor.lnum, 1L);
// don't move the cursor if still in the same window
if (curwin == old_curwin)
curwin->w_cursor = save_cursor;
}
#endif
#if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)
if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)
{
clip_modeless(which_button, is_click, is_drag);
return FALSE;
}
#endif
// Set global flag that we are extending the Visual area with mouse
// dragging; temporarily minimize 'scrolloff'.
if (VIsual_active && is_drag && get_scrolloff_value())
{
// In the very first line, allow scrolling one line
if (mouse_row == 0)
mouse_dragging = 2;
else
mouse_dragging = 1;
}
// When dragging the mouse above the window, scroll down.
if (is_drag && mouse_row < 0 && !in_status_line)
{
scroll_redraw(FALSE, 1L);
mouse_row = 0;
}
if (start_visual.lnum) // right click in visual mode
{
// When ALT is pressed make Visual mode blockwise.
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
// In Visual-block mode, divide the area in four, pick up the corner
// that is in the quarter that the cursor is in.
if (VIsual_mode == Ctrl_V)
{
getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);
if (curwin->w_curswant > (leftcol + rightcol) / 2)
end_visual.col = leftcol;
else
end_visual.col = rightcol;
if (curwin->w_cursor.lnum >=
(start_visual.lnum + end_visual.lnum) / 2)
end_visual.lnum = start_visual.lnum;
// move VIsual to the right column
start_visual = curwin->w_cursor; // save the cursor pos
curwin->w_cursor = end_visual;
coladvance(end_visual.col);
VIsual = curwin->w_cursor;
curwin->w_cursor = start_visual; // restore the cursor
}
else
{
// If the click is before the start of visual, change the start.
// If the click is after the end of visual, change the end. If
// the click is inside the visual, change the closest side.
if (LT_POS(curwin->w_cursor, start_visual))
VIsual = end_visual;
else if (LT_POS(end_visual, curwin->w_cursor))
VIsual = start_visual;
else
{
// In the same line, compare column number
if (end_visual.lnum == start_visual.lnum)
{
if (curwin->w_cursor.col - start_visual.col >
end_visual.col - curwin->w_cursor.col)
VIsual = start_visual;
else
VIsual = end_visual;
}
// In different lines, compare line number
else
{
diff = (curwin->w_cursor.lnum - start_visual.lnum) -
(end_visual.lnum - curwin->w_cursor.lnum);
if (diff > 0) // closest to end
VIsual = start_visual;
else if (diff < 0) // closest to start
VIsual = end_visual;
else // in the middle line
{
if (curwin->w_cursor.col <
(start_visual.col + end_visual.col) / 2)
VIsual = end_visual;
else
VIsual = start_visual;
}
}
}
}
}
// If Visual mode started in insert mode, execute "CTRL-O"
else if ((State & MODE_INSERT) && VIsual_active)
stuffcharReadbuff(Ctrl_O);
// Middle mouse click: Put text before cursor.
if (which_button == MOUSE_MIDDLE)
{
#ifdef FEAT_CLIPBOARD
if (clip_star.available && regname == 0)
regname = '*';
#endif
if (yank_register_mline(regname))
{
if (mouse_past_bottom)
dir = FORWARD;
}
else if (mouse_past_eol)
dir = FORWARD;
if (fixindent)
{
c1 = (dir == BACKWARD) ? '[' : ']';
c2 = 'p';
}
else
{
c1 = (dir == FORWARD) ? 'p' : 'P';
c2 = NUL;
}
prep_redo(regname, count, NUL, c1, NUL, c2, NUL);
// Remember where the paste started, so in edit() Insstart can be set
// to this position
if (restart_edit != 0)
where_paste_started = curwin->w_cursor;
do_put(regname, NULL, dir, count, fixindent | PUT_CURSEND);
}
#if defined(FEAT_QUICKFIX)
// Ctrl-Mouse click or double click in a quickfix window jumps to the
// error under the mouse pointer.
else if (((mod_mask & MOD_MASK_CTRL)
|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
&& bt_quickfix(curbuf))
{
if (curwin->w_llist_ref == NULL) // quickfix window
do_cmdline_cmd((char_u *)".cc");
else // location list window
do_cmdline_cmd((char_u *)".ll");
got_click = FALSE; // ignore drag&release now
}
#endif
// Ctrl-Mouse click (or double click in a help window) jumps to the tag
// under the mouse pointer.
else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help
&& (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))
{
if (State & MODE_INSERT)
stuffcharReadbuff(Ctrl_O);
stuffcharReadbuff(Ctrl_RSB);
got_click = FALSE; // ignore drag&release now
}
// Shift-Mouse click searches for the next occurrence of the word under
// the mouse pointer
else if ((mod_mask & MOD_MASK_SHIFT))
{
if ((State & MODE_INSERT) || (VIsual_active && VIsual_select))
stuffcharReadbuff(Ctrl_O);
if (which_button == MOUSE_LEFT)
stuffcharReadbuff('*');
else // MOUSE_RIGHT
stuffcharReadbuff('#');
}
// Handle double clicks, unless on status line
else if (in_status_line)
{
#ifdef FEAT_MOUSESHAPE
if ((is_drag || is_click) && !drag_status_line)
{
drag_status_line = TRUE;
update_mouseshape(-1);
}
#endif
}
else if (in_sep_line)
{
#ifdef FEAT_MOUSESHAPE
if ((is_drag || is_click) && !drag_sep_line)
{
drag_sep_line = TRUE;
update_mouseshape(-1);
}
#endif
}
else if ((mod_mask & MOD_MASK_MULTI_CLICK)
&& (State & (MODE_NORMAL | MODE_INSERT))
&& mouse_has(MOUSE_VISUAL))
{
if (is_click || !VIsual_active)
{
if (VIsual_active)
orig_cursor = VIsual;
else
{
check_visual_highlight();
VIsual = curwin->w_cursor;
orig_cursor = VIsual;
VIsual_active = TRUE;
VIsual_reselect = TRUE;
// start Select mode if 'selectmode' contains "mouse"
may_start_select('o');
setmouse();
}
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
// Double click with ALT pressed makes it blockwise.
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
else
VIsual_mode = 'v';
}
else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)
VIsual_mode = 'V';
else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)
VIsual_mode = Ctrl_V;
#ifdef FEAT_CLIPBOARD
// Make sure the clipboard gets updated. Needed because start and
// end may still be the same, and the selection needs to be owned
clip_star.vmode = NUL;
#endif
}
// A double click selects a word or a block.
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
pos_T *pos = NULL;
int gc;
if (is_click)
{
// If the character under the cursor (skipping white space) is
// not a word character, try finding a match and select a (),
// {}, [], #if/#endif, etc. block.
end_visual = curwin->w_cursor;
while (gc = gchar_pos(&end_visual), VIM_ISWHITE(gc))
inc(&end_visual);
if (oap != NULL)
oap->motion_type = MCHAR;
if (oap != NULL
&& VIsual_mode == 'v'
&& !vim_iswordc(gchar_pos(&end_visual))
&& EQUAL_POS(curwin->w_cursor, VIsual)
&& (pos = findmatch(oap, NUL)) != NULL)
{
curwin->w_cursor = *pos;
if (oap->motion_type == MLINE)
VIsual_mode = 'V';
else if (*p_sel == 'e')
{
if (LT_POS(curwin->w_cursor, VIsual))
++VIsual.col;
else
++curwin->w_cursor.col;
}
}
}
if (pos == NULL && (is_click || is_drag))
{
// When not found a match or when dragging: extend to include
// a word.
if (LT_POS(curwin->w_cursor, orig_cursor))
{
find_start_of_word(&curwin->w_cursor);
find_end_of_word(&VIsual);
}
else
{
find_start_of_word(&VIsual);
if (*p_sel == 'e' && *ml_get_cursor() != NUL)
curwin->w_cursor.col +=
(*mb_ptr2len)(ml_get_cursor());
find_end_of_word(&curwin->w_cursor);
}
}
curwin->w_set_curswant = TRUE;
}
if (is_click)
redraw_curbuf_later(UPD_INVERTED); // update the inversion
}
else if (VIsual_active && !old_active)
{
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
else
VIsual_mode = 'v';
}
// If Visual mode changed show it later.
if ((!VIsual_active && old_active && mode_displayed)
|| (VIsual_active && p_smd && msg_silent == 0
&& (!old_active || VIsual_mode != old_mode)))
redraw_cmdline = TRUE;
return moved;
}
|
340201685272816729984528939326600503133
|
mouse.c
|
56805804002879785388836197750941387525
|
CWE-703
|
CVE-2022-2980
|
NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-2980
|
209,801
|
mujs
|
f5b3c703e18725e380b83427004632e744f85a6f
|
https://github.com/ccxvii/mujs
|
https://github.com/ccxvii/mujs/commit/f5b3c703e18725e380b83427004632e744f85a6f
|
Issue #161: Cope with empty programs in mujs-pp.
| 1
|
void jsP_dumpsyntax(js_State *J, js_Ast *prog, int dominify)
{
minify = dominify;
if (prog->type == AST_LIST)
pstmlist(-1, prog);
else {
pstm(0, prog);
nl();
}
if (minify > 1)
putchar('\n');
}
|
236329653693817075818818411816465624514
|
jsdump.c
|
195852189272926394340196020756121895406
|
CWE-476
|
CVE-2022-30975
|
In Artifex MuJS through 1.2.0, jsP_dumpsyntax in jsdump.c has a NULL pointer dereference, as demonstrated by mujs-pp.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-30975
|
421,378
|
mujs
|
f5b3c703e18725e380b83427004632e744f85a6f
|
https://github.com/ccxvii/mujs
|
https://github.com/ccxvii/mujs/commit/f5b3c703e18725e380b83427004632e744f85a6f
|
Issue #161: Cope with empty programs in mujs-pp.
| 0
|
void jsP_dumpsyntax(js_State *J, js_Ast *prog, int dominify)
{
minify = dominify;
if (prog) {
if (prog->type == AST_LIST)
pstmlist(-1, prog);
else {
pstm(0, prog);
nl();
}
}
if (minify > 1)
putchar('\n');
}
|
148093103302179844815401983905255483216
|
jsdump.c
|
205390724250782891362749099686890673449
|
CWE-476
|
CVE-2022-30975
|
In Artifex MuJS through 1.2.0, jsP_dumpsyntax in jsdump.c has a NULL pointer dereference, as demonstrated by mujs-pp.
|
https://nvd.nist.gov/vuln/detail/CVE-2022-30975
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.