func_before
stringlengths 10
482k
| func_after
stringlengths 14
484k
| cve_id
stringlengths 13
28
⌀ | cwe_id
stringclasses 776
values | cve_description
stringlengths 30
3.31k
⌀ | commit_link
stringlengths 48
164
⌀ | commit_message
stringlengths 1
30.3k
⌀ | file_name
stringlengths 4
244
⌀ | extension
stringclasses 20
values | datetime
stringdate 1999-11-10 02:42:49
2024-01-29 16:00:57
⌀ |
|---|---|---|---|---|---|---|---|---|---|
public void test_like_startsWith() {
Entity from = from(Entity.class);
where(from.getCode()).like().startsWith("test");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where entity_0.code like 'test%'", select.getQuery());
}
|
public void test_like_startsWith() {
Entity from = from(Entity.class);
where(from.getCode()).like().startsWith("test");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where entity_0.code like :code_1", select.getQuery());
assertEquals("test%", select.getParameters().get("code_1"));
}
|
CVE-2019-11343
|
NVD-CWE-noinfo
|
Torpedo Query before 2.5.3 mishandles the LIKE operator in ConditionBuilder.java, LikeCondition.java, and NotLikeCondition.java.
|
https://github.com/xjodoin/torpedoquery/commit/3c20b874fba9cc2a78b9ace10208de1602b56c3f
|
Fix issue with like
|
ConditionBuilder.java
|
java
|
2020-03-12T21:15:00Z
|
@Nullable
public String getSourceSpawnerName(){
String spawnerName = this.sourceSpawnerName;
if (this.sourceSpawnerName == null){
synchronized (livingEntity.getPersistentDataContainer()){
if (getPDC().has(main.namespaced_keys.sourceSpawnerName, PersistentDataType.STRING))
spawnerName = getPDC().get(main.namespaced_keys.sourceSpawnerName, PersistentDataType.STRING);
}
if (spawnerName == null){
this.sourceSpawnerName = "(none)";
spawnerName = this.sourceSpawnerName;
}
}
return spawnerName;
}
|
@Nullable
public String getSourceSpawnerName(){
if (this.sourceSpawnerName != null) return this.sourceSpawnerName;
if (getPDCLock()) {
try {
if (getPDC().has(main.namespaced_keys.sourceSpawnerName, PersistentDataType.STRING))
this.sourceSpawnerName = getPDC().get(main.namespaced_keys.sourceSpawnerName, PersistentDataType.STRING);
} finally {
releasePDCLock();
}
}
if (this.sourceSpawnerName == null)
this.sourceSpawnerName = "(none)";
return this.sourceSpawnerName;
}
| null | null | null |
https://github.com/ArcanePlugins/LevelledMobs/commit/b6f820e0e861b368623996b006c6b6300b6eadc0
|
3.3.0 b574
* when using any of the new variables `%home_distance%`, `%home_distance_with_bed%`, `%bed_distance%` and the player is in nether, if no bed or home location is present then the portal they entered the nether from is utilised
* improved locking code to prevent potential server crashes / hangs
* added LM 3.2.6 code changes
|
src/main/java/me/lokka30/levelledmobs/misc/LivingEntityWrapper.java
|
java
|
2021-11-29T15:53:33Z
|
int WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids)
{
uint32_t flags, bps = 0;
uint32_t chan_mask = config->channel_mask;
int num_chans = config->num_channels;
int i;
wpc->stream_version = (config->flags & CONFIG_COMPATIBLE_WRITE) ? CUR_STREAM_VERS : MAX_STREAM_VERS;
if ((config->qmode & QMODE_DSD_AUDIO) && config->bytes_per_sample == 1 && config->bits_per_sample == 8) {
#ifdef ENABLE_DSD
wpc->dsd_multiplier = 1;
flags = DSD_FLAG;
for (i = 14; i >= 0; --i)
if (config->sample_rate % sample_rates [i] == 0) {
int divisor = config->sample_rate / sample_rates [i];
if (divisor && (divisor & (divisor - 1)) == 0) {
config->sample_rate /= divisor;
wpc->dsd_multiplier = divisor;
break;
}
}
if (config->flags & CONFIG_HYBRID_FLAG) {
strcpy (wpc->error_message, "hybrid mode not available for DSD!");
return FALSE;
}
config->flags &= (CONFIG_HIGH_FLAG | CONFIG_MD5_CHECKSUM | CONFIG_PAIR_UNDEF_CHANS);
config->float_norm_exp = config->xmode = 0;
#else
strcpy (wpc->error_message, "libwavpack not configured for DSD!");
return FALSE;
#endif
}
else
flags = config->bytes_per_sample - 1;
wpc->total_samples = total_samples;
wpc->config.sample_rate = config->sample_rate;
wpc->config.num_channels = config->num_channels;
wpc->config.channel_mask = config->channel_mask;
wpc->config.bits_per_sample = config->bits_per_sample;
wpc->config.bytes_per_sample = config->bytes_per_sample;
wpc->config.block_samples = config->block_samples;
wpc->config.flags = config->flags;
wpc->config.qmode = config->qmode;
if (config->flags & CONFIG_VERY_HIGH_FLAG)
wpc->config.flags |= CONFIG_HIGH_FLAG;
for (i = 0; i < 15; ++i)
if (wpc->config.sample_rate == sample_rates [i])
break;
flags |= i << SRATE_LSB;
if (!(flags & DSD_FLAG)) {
if (config->float_norm_exp) {
wpc->config.float_norm_exp = config->float_norm_exp;
wpc->config.flags |= CONFIG_FLOAT_DATA;
flags |= FLOAT_DATA;
}
else
flags |= ((config->bytes_per_sample * 8) - config->bits_per_sample) << SHIFT_LSB;
if (config->flags & CONFIG_HYBRID_FLAG) {
flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE;
if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) {
wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) {
wpc->config.shaping_weight = config->shaping_weight;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
if (wpc->config.flags & (CONFIG_CROSS_DECORR | CONFIG_OPTIMIZE_WVC))
flags |= CROSS_DECORR;
if (config->flags & CONFIG_BITRATE_KBPS) {
bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5);
if (bps > (64 << 8))
bps = 64 << 8;
}
else
bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5);
}
else
flags |= CROSS_DECORR;
if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO))
flags |= JOINT_STEREO;
if (config->flags & CONFIG_CREATE_WVC)
wpc->wvc_flag = TRUE;
}
if (chan_ids) {
int lastchan = 0, mask_copy = chan_mask;
if ((int) strlen ((char *) chan_ids) > num_chans) { // can't be more than num channels!
strcpy (wpc->error_message, "chan_ids longer than num channels!");
return FALSE;
}
while (*chan_ids)
if (*chan_ids <= 32 && *chan_ids > lastchan && (mask_copy & (1 << (*chan_ids-1)))) {
mask_copy &= ~(1 << (*chan_ids-1));
lastchan = *chan_ids++;
}
else
break;
for (i = 0; chan_ids [i]; i++)
if (chan_ids [i] != 0xff) {
wpc->channel_identities = (unsigned char *) strdup ((char *) chan_ids);
break;
}
}
for (wpc->current_stream = 0; num_chans; wpc->current_stream++) {
WavpackStream *wps = malloc (sizeof (WavpackStream));
unsigned char left_chan_id = 0, right_chan_id = 0;
int pos, chans = 1;
wpc->streams = realloc (wpc->streams, (wpc->current_stream + 1) * sizeof (wpc->streams [0]));
wpc->streams [wpc->current_stream] = wps;
CLEAR (*wps);
if (chan_mask)
for (pos = 0; pos < 32; ++pos)
if (chan_mask & (1 << pos)) {
if (left_chan_id) {
right_chan_id = pos + 1;
break;
}
else {
chan_mask &= ~(1 << pos);
left_chan_id = pos + 1;
}
}
while (!right_chan_id && chan_ids && *chan_ids)
if (left_chan_id)
right_chan_id = *chan_ids;
else
left_chan_id = *chan_ids++;
if (!left_chan_id)
left_chan_id = right_chan_id = 0xff;
else if (!right_chan_id)
right_chan_id = 0xff;
if (num_chans >= 2) {
if ((config->flags & CONFIG_PAIR_UNDEF_CHANS) && left_chan_id == 0xff && right_chan_id == 0xff)
chans = 2;
else
for (i = 0; i < NUM_STEREO_PAIRS; ++i)
if ((left_chan_id == stereo_pairs [i].a && right_chan_id == stereo_pairs [i].b) ||
(left_chan_id == stereo_pairs [i].b && right_chan_id == stereo_pairs [i].a)) {
if (right_chan_id <= 32 && (chan_mask & (1 << (right_chan_id-1))))
chan_mask &= ~(1 << (right_chan_id-1));
else if (chan_ids && *chan_ids == right_chan_id)
chan_ids++;
chans = 2;
break;
}
}
num_chans -= chans;
if (num_chans && wpc->current_stream == NEW_MAX_STREAMS - 1)
break;
memcpy (wps->wphdr.ckID, "wvpk", 4);
wps->wphdr.ckSize = sizeof (WavpackHeader) - 8;
SET_TOTAL_SAMPLES (wps->wphdr, wpc->total_samples);
wps->wphdr.version = wpc->stream_version;
wps->wphdr.flags = flags;
wps->bits = bps;
if (!wpc->current_stream)
wps->wphdr.flags |= INITIAL_BLOCK;
if (!num_chans)
wps->wphdr.flags |= FINAL_BLOCK;
if (chans == 1) {
wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE);
wps->wphdr.flags |= MONO_FLAG;
}
}
wpc->num_streams = wpc->current_stream;
wpc->current_stream = 0;
if (num_chans) {
strcpy (wpc->error_message, "too many channels!");
return FALSE;
}
if (config->flags & CONFIG_EXTRA_MODE)
wpc->config.xmode = config->xmode ? config->xmode : 1;
return TRUE;
}
|
int WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids)
{
uint32_t flags, bps = 0;
uint32_t chan_mask = config->channel_mask;
int num_chans = config->num_channels;
int i;
if (!config->sample_rate) {
strcpy (wpc->error_message, "sample rate cannot be zero!");
return FALSE;
}
wpc->stream_version = (config->flags & CONFIG_COMPATIBLE_WRITE) ? CUR_STREAM_VERS : MAX_STREAM_VERS;
if ((config->qmode & QMODE_DSD_AUDIO) && config->bytes_per_sample == 1 && config->bits_per_sample == 8) {
#ifdef ENABLE_DSD
wpc->dsd_multiplier = 1;
flags = DSD_FLAG;
for (i = 14; i >= 0; --i)
if (config->sample_rate % sample_rates [i] == 0) {
int divisor = config->sample_rate / sample_rates [i];
if (divisor && (divisor & (divisor - 1)) == 0) {
config->sample_rate /= divisor;
wpc->dsd_multiplier = divisor;
break;
}
}
if (config->flags & CONFIG_HYBRID_FLAG) {
strcpy (wpc->error_message, "hybrid mode not available for DSD!");
return FALSE;
}
config->flags &= (CONFIG_HIGH_FLAG | CONFIG_MD5_CHECKSUM | CONFIG_PAIR_UNDEF_CHANS);
config->float_norm_exp = config->xmode = 0;
#else
strcpy (wpc->error_message, "libwavpack not configured for DSD!");
return FALSE;
#endif
}
else
flags = config->bytes_per_sample - 1;
wpc->total_samples = total_samples;
wpc->config.sample_rate = config->sample_rate;
wpc->config.num_channels = config->num_channels;
wpc->config.channel_mask = config->channel_mask;
wpc->config.bits_per_sample = config->bits_per_sample;
wpc->config.bytes_per_sample = config->bytes_per_sample;
wpc->config.block_samples = config->block_samples;
wpc->config.flags = config->flags;
wpc->config.qmode = config->qmode;
if (config->flags & CONFIG_VERY_HIGH_FLAG)
wpc->config.flags |= CONFIG_HIGH_FLAG;
for (i = 0; i < 15; ++i)
if (wpc->config.sample_rate == sample_rates [i])
break;
flags |= i << SRATE_LSB;
if (!(flags & DSD_FLAG)) {
if (config->float_norm_exp) {
wpc->config.float_norm_exp = config->float_norm_exp;
wpc->config.flags |= CONFIG_FLOAT_DATA;
flags |= FLOAT_DATA;
}
else
flags |= ((config->bytes_per_sample * 8) - config->bits_per_sample) << SHIFT_LSB;
if (config->flags & CONFIG_HYBRID_FLAG) {
flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE;
if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) {
wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) {
wpc->config.shaping_weight = config->shaping_weight;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
if (wpc->config.flags & (CONFIG_CROSS_DECORR | CONFIG_OPTIMIZE_WVC))
flags |= CROSS_DECORR;
if (config->flags & CONFIG_BITRATE_KBPS) {
bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5);
if (bps > (64 << 8))
bps = 64 << 8;
}
else
bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5);
}
else
flags |= CROSS_DECORR;
if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO))
flags |= JOINT_STEREO;
if (config->flags & CONFIG_CREATE_WVC)
wpc->wvc_flag = TRUE;
}
if (chan_ids) {
int lastchan = 0, mask_copy = chan_mask;
if ((int) strlen ((char *) chan_ids) > num_chans) { // can't be more than num channels!
strcpy (wpc->error_message, "chan_ids longer than num channels!");
return FALSE;
}
while (*chan_ids)
if (*chan_ids <= 32 && *chan_ids > lastchan && (mask_copy & (1 << (*chan_ids-1)))) {
mask_copy &= ~(1 << (*chan_ids-1));
lastchan = *chan_ids++;
}
else
break;
for (i = 0; chan_ids [i]; i++)
if (chan_ids [i] != 0xff) {
wpc->channel_identities = (unsigned char *) strdup ((char *) chan_ids);
break;
}
}
for (wpc->current_stream = 0; num_chans; wpc->current_stream++) {
WavpackStream *wps = malloc (sizeof (WavpackStream));
unsigned char left_chan_id = 0, right_chan_id = 0;
int pos, chans = 1;
wpc->streams = realloc (wpc->streams, (wpc->current_stream + 1) * sizeof (wpc->streams [0]));
wpc->streams [wpc->current_stream] = wps;
CLEAR (*wps);
if (chan_mask)
for (pos = 0; pos < 32; ++pos)
if (chan_mask & (1 << pos)) {
if (left_chan_id) {
right_chan_id = pos + 1;
break;
}
else {
chan_mask &= ~(1 << pos);
left_chan_id = pos + 1;
}
}
while (!right_chan_id && chan_ids && *chan_ids)
if (left_chan_id)
right_chan_id = *chan_ids;
else
left_chan_id = *chan_ids++;
if (!left_chan_id)
left_chan_id = right_chan_id = 0xff;
else if (!right_chan_id)
right_chan_id = 0xff;
if (num_chans >= 2) {
if ((config->flags & CONFIG_PAIR_UNDEF_CHANS) && left_chan_id == 0xff && right_chan_id == 0xff)
chans = 2;
else
for (i = 0; i < NUM_STEREO_PAIRS; ++i)
if ((left_chan_id == stereo_pairs [i].a && right_chan_id == stereo_pairs [i].b) ||
(left_chan_id == stereo_pairs [i].b && right_chan_id == stereo_pairs [i].a)) {
if (right_chan_id <= 32 && (chan_mask & (1 << (right_chan_id-1))))
chan_mask &= ~(1 << (right_chan_id-1));
else if (chan_ids && *chan_ids == right_chan_id)
chan_ids++;
chans = 2;
break;
}
}
num_chans -= chans;
if (num_chans && wpc->current_stream == NEW_MAX_STREAMS - 1)
break;
memcpy (wps->wphdr.ckID, "wvpk", 4);
wps->wphdr.ckSize = sizeof (WavpackHeader) - 8;
SET_TOTAL_SAMPLES (wps->wphdr, wpc->total_samples);
wps->wphdr.version = wpc->stream_version;
wps->wphdr.flags = flags;
wps->bits = bps;
if (!wpc->current_stream)
wps->wphdr.flags |= INITIAL_BLOCK;
if (!num_chans)
wps->wphdr.flags |= FINAL_BLOCK;
if (chans == 1) {
wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE);
wps->wphdr.flags |= MONO_FLAG;
}
}
wpc->num_streams = wpc->current_stream;
wpc->current_stream = 0;
if (num_chans) {
strcpy (wpc->error_message, "too many channels!");
return FALSE;
}
if (config->flags & CONFIG_EXTRA_MODE)
wpc->config.xmode = config->xmode ? config->xmode : 1;
return TRUE;
}
|
CVE-2018-19840
|
CWE-835
|
The function WavpackPackInit in pack_utils.c in libwavpack.a in WavPack through 5.1.0 allows attackers to cause a denial-of-service (resource exhaustion caused by an infinite loop) via a crafted wav audio file because WavpackSetConfiguration64 mishandles a sample rate of zero.
|
https://github.com/dbry/WavPack/commit/070ef6f138956d9ea9612e69586152339dbefe51
|
issue #53: error out on zero sample rate
|
src/pack_utils.c
|
c
|
2018-11-30T05:00:42Z
|
isdn_ppp_ioctl(int min, struct file *file, unsigned int cmd, unsigned long arg)
{
unsigned long val;
int r, i, j;
struct ippp_struct *is;
isdn_net_local *lp;
struct isdn_ppp_comp_data data;
void __user *argp = (void __user *)arg;
is = file->private_data;
lp = is->lp;
if (is->debug & 0x1)
printk(KERN_DEBUG "isdn_ppp_ioctl: minor: %d cmd: %x state: %x\n", min, cmd, is->state);
if (!(is->state & IPPP_OPEN))
return -EINVAL;
switch (cmd) {
case PPPIOCBUNDLE:
#ifdef CONFIG_ISDN_MPP
if (!(is->state & IPPP_CONNECT))
return -EINVAL;
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
printk(KERN_DEBUG "iPPP-bundle: minor: %d, slave unit: %d, master unit: %d\n",
(int) min, (int) is->unit, (int) val);
return isdn_ppp_bundle(is, val);
#else
return -1;
#endif
break;
case PPPIOCGUNIT: /* get ppp/isdn unit number */
if ((r = set_arg(argp, &is->unit, sizeof(is->unit))))
return r;
break;
case PPPIOCGIFNAME:
if (!lp)
return -EINVAL;
if ((r = set_arg(argp, lp->netdev->dev->name,
strlen(lp->netdev->dev->name))))
return r;
break;
case PPPIOCGMPFLAGS: /* get configuration flags */
if ((r = set_arg(argp, &is->mpppcfg, sizeof(is->mpppcfg))))
return r;
break;
case PPPIOCSMPFLAGS: /* set configuration flags */
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
is->mpppcfg = val;
break;
case PPPIOCGFLAGS: /* get configuration flags */
if ((r = set_arg(argp, &is->pppcfg, sizeof(is->pppcfg))))
return r;
break;
case PPPIOCSFLAGS: /* set configuration flags */
if ((r = get_arg(argp, &val, sizeof(val)))) {
return r;
}
if (val & SC_ENABLE_IP && !(is->pppcfg & SC_ENABLE_IP) && (is->state & IPPP_CONNECT)) {
if (lp) {
/* OK .. we are ready to send buffers */
is->pppcfg = val; /* isdn_ppp_xmit test for SC_ENABLE_IP !!! */
netif_wake_queue(lp->netdev->dev);
break;
}
}
is->pppcfg = val;
break;
case PPPIOCGIDLE: /* get idle time information */
if (lp) {
struct ppp_idle pidle;
pidle.xmit_idle = pidle.recv_idle = lp->huptimer;
if ((r = set_arg(argp, &pidle, sizeof(struct ppp_idle))))
return r;
}
break;
case PPPIOCSMRU: /* set receive unit size for PPP */
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
is->mru = val;
break;
case PPPIOCSMPMRU:
break;
case PPPIOCSMPMTU:
break;
case PPPIOCSMAXCID: /* set the maximum compression slot id */
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
val++;
if (is->maxcid != val) {
#ifdef CONFIG_ISDN_PPP_VJ
struct slcompress *sltmp;
#endif
if (is->debug & 0x1)
printk(KERN_DEBUG "ippp, ioctl: changed MAXCID to %ld\n", val);
is->maxcid = val;
#ifdef CONFIG_ISDN_PPP_VJ
sltmp = slhc_init(16, val);
if (!sltmp) {
printk(KERN_ERR "ippp, can't realloc slhc struct\n");
return -ENOMEM;
}
if (is->slcomp)
slhc_free(is->slcomp);
is->slcomp = sltmp;
#endif
}
break;
case PPPIOCGDEBUG:
if ((r = set_arg(argp, &is->debug, sizeof(is->debug))))
return r;
break;
case PPPIOCSDEBUG:
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
is->debug = val;
break;
case PPPIOCGCOMPRESSORS:
{
unsigned long protos[8] = {0,};
struct isdn_ppp_compressor *ipc = ipc_head;
while (ipc) {
j = ipc->num / (sizeof(long) * 8);
i = ipc->num % (sizeof(long) * 8);
if (j < 8)
protos[j] |= (1UL << i);
ipc = ipc->next;
}
if ((r = set_arg(argp, protos, 8 * sizeof(long))))
return r;
}
break;
case PPPIOCSCOMPRESSOR:
if ((r = get_arg(argp, &data, sizeof(struct isdn_ppp_comp_data))))
return r;
return isdn_ppp_set_compressor(is, &data);
case PPPIOCGCALLINFO:
{
struct pppcallinfo pci;
memset((char *)&pci, 0, sizeof(struct pppcallinfo));
if (lp)
{
strncpy(pci.local_num, lp->msn, 63);
if (lp->dial) {
strncpy(pci.remote_num, lp->dial->num, 63);
}
pci.charge_units = lp->charge;
if (lp->outgoing)
pci.calltype = CALLTYPE_OUTGOING;
else
pci.calltype = CALLTYPE_INCOMING;
if (lp->flags & ISDN_NET_CALLBACK)
pci.calltype |= CALLTYPE_CALLBACK;
}
return set_arg(argp, &pci, sizeof(struct pppcallinfo));
}
#ifdef CONFIG_IPPP_FILTER
case PPPIOCSPASS:
{
struct sock_fprog_kern fprog;
struct sock_filter *code;
int err, len = get_filter(argp, &code);
if (len < 0)
return len;
fprog.len = len;
fprog.filter = code;
if (is->pass_filter) {
bpf_prog_destroy(is->pass_filter);
is->pass_filter = NULL;
}
if (fprog.filter != NULL)
err = bpf_prog_create(&is->pass_filter, &fprog);
else
err = 0;
kfree(code);
return err;
}
case PPPIOCSACTIVE:
{
struct sock_fprog_kern fprog;
struct sock_filter *code;
int err, len = get_filter(argp, &code);
if (len < 0)
return len;
fprog.len = len;
fprog.filter = code;
if (is->active_filter) {
bpf_prog_destroy(is->active_filter);
is->active_filter = NULL;
}
if (fprog.filter != NULL)
err = bpf_prog_create(&is->active_filter, &fprog);
else
err = 0;
kfree(code);
return err;
}
#endif /* CONFIG_IPPP_FILTER */
default:
break;
}
return 0;
}
|
isdn_ppp_ioctl(int min, struct file *file, unsigned int cmd, unsigned long arg)
{
unsigned long val;
int r, i, j;
struct ippp_struct *is;
isdn_net_local *lp;
struct isdn_ppp_comp_data data;
void __user *argp = (void __user *)arg;
is = file->private_data;
lp = is->lp;
if (is->debug & 0x1)
printk(KERN_DEBUG "isdn_ppp_ioctl: minor: %d cmd: %x state: %x\n", min, cmd, is->state);
if (!(is->state & IPPP_OPEN))
return -EINVAL;
switch (cmd) {
case PPPIOCBUNDLE:
#ifdef CONFIG_ISDN_MPP
if (!(is->state & IPPP_CONNECT))
return -EINVAL;
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
printk(KERN_DEBUG "iPPP-bundle: minor: %d, slave unit: %d, master unit: %d\n",
(int) min, (int) is->unit, (int) val);
return isdn_ppp_bundle(is, val);
#else
return -1;
#endif
break;
case PPPIOCGUNIT: /* get ppp/isdn unit number */
if ((r = set_arg(argp, &is->unit, sizeof(is->unit))))
return r;
break;
case PPPIOCGIFNAME:
if (!lp)
return -EINVAL;
if ((r = set_arg(argp, lp->netdev->dev->name,
strlen(lp->netdev->dev->name))))
return r;
break;
case PPPIOCGMPFLAGS: /* get configuration flags */
if ((r = set_arg(argp, &is->mpppcfg, sizeof(is->mpppcfg))))
return r;
break;
case PPPIOCSMPFLAGS: /* set configuration flags */
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
is->mpppcfg = val;
break;
case PPPIOCGFLAGS: /* get configuration flags */
if ((r = set_arg(argp, &is->pppcfg, sizeof(is->pppcfg))))
return r;
break;
case PPPIOCSFLAGS: /* set configuration flags */
if ((r = get_arg(argp, &val, sizeof(val)))) {
return r;
}
if (val & SC_ENABLE_IP && !(is->pppcfg & SC_ENABLE_IP) && (is->state & IPPP_CONNECT)) {
if (lp) {
/* OK .. we are ready to send buffers */
is->pppcfg = val; /* isdn_ppp_xmit test for SC_ENABLE_IP !!! */
netif_wake_queue(lp->netdev->dev);
break;
}
}
is->pppcfg = val;
break;
case PPPIOCGIDLE: /* get idle time information */
if (lp) {
struct ppp_idle pidle;
pidle.xmit_idle = pidle.recv_idle = lp->huptimer;
if ((r = set_arg(argp, &pidle, sizeof(struct ppp_idle))))
return r;
}
break;
case PPPIOCSMRU: /* set receive unit size for PPP */
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
is->mru = val;
break;
case PPPIOCSMPMRU:
break;
case PPPIOCSMPMTU:
break;
case PPPIOCSMAXCID: /* set the maximum compression slot id */
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
val++;
if (is->maxcid != val) {
#ifdef CONFIG_ISDN_PPP_VJ
struct slcompress *sltmp;
#endif
if (is->debug & 0x1)
printk(KERN_DEBUG "ippp, ioctl: changed MAXCID to %ld\n", val);
is->maxcid = val;
#ifdef CONFIG_ISDN_PPP_VJ
sltmp = slhc_init(16, val);
if (IS_ERR(sltmp))
return PTR_ERR(sltmp);
if (is->slcomp)
slhc_free(is->slcomp);
is->slcomp = sltmp;
#endif
}
break;
case PPPIOCGDEBUG:
if ((r = set_arg(argp, &is->debug, sizeof(is->debug))))
return r;
break;
case PPPIOCSDEBUG:
if ((r = get_arg(argp, &val, sizeof(val))))
return r;
is->debug = val;
break;
case PPPIOCGCOMPRESSORS:
{
unsigned long protos[8] = {0,};
struct isdn_ppp_compressor *ipc = ipc_head;
while (ipc) {
j = ipc->num / (sizeof(long) * 8);
i = ipc->num % (sizeof(long) * 8);
if (j < 8)
protos[j] |= (1UL << i);
ipc = ipc->next;
}
if ((r = set_arg(argp, protos, 8 * sizeof(long))))
return r;
}
break;
case PPPIOCSCOMPRESSOR:
if ((r = get_arg(argp, &data, sizeof(struct isdn_ppp_comp_data))))
return r;
return isdn_ppp_set_compressor(is, &data);
case PPPIOCGCALLINFO:
{
struct pppcallinfo pci;
memset((char *)&pci, 0, sizeof(struct pppcallinfo));
if (lp)
{
strncpy(pci.local_num, lp->msn, 63);
if (lp->dial) {
strncpy(pci.remote_num, lp->dial->num, 63);
}
pci.charge_units = lp->charge;
if (lp->outgoing)
pci.calltype = CALLTYPE_OUTGOING;
else
pci.calltype = CALLTYPE_INCOMING;
if (lp->flags & ISDN_NET_CALLBACK)
pci.calltype |= CALLTYPE_CALLBACK;
}
return set_arg(argp, &pci, sizeof(struct pppcallinfo));
}
#ifdef CONFIG_IPPP_FILTER
case PPPIOCSPASS:
{
struct sock_fprog_kern fprog;
struct sock_filter *code;
int err, len = get_filter(argp, &code);
if (len < 0)
return len;
fprog.len = len;
fprog.filter = code;
if (is->pass_filter) {
bpf_prog_destroy(is->pass_filter);
is->pass_filter = NULL;
}
if (fprog.filter != NULL)
err = bpf_prog_create(&is->pass_filter, &fprog);
else
err = 0;
kfree(code);
return err;
}
case PPPIOCSACTIVE:
{
struct sock_fprog_kern fprog;
struct sock_filter *code;
int err, len = get_filter(argp, &code);
if (len < 0)
return len;
fprog.len = len;
fprog.filter = code;
if (is->active_filter) {
bpf_prog_destroy(is->active_filter);
is->active_filter = NULL;
}
if (fprog.filter != NULL)
err = bpf_prog_create(&is->active_filter, &fprog);
else
err = 0;
kfree(code);
return err;
}
#endif /* CONFIG_IPPP_FILTER */
default:
break;
}
return 0;
}
|
CVE-2015-7799
| null |
The slhc_init function in drivers/net/slip/slhc.c in the Linux kernel through 4.2.3 does not ensure that certain slot numbers are valid, which allows local users to cause a denial of service (NULL pointer dereference and system crash) via a crafted PPPIOCSMAXCID ioctl call.
|
http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/drivers/net/slip/slhc.c?id=4ab42d78e37a294ac7bc56901d563c642e03c4ae
|
ppp, slip: Validate VJ compression slot parameters completely
Currently slhc_init() treats out-of-range values of rslots and tslots
as equivalent to 0, except that if tslots is too large it will
dereference a null pointer (CVE-2015-7799).
Add a range-check at the top of the function and make it return an
ERR_PTR() on error instead of NULL. Change the callers accordingly.
Compile-tested only.
Reported-by: 郭永刚 <guoyonggang@360.cn>
References: http://article.gmane.org/gmane.comp.security.oss.general/17908
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Signed-off-by: David S. Miller <davem@davemloft.net>
| null | null | null |
public void trimChangedTagNamesValues() {
Entity entity = getEntity();
if (entity == null) {
return;
}
Set<String> changedTags = new HashSet<>(entity.getChangedTags());
if (!Algorithms.isEmpty(changedTags)) {
for (String changedTag : changedTags) {
if (changedTag == null || changedTag.trim().equals(changedTag)) {
continue;
}
String trimmedTag = changedTag.trim();
changedTags.add(trimmedTag);
changedTags.remove(changedTag);
String tagValue = entity.getTag(trimmedTag);
entity.putTag(trimmedTag, Algorithms.trimIfNotNull(tagValue));
entity.removeTag(changedTag);
}
entity.setChangedTags(changedTags);
}
}
|
public void trimChangedTagNamesValues() {
Entity entity = getEntity();
if (entity == null || entity.getChangedTags() == null) {
return;
}
Set<String> changedTags = new HashSet<>(entity.getChangedTags());
if (!Algorithms.isEmpty(changedTags)) {
for (String changedTag : changedTags) {
if (changedTag == null || changedTag.trim().equals(changedTag)) {
continue;
}
String trimmedTag = changedTag.trim();
changedTags.add(trimmedTag);
changedTags.remove(changedTag);
String tagValue = entity.getTag(trimmedTag);
entity.putTag(trimmedTag, Algorithms.trimIfNotNull(tagValue));
entity.removeTag(changedTag);
}
entity.setChangedTags(changedTags);
}
}
| null | null | null |
https://github.com/osmandapp/OsmAnd/commit/31ad764da69284c64be01b06290a56af99d23dd1
|
Fix #15245 CRASH on upload new POI
|
OsmAnd/src/net/osmand/plus/plugins/osmedit/data/OpenstreetmapPoint.java
|
java
|
2022-09-19T17:32:38Z
|
@Override
public int suggestedInternalSecurityLevel() {
// invoked after nextTurn() processing is complete on each civ's turn
// also invoked when contact is made in mid-turn
// return from 0 to 40, which translates to 0% to 20% of total prod
//
// modnar: is it not 0% to 10% of total prod, for a max of +20% security bonus, with 0 to 10 ticks/clicks?
// MAX_SECURITY_TICKS = 10 in model/empires/Empire.java
int paranoia = 0;
boolean alone = true;
for (EmpireView cv : empire.empireViews()) {
if ((cv != null) && cv.embassy().contact()) {
//ail: only panic when I'm technologically ahead and don't have the computer-tech to cover it
int shouldPanicThreshold = 0;
shouldPanicThreshold += empire.tech().avgTechLevel();
shouldPanicThreshold -= cv.empire().tech().avgTechLevel();
shouldPanicThreshold += cv.empire().tech().computer().techLevel();
shouldPanicThreshold -= empire.tech().computer().techLevel();
alone = false;
if(shouldPanicThreshold > 0)
{
if (cv.embassy().anyWar())
paranoia += 3; // modnar: more internal security paranoia
if (cv.embassy().noTreaty())
paranoia += 2; // modnar: more internal security paranoia
}
}
}
if ((paranoia == 0) && !alone)
paranoia++;
if (empire.leader().isXenophobic())
paranoia *= 2;
//ail: Only do periodical spy-sweeps, 30% of the time should be fine
if(random() < 0.7)
{
paranoia = 0;
}
return min(10, paranoia); // modnar: change max to 10, MAX_SECURITY_TICKS = 10
}
|
@Override
public int suggestedInternalSecurityLevel() {
// invoked after nextTurn() processing is complete on each civ's turn
// also invoked when contact is made in mid-turn
// return from 0 to 40, which translates to 0% to 20% of total prod
//
// modnar: is it not 0% to 10% of total prod, for a max of +20% security bonus, with 0 to 10 ticks/clicks?
// MAX_SECURITY_TICKS = 10 in model/empires/Empire.java
int paranoia = 0;
boolean alone = true;
for (EmpireView cv : empire.empireViews()) {
if ((cv != null) && cv.embassy().contact() && cv.inEconomicRange()) {
//ail: only panic when I'm technologically ahead and don't have the computer-tech to cover it
int shouldPanicThreshold = 0;
shouldPanicThreshold += empire.tech().avgTechLevel();
shouldPanicThreshold -= cv.empire().tech().avgTechLevel();
shouldPanicThreshold += cv.empire().tech().computer().techLevel();
shouldPanicThreshold -= empire.tech().computer().techLevel();
alone = false;
if(shouldPanicThreshold > 0)
{
if (cv.embassy().anyWar())
paranoia += 3; // modnar: more internal security paranoia
if (cv.embassy().noTreaty())
paranoia += 2; // modnar: more internal security paranoia
}
}
}
if ((paranoia == 0) && !alone)
paranoia++;
//ail: Only do periodical spy-sweeps, 30% of the time should be fine
if(random() < 0.7)
{
paranoia = 0;
}
return min(10, paranoia); // modnar: change max to 10, MAX_SECURITY_TICKS = 10
}
| null | null | null |
https://github.com/rayfowler/rotp-public/commit/e4239ef2d2162d2bc31a5bb2a6aa9134034aa7e6
|
Xilmi ai (#45)
* Replaced many isPlayer() by isPlayerControlled()
This leads to a more fluent experience on AutoPlay.
Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown.
* Orion-guard-handling
Avoid sending colonization-fleets, when guardian is still alive
Increase guardian-power-estimate to 100,000
Don't send and count bombers towards guardian-defeat-force
* Fixed Crash from a report on reddit
Not sure how that could happen though. Never had this issue in games started on my computer.
* Fixed crash after AI defeats orion-guard
Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it.
* All the forgotten isPlayer()-calls
Including the Base- and Modnar-AI-Diplomat
* Personalities now play a role in my AI once again
Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less.
* Fixed issue where enemy-fleets weren's seen, when they actually were.
Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them.
* Update AIDiplomat.java
* Delete ShipCombatResults.java
* Delete Empire.java
* Delete TradeRoute.java
* Revert "Delete TradeRoute.java"
This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83.
* Revert "Delete Empire.java"
This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35.
* Revert "Delete ShipCombatResults.java"
This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5.
* Update ShipCombatResults.java
reverting pull-request... manually because I don't know of a better way 8[
* Update Empire.java
* Update TradeRoute.java
* Merge with Master
* Update TradeRoute.java
* Update TradeRoute.java
github editor does not allow me to remove a newline oO
* AI improvements
Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships.
Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for.
Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs.
Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot.
Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed.
* Update OrionGuardianShip.java
Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>
|
src/rotp/model/ai/xilmi/AISpyMaster.java
|
java
|
2021-03-26T15:26:00Z
|
public static int canRestrictMember (TdApi.ChatMemberStatus me, TdApi.ChatMemberStatus him) {
if (him.getConstructor() == TdApi.ChatMemberStatusCreator.CONSTRUCTOR) {
return RESTRICT_MODE_NONE;
}
switch (me.getConstructor()) {
case TdApi.ChatMemberStatusCreator.CONSTRUCTOR:
switch (him.getConstructor()) {
case TdApi.ChatMemberStatusBanned.CONSTRUCTOR:
case TdApi.ChatMemberStatusRestricted.CONSTRUCTOR:
return RESTRICT_MODE_EDIT;
default:
return RESTRICT_MODE_NEW;
}
case TdApi.ChatMemberStatusAdministrator.CONSTRUCTOR:
if (((TdApi.ChatMemberStatusAdministrator) me).canRestrictMembers) {
switch (him.getConstructor()) {
case TdApi.ChatMemberStatusAdministrator.CONSTRUCTOR:
if (((TdApi.ChatMemberStatusAdministrator) him).canBeEdited) {
return RESTRICT_MODE_NEW;
} else {
return RESTRICT_MODE_NONE;
}
case TdApi.ChatMemberStatusRestricted.CONSTRUCTOR:
case TdApi.ChatMemberStatusBanned.CONSTRUCTOR:
return RESTRICT_MODE_EDIT;
case TdApi.ChatMemberStatusMember.CONSTRUCTOR:
return RESTRICT_MODE_NEW;
}
}
break;
default:
if (him.getConstructor() == TdApi.ChatMemberStatusRestricted.CONSTRUCTOR) {
return RESTRICT_MODE_VIEW;
}
break;
}
return RESTRICT_MODE_NONE;
}
|
public static int canRestrictMember (TdApi.ChatMemberStatus me, TdApi.ChatMemberStatus him) {
if (him.getConstructor() == TdApi.ChatMemberStatusCreator.CONSTRUCTOR) {
return RESTRICT_MODE_NONE;
}
switch (me.getConstructor()) {
case TdApi.ChatMemberStatusCreator.CONSTRUCTOR:
switch (him.getConstructor()) {
case TdApi.ChatMemberStatusBanned.CONSTRUCTOR:
case TdApi.ChatMemberStatusRestricted.CONSTRUCTOR:
return RESTRICT_MODE_EDIT;
default:
return RESTRICT_MODE_NEW;
}
case TdApi.ChatMemberStatusAdministrator.CONSTRUCTOR:
if (((TdApi.ChatMemberStatusAdministrator) me).canRestrictMembers) {
switch (him.getConstructor()) {
case TdApi.ChatMemberStatusAdministrator.CONSTRUCTOR:
if (((TdApi.ChatMemberStatusAdministrator) him).canBeEdited) {
return RESTRICT_MODE_NEW;
} else {
return RESTRICT_MODE_NONE;
}
case TdApi.ChatMemberStatusRestricted.CONSTRUCTOR:
case TdApi.ChatMemberStatusBanned.CONSTRUCTOR:
return RESTRICT_MODE_EDIT;
case TdApi.ChatMemberStatusMember.CONSTRUCTOR:
case TdApi.ChatMemberStatusLeft.CONSTRUCTOR:
return RESTRICT_MODE_NEW;
case TdApi.ChatMemberStatusCreator.CONSTRUCTOR:
return RESTRICT_MODE_NONE;
}
}
break;
default:
if (him.getConstructor() == TdApi.ChatMemberStatusRestricted.CONSTRUCTOR) {
return RESTRICT_MODE_VIEW;
}
break;
}
return RESTRICT_MODE_NONE;
}
| null | null | null |
https://github.com/TGX-Android/Telegram-X/commit/4ac723c4100ee888b9e0f01ddcf44a259d81d73c
|
fixed crash when deleting messages from different senders in supergroups + added managing admin rights in message menu + improved banning/unbanning chats + fixed unavailable save button when changing only blocked date + fixed screenshot availability for chat preview + other bugfixes
|
app/src/main/java/org/thunderdog/challegram/data/TD.java
|
java
|
2021-12-12T01:41:10Z
|
QPDF::resolveObjectsInStream(int obj_stream_number)
{
// Force resolution of object stream
QPDFObjectHandle obj_stream = getObjectByID(obj_stream_number, 0);
if (! obj_stream.isStream())
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"supposed object stream " +
QUtil::int_to_string(obj_stream_number) +
" is not a stream");
}
// For linearization data in the object, use the data from the
// object stream for the objects in the stream.
QPDFObjGen stream_og(obj_stream_number, 0);
qpdf_offset_t end_before_space =
this->m->obj_cache[stream_og].end_before_space;
qpdf_offset_t end_after_space =
this->m->obj_cache[stream_og].end_after_space;
QPDFObjectHandle dict = obj_stream.getDict();
if (! (dict.getKey("/Type").isName() &&
dict.getKey("/Type").getName() == "/ObjStm"))
{
QTC::TC("qpdf", "QPDF ERR object stream with wrong type");
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"supposed object stream " +
QUtil::int_to_string(obj_stream_number) +
" has wrong type");
}
if (! (dict.getKey("/N").isInteger() &&
dict.getKey("/First").isInteger()))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"object stream " +
QUtil::int_to_string(obj_stream_number) +
" has incorrect keys");
}
int n = dict.getKey("/N").getIntValue();
int first = dict.getKey("/First").getIntValue();
std::map<int, int> offsets;
PointerHolder<Buffer> bp = obj_stream.getStreamData(qpdf_dl_specialized);
PointerHolder<InputSource> input = new BufferInputSource(
this->m->file->getName() +
" object stream " + QUtil::int_to_string(obj_stream_number),
bp.getPointer());
for (int i = 0; i < n; ++i)
{
QPDFTokenizer::Token tnum = readToken(input);
QPDFTokenizer::Token toffset = readToken(input);
if (! ((tnum.getType() == QPDFTokenizer::tt_integer) &&
(toffset.getType() == QPDFTokenizer::tt_integer)))
{
throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),
this->m->last_object_description,
input->getLastOffset(),
"expected integer in object stream header");
}
int num = QUtil::string_to_int(tnum.getValue().c_str());
int offset = QUtil::string_to_ll(toffset.getValue().c_str());
offsets[num] = offset + first;
}
// To avoid having to read the object stream multiple times, store
// all objects that would be found here in the cache. Remember
// that some objects stored here might have been overridden by new
// objects appended to the file, so it is necessary to recheck the
// xref table and only cache what would actually be resolved here.
for (std::map<int, int>::iterator iter = offsets.begin();
iter != offsets.end(); ++iter)
{
int obj = (*iter).first;
QPDFObjGen og(obj, 0);
QPDFXRefEntry const& entry = this->m->xref_table[og];
if ((entry.getType() == 2) &&
(entry.getObjStreamNumber() == obj_stream_number))
{
int offset = (*iter).second;
input->seek(offset, SEEK_SET);
QPDFObjectHandle oh = readObject(input, "", obj, 0, true);
this->m->obj_cache[og] =
ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh),
end_before_space, end_after_space);
}
else
{
QTC::TC("qpdf", "QPDF not caching overridden objstm object");
}
}
}
|
QPDF::resolveObjectsInStream(int obj_stream_number)
{
// Force resolution of object stream
QPDFObjectHandle obj_stream = getObjectByID(obj_stream_number, 0);
if (! obj_stream.isStream())
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"supposed object stream " +
QUtil::int_to_string(obj_stream_number) +
" is not a stream");
}
// For linearization data in the object, use the data from the
// object stream for the objects in the stream.
QPDFObjGen stream_og(obj_stream_number, 0);
qpdf_offset_t end_before_space =
this->m->obj_cache[stream_og].end_before_space;
qpdf_offset_t end_after_space =
this->m->obj_cache[stream_og].end_after_space;
QPDFObjectHandle dict = obj_stream.getDict();
if (! (dict.getKey("/Type").isName() &&
dict.getKey("/Type").getName() == "/ObjStm"))
{
QTC::TC("qpdf", "QPDF ERR object stream with wrong type");
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"supposed object stream " +
QUtil::int_to_string(obj_stream_number) +
" has wrong type");
}
if (! (dict.getKey("/N").isInteger() &&
dict.getKey("/First").isInteger()))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"object stream " +
QUtil::int_to_string(obj_stream_number) +
" has incorrect keys");
}
int n = dict.getKey("/N").getIntValueAsInt();
int first = dict.getKey("/First").getIntValueAsInt();
std::map<int, int> offsets;
PointerHolder<Buffer> bp = obj_stream.getStreamData(qpdf_dl_specialized);
PointerHolder<InputSource> input = new BufferInputSource(
this->m->file->getName() +
" object stream " + QUtil::int_to_string(obj_stream_number),
bp.getPointer());
for (int i = 0; i < n; ++i)
{
QPDFTokenizer::Token tnum = readToken(input);
QPDFTokenizer::Token toffset = readToken(input);
if (! ((tnum.getType() == QPDFTokenizer::tt_integer) &&
(toffset.getType() == QPDFTokenizer::tt_integer)))
{
throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),
this->m->last_object_description,
input->getLastOffset(),
"expected integer in object stream header");
}
int num = QUtil::string_to_int(tnum.getValue().c_str());
int offset = QUtil::string_to_int(toffset.getValue().c_str());
offsets[num] = offset + first;
}
// To avoid having to read the object stream multiple times, store
// all objects that would be found here in the cache. Remember
// that some objects stored here might have been overridden by new
// objects appended to the file, so it is necessary to recheck the
// xref table and only cache what would actually be resolved here.
for (std::map<int, int>::iterator iter = offsets.begin();
iter != offsets.end(); ++iter)
{
int obj = (*iter).first;
QPDFObjGen og(obj, 0);
QPDFXRefEntry const& entry = this->m->xref_table[og];
if ((entry.getType() == 2) &&
(entry.getObjStreamNumber() == obj_stream_number))
{
int offset = (*iter).second;
input->seek(offset, SEEK_SET);
QPDFObjectHandle oh = readObject(input, "", obj, 0, true);
this->m->obj_cache[og] =
ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh),
end_before_space, end_after_space);
}
else
{
QTC::TC("qpdf", "QPDF not caching overridden objstm object");
}
}
}
| null |
CWE-787
| null |
https://github.com/qpdf/qpdf/commit/d71f05ca07eb5c7cfa4d6d23e5c1f2a800f52e8e
|
Fix sign and conversion warnings (major)
This makes all integer type conversions that have potential data loss
explicit with calls that do range checks and raise an exception. After
this commit, qpdf builds with no warnings when -Wsign-conversion
-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used
with MSVC. This significantly reduces the likelihood of potential
crashes from bogus integer values.
There are some parts of the code that take int when they should take
size_t or an offset. Such places would make qpdf not support files
with more than 2^31 of something that usually wouldn't be so large. In
the event that such a file shows up and is valid, at least qpdf would
raise an error in the right spot so the issue could be legitimately
addressed rather than failing in some weird way because of a silent
overflow condition.
| null | null |
2019-06-21T03:35:23Z
|
static DataSource lookupDataSource(Hints hints) throws FactoryException {
Object hint = hints.get(Hints.EPSG_DATA_SOURCE);
if (hint instanceof DataSource) {
return (DataSource) hint;
} else if (hint instanceof String) {
String name = (String) hint;
InitialContext context;
try {
context = GeoTools.getInitialContext();
// name = GeoTools.fixName( context, name );
return (DataSource) context.lookup(name);
} catch (Exception e) {
throw new FactoryException("EPSG_DATA_SOURCE '" + name + "' not found:" + e, e);
}
}
throw new FactoryException("EPSG_DATA_SOURCE must be provided");
}
|
static DataSource lookupDataSource(Hints hints) throws FactoryException {
Object hint = hints.get(Hints.EPSG_DATA_SOURCE);
if (hint instanceof DataSource) {
return (DataSource) hint;
} else if (hint instanceof String) {
String name = (String) hint;
try {
return (DataSource) GeoTools.jndiLookup(name);
} catch (Exception e) {
throw new FactoryException("EPSG_DATA_SOURCE '" + name + "' not found:" + e, e);
}
}
throw new FactoryException("EPSG_DATA_SOURCE must be provided");
}
|
CVE-2022-24818
|
CWE-917,CWE-20
|
GeoTools is an open source Java library that provides tools for geospatial data. The GeoTools library has a number of data sources that can perform unchecked JNDI lookups, which in turn can be used to perform class deserialization and result in arbitrary code execution. Similar to the Log4J case, the vulnerability can be triggered if the JNDI names are user-provided, but requires admin-level login to be triggered. The lookups are now restricted in GeoTools 26.4, GeoTools 25.6, and GeoTools 24.6. Users unable to upgrade should ensure that any downstream application should not allow usage of remotely provided JNDI strings.
|
https://github.com/geotools/geotools/commit/4f70fa3234391dd0cda883a20ab0ec75688cba49
|
[GEOT-7115] Streamline JNDI lookups
|
AbstractEpsgMediator.java
|
java
|
2022-04-13T21:15:00Z
|
vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif )
{
VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif );
GifFileType *file = gif->file;
ColorMapObject *map = file->Image.ColorMap ?
file->Image.ColorMap : file->SColorMap;
GifByteType *extension;
if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) {
vips_foreign_load_gif_error( gif );
return( -1 );
}
/* Check that the frame looks sane. Perhaps giflib checks
* this for us.
*/
if( file->Image.Left < 0 ||
file->Image.Width < 1 ||
file->Image.Width > 10000 ||
file->Image.Left + file->Image.Width > file->SWidth ||
file->Image.Top < 0 ||
file->Image.Height < 1 ||
file->Image.Height > 10000 ||
file->Image.Top + file->Image.Height > file->SHeight ) {
vips_error( class->nickname, "%s", _( "bad frame size" ) );
return( -1 );
}
/* Test for a non-greyscale colourmap for this frame.
*/
if( !gif->has_colour &&
map ) {
int i;
for( i = 0; i < map->ColorCount; i++ )
if( map->Colors[i].Red != map->Colors[i].Green ||
map->Colors[i].Green != map->Colors[i].Blue ) {
gif->has_colour = TRUE;
break;
}
}
/* Step over compressed image data.
*/
do {
if( vips_foreign_load_gif_code_next( gif, &extension ) )
return( -1 );
} while( extension != NULL );
return( 0 );
}
|
vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif )
{
VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif );
GifFileType *file = gif->file;
ColorMapObject *map;
GifByteType *extension;
if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) {
vips_foreign_load_gif_error( gif );
return( -1 );
}
/* Check that the frame looks sane. Perhaps giflib checks
* this for us.
*/
if( file->Image.Left < 0 ||
file->Image.Width < 1 ||
file->Image.Width > 10000 ||
file->Image.Left + file->Image.Width > file->SWidth ||
file->Image.Top < 0 ||
file->Image.Height < 1 ||
file->Image.Height > 10000 ||
file->Image.Top + file->Image.Height > file->SHeight ) {
vips_error( class->nickname, "%s", _( "bad frame size" ) );
return( -1 );
}
/* Test for a non-greyscale colourmap for this frame.
*/
map = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap;
if( !gif->has_colour &&
map ) {
int i;
for( i = 0; i < map->ColorCount; i++ )
if( map->Colors[i].Red != map->Colors[i].Green ||
map->Colors[i].Green != map->Colors[i].Blue ) {
gif->has_colour = TRUE;
break;
}
}
/* Step over compressed image data.
*/
do {
if( vips_foreign_load_gif_code_next( gif, &extension ) )
return( -1 );
} while( extension != NULL );
return( 0 );
}
|
CVE-2019-17534
|
CWE-416
|
vips_foreign_load_gif_scan_image in foreign/gifload.c in libvips before 8.8.2 tries to access a color map before a DGifGetImageDesc call, leading to a use-after-free.
|
https://github.com/libvips/libvips/commit/ce684dd008532ea0bf9d4a1d89bacb35f4a83f4d
|
fetch map after DGifGetImageDesc()
Earlier refactoring broke GIF map fetch.
|
gifload.c
|
c
|
2019-08-27T11:50:52Z
|
I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
base::Unretained(this)));
}
|
I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage", "i18n",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage", "i18n",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage", "i18n",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
base::Unretained(this)));
}
|
CVE-2016-1696
|
CWE-254,CWE-284
|
The extensions subsystem in Google Chrome before 51.0.2704.79 does not properly restrict bindings access, which allows remote attackers to bypass the Same Origin Policy via unspecified vectors.
|
https://github.com/chromium/chromium/commit/c0569cc04741cccf6548c2169fcc1609d958523f
|
[Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
|
extensions/renderer/i18n_custom_bindings.cc
|
cc
|
2016-04-15T21:51:21Z
|
uppdateCard(id, asked, answered) {
this.get(
`SELECT * FROM flashcards WHERE id="${id}"`,
(err, card) => {
if (!card || !card.id) throw 'could not update the card';
this.run(`REPLACE INTO flashcards VALUES(${card.id}, ${card.user}, "${card.text}", "${card.translation}", ${asked}, ${answered})`);
}
);
}
|
uppdateCard(id, asked, answered) {
this.get(
'SELECT * FROM flashcards WHERE id = ?',
[id],
(err, card) => {
if (!card || !card.id) throw 'could not update the card';
this.run(
'REPLACE INTO flashcards VALUES(?, ?, ?, ?, ?, ?)',
[card.id, card.user, card.text, card.translation, asked, answered]
);
}
);
}
|
CVE-2019-15561
|
CWE-89
|
FlashLingo before 2019-06-12 allows SQL injection, related to flashlingo.js and db.js.
|
https://github.com/vpoliakov/FlashLingo/commit/42537d90087a920210048d6fe32c2d8c801790b9
|
Fixes for sql injection and app rerendering
|
db.js
|
js
|
2019-06-12T20:55:08Z
|
int ipmi_destroy_user(struct ipmi_user *user)
{
_ipmi_destroy_user(user);
cleanup_srcu_struct(&user->release_barrier);
kref_put(&user->refcount, free_user);
return 0;
}
|
int ipmi_destroy_user(struct ipmi_user *user)
{
_ipmi_destroy_user(user);
kref_put(&user->refcount, free_user);
return 0;
}
| null |
CWE-416, CWE-284
| null |
https://github.com/torvalds/linux/commit/77f8269606bf95fcb232ee86f6da80886f1dfae8
|
ipmi: fix use-after-free of user->release_barrier.rda
When we do the following test, we got oops in ipmi_msghandler driver
while((1))
do
service ipmievd restart & service ipmievd restart
done
---------------------------------------------------------------
[ 294.230186] Unable to handle kernel paging request at virtual address 0000803fea6ea008
[ 294.230188] Mem abort info:
[ 294.230190] ESR = 0x96000004
[ 294.230191] Exception class = DABT (current EL), IL = 32 bits
[ 294.230193] SET = 0, FnV = 0
[ 294.230194] EA = 0, S1PTW = 0
[ 294.230195] Data abort info:
[ 294.230196] ISV = 0, ISS = 0x00000004
[ 294.230197] CM = 0, WnR = 0
[ 294.230199] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000a1c1b75a
[ 294.230201] [0000803fea6ea008] pgd=0000000000000000
[ 294.230204] Internal error: Oops: 96000004 [#1] SMP
[ 294.235211] Modules linked in: nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm iw_cm dm_mirror dm_region_hash dm_log dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce sha2_ce ses sha256_arm64 sha1_ce hibmc_drm hisi_sas_v2_hw enclosure sg hisi_sas_main sbsa_gwdt ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe ipmi_si mdio hns_dsaf ipmi_devintf ipmi_msghandler hns_enet_drv hns_mdio
[ 294.277745] CPU: 3 PID: 0 Comm: swapper/3 Kdump: loaded Not tainted 5.0.0-rc2+ #113
[ 294.285511] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 294.292835] pstate: 80000005 (Nzcv daif -PAN -UAO)
[ 294.297695] pc : __srcu_read_lock+0x38/0x58
[ 294.301940] lr : acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.307853] sp : ffff00001001bc80
[ 294.311208] x29: ffff00001001bc80 x28: ffff0000117e5000
[ 294.316594] x27: 0000000000000000 x26: dead000000000100
[ 294.321980] x25: dead000000000200 x24: ffff803f6bd06800
[ 294.327366] x23: 0000000000000000 x22: 0000000000000000
[ 294.332752] x21: ffff00001001bd04 x20: ffff80df33d19018
[ 294.338137] x19: ffff80df33d19018 x18: 0000000000000000
[ 294.343523] x17: 0000000000000000 x16: 0000000000000000
[ 294.348908] x15: 0000000000000000 x14: 0000000000000002
[ 294.354293] x13: 0000000000000000 x12: 0000000000000000
[ 294.359679] x11: 0000000000000000 x10: 0000000000100000
[ 294.365065] x9 : 0000000000000000 x8 : 0000000000000004
[ 294.370451] x7 : 0000000000000000 x6 : ffff80df34558678
[ 294.375836] x5 : 000000000000000c x4 : 0000000000000000
[ 294.381221] x3 : 0000000000000001 x2 : 0000803fea6ea000
[ 294.386607] x1 : 0000803fea6ea008 x0 : 0000000000000001
[ 294.391994] Process swapper/3 (pid: 0, stack limit = 0x0000000083087293)
[ 294.398791] Call trace:
[ 294.401266] __srcu_read_lock+0x38/0x58
[ 294.405154] acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.410716] deliver_response+0x80/0xf8 [ipmi_msghandler]
[ 294.416189] deliver_local_response+0x28/0x68 [ipmi_msghandler]
[ 294.422193] handle_one_recv_msg+0x158/0xcf8 [ipmi_msghandler]
[ 294.432050] handle_new_recv_msgs+0xc0/0x210 [ipmi_msghandler]
[ 294.441984] smi_recv_tasklet+0x8c/0x158 [ipmi_msghandler]
[ 294.451618] tasklet_action_common.isra.5+0x88/0x138
[ 294.460661] tasklet_action+0x2c/0x38
[ 294.468191] __do_softirq+0x120/0x2f8
[ 294.475561] irq_exit+0x134/0x140
[ 294.482445] __handle_domain_irq+0x6c/0xc0
[ 294.489954] gic_handle_irq+0xb8/0x178
[ 294.497037] el1_irq+0xb0/0x140
[ 294.503381] arch_cpu_idle+0x34/0x1a8
[ 294.510096] do_idle+0x1d4/0x290
[ 294.516322] cpu_startup_entry+0x28/0x30
[ 294.523230] secondary_start_kernel+0x184/0x1d0
[ 294.530657] Code: d538d082 d2800023 8b010c81 8b020021 (c85f7c25)
[ 294.539746] ---[ end trace 8a7a880dee570b29 ]---
[ 294.547341] Kernel panic - not syncing: Fatal exception in interrupt
[ 294.556837] SMP: stopping secondary CPUs
[ 294.563996] Kernel Offset: disabled
[ 294.570515] CPU features: 0x002,21006008
[ 294.577638] Memory Limit: none
[ 294.587178] Starting crashdump kernel...
[ 294.594314] Bye!
Because the user->release_barrier.rda is freed in ipmi_destroy_user(), but
the refcount is not zero, when acquire_ipmi_user() uses user->release_barrier.rda
in __srcu_read_lock(), it causes oops.
Fix this by calling cleanup_srcu_struct() when the refcount is zero.
Fixes: e86ee2d44b44 ("ipmi: Rework locking and shutdown for hot remove")
Cc: stable@vger.kernel.org # 4.18
Signed-off-by: Yang Yingliang <yangyingliang@huawei.com>
Signed-off-by: Corey Minyard <cminyard@mvista.com>
| null | null |
2019-01-16T05:33:22Z
|
static void chomp3(ChannelData *ctx, int16_t *output, uint8_t val,
const uint16_t tab1[],
const int16_t *tab2, int tab2_stride,
uint32_t numChannels)
{
int16_t current;
current = tab2[((ctx->index & 0x7f0) >> 4)*tab2_stride + val];
current = mace_broken_clip_int16(current + ctx->lev);
ctx->lev = current - (current >> 3);
*output = QT_8S_2_16S(current);
if (( ctx->index += tab1[val]-(ctx->index >> 5) ) < 0)
ctx->index = 0;
}
|
static void chomp3(ChannelData *ctx, int16_t *output, uint8_t val,
const uint16_t tab1[],
const int16_t *tab2, int tab2_stride,
uint32_t numChannels)
{
int16_t current;
if (val < tab2_stride)
current = tab2[((ctx->index & 0x7f0) >> 4)*tab2_stride + val];
else
current = - 1 - tab2[((ctx->index & 0x7f0) >> 4)*tab2_stride + 2*tab2_stride-val-1];
current = mace_broken_clip_int16(current + ctx->lev);
ctx->lev = current - (current >> 3);
*output = QT_8S_2_16S(current);
if (( ctx->index += tab1[val]-(ctx->index >> 5) ) < 0)
ctx->index = 0;
}
| null | null | null |
FFmpeg/commit/f36aec3b5e18c4c167612d0051a6d5b6144b3552
|
Exploit symmetry to reduce size of tables by half.
Originally committed as revision 15255 to svn://svn.ffmpeg.org/ffmpeg/trunk
|
./ffmpeg/libavcodec/mace.c
|
c
|
2008-09-07T17:20:55Z
|
def _clean_code(self, code: str) -> str:
"""
A method to clean the code to prevent malicious code execution
Args:
code(str): A python code
Returns (str): Returns a Clean Code String
"""
tree = ast.parse(code)
new_body = []
# clear recent optional dependencies
self._additional_dependencies = []
for node in tree.body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
self._check_imports(node)
continue
if self._is_df_overwrite(node):
continue
new_body.append(node)
new_tree = ast.Module(body=new_body)
return astor.to_source(new_tree, pretty_source=lambda x: "".join(x)).strip()
|
def _clean_code(self, code: str) -> str:
"""
A method to clean the code to prevent malicious code execution
Args:
code(str): A python code
Returns (str): Returns a Clean Code String
"""
tree = ast.parse(code)
new_body = []
# clear recent optional dependencies
self._additional_dependencies = []
for node in tree.body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
self._check_imports(node)
continue
if self._is_df_overwrite(node) or self._is_jailbreak(node):
continue
new_body.append(node)
new_tree = ast.Module(body=new_body)
return astor.to_source(new_tree, pretty_source=lambda x: "".join(x)).strip()
| null | null | null |
https://github.com/gventuri/pandas-ai/commit/3aac79be8fc1d18b53d66a566adddbbdd2b38ad5
|
fix: bypass the security check with prompt injection (#399) (#409)
|
pandasai/__init__.py
|
py
|
2023-07-28T23:29:40Z
|
void Messageheader::Parser::checkHeaderspace(unsigned chars) const
{
if (headerdataPtr + chars >= header.rawdata + sizeof(header.rawdata))
throw HttpError(HTTP_REQUEST_ENTITY_TOO_LARGE, "header too large");
}
|
void Messageheader::Parser::checkHeaderspace(unsigned chars) const
{
if (headerdataPtr + chars >= header.rawdata + sizeof(header.rawdata))
{
header.rawdata[sizeof(header.rawdata) - 1] = '\0';
throw HttpError(HTTP_REQUEST_ENTITY_TOO_LARGE, "header too large");
}
}
|
CVE-2013-7299
|
CWE-200
|
framework/common/messageheaderparser.cpp in Tntnet before 2.2.1 allows remote attackers to obtain sensitive information via a header that ends in \n instead of \r\n, which prevents a null terminator from being added and causes Tntnet to include headers from other requests.
|
https://github.com/maekitalo/tntnet/commit/9bd3b14042e12d84f39ea9f55731705ba516f525
|
fix possible information leak
| null | null |
2013-12-11T13:59:32Z
|
public static String loadTextFile(BufferedReader iStream) throws IOException {
StringWriter buffer = null;
PrintWriter writer = null;
try {
buffer = new StringWriter();
writer = new PrintWriter(buffer);
String line = null;
while ((line = iStream.readLine()) != null)
writer.println(line);
writer.flush();
} catch (IOException exc) {
throw exc;
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
}
}
}
return buffer.toString();
}
|
public static String loadTextFile(BufferedReader iStream) throws IOException {
try (StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer);) {
String line = null;
while ((line = iStream.readLine()) != null) {
writer.println(line);
}
return buffer.toString();
}
}
| null | null | null |
https://github.com/apache/uima-uimaj/commit/aeb44042110b2e5876437126d496633fff1cc091
|
Merge pull request #145 from apache/bugfix/UIMA-6387-Update-p2-repo-URLs-from-http-to-https
[UIMA-6387] Update p2 repo URLs from http to https
|
uimaj-core/src/main/java/org/apache/uima/pear/util/FileUtil.java
|
java
|
2023-01-24T07:25:16Z
|
static unsigned int XBMInteger(Image *image,short int *hex_digits)
{
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadBlobByte(image);
if (c == EOF)
return(0);
} while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
/*
Evaluate number.
*/
value=0;
while (hex_digits[c] >= 0) {
if (value > (unsigned int) (INT_MAX/10))
break;
value*=16;
c&=0xff;
if (value > (unsigned int) (INT_MAX-hex_digits[c]))
break;
value+=hex_digits[c];
c=ReadBlobByte(image);
if (c == EOF)
return(0);
}
return(value);
}
|
static int XBMInteger(Image *image,short int *hex_digits)
{
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadBlobByte(image);
if (c == EOF)
return(-1);
} while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
/*
Evaluate number.
*/
value=0;
while (hex_digits[c] >= 0) {
if (value > (unsigned int) (INT_MAX/10))
break;
value*=16;
c&=0xff;
if (value > (unsigned int) (INT_MAX-hex_digits[c]))
break;
value+=hex_digits[c];
c=ReadBlobByte(image);
if (c == EOF)
return(-1);
}
return((int) value);
}
| null | null | null |
https://github.com/ImageMagick/ImageMagick/commit/b8c63b156bf26b52e710b1a0643c846a6cd01e56
|
https://github.com/ImageMagick/ImageMagick/issues/712
|
coders/xbm.c
|
c
|
2017-08-31T13:10:37Z
|
public function dump($value)
{
$dumper = $this->getDumper();
if ($dumper) {
// re-use the same DumpOutput instance, so it won't re-render the global styles/scripts on each dump.
// exclude verbose information (e.g. exception stack traces)
if (class_exists('Symfony\Component\VarDumper\Caster\Caster')) {
$cloneVar = $this->getCloner()->cloneVar($value, Caster::EXCLUDE_VERBOSE);
// Symfony VarDumper 2.6 Caster class dont exist.
} else {
$cloneVar = $this->getCloner()->cloneVar($value);
}
$dumper->dump(
$cloneVar,
$this->htmlDumperOutput
);
$output = $this->htmlDumperOutput->getOutput();
$this->htmlDumperOutput->clear();
return $output;
}
return print_r($value, true);
}
|
public function dump($value)
{
$dumper = $this->getDumper();
if ($dumper) {
// re-use the same DumpOutput instance, so it won't re-render the global styles/scripts on each dump.
// exclude verbose information (e.g. exception stack traces)
if (class_exists('Symfony\Component\VarDumper\Caster\Caster')) {
$cloneVar = $this->getCloner()->cloneVar($value, Caster::EXCLUDE_VERBOSE);
// Symfony VarDumper 2.6 Caster class dont exist.
} else {
$cloneVar = $this->getCloner()->cloneVar($value);
}
$dumper->dump(
$cloneVar,
$this->htmlDumperOutput
);
$output = $this->htmlDumperOutput->getOutput();
$this->htmlDumperOutput->clear();
return $output;
}
return htmlspecialchars(print_r($value, true));
}
|
CVE-2017-16880
|
CWE-79
|
The dump function in Util/TemplateHelper.php in filp whoops before 2.1.13 has XSS.
|
https://github.com/filp/whoops/commit/c16791d28d1ca3139e398145f0c6565c523c291a
|
TemplateHelper: fix XSS if Symfony dumper is not available
|
TemplateHelper.php
|
php
|
2017-11-17T21:29:00Z
|
static int vvfat_open(BlockDriverState *bs, QDict *options, int flags)
{
BDRVVVFATState *s = bs->opaque;
int cyls, heads, secs;
bool floppy;
const char *dirname;
QemuOpts *opts;
Error *local_err = NULL;
int ret;
#ifdef DEBUG
vvv = s;
#endif
DLOG(if (stderr == NULL) {
stderr = fopen("vvfat.log", "a");
setbuf(stderr, NULL);
})
opts = qemu_opts_create_nofail(&runtime_opts);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (error_is_set(&local_err)) {
qerror_report_err(local_err);
error_free(local_err);
ret = -EINVAL;
goto fail;
}
dirname = qemu_opt_get(opts, "dir");
if (!dirname) {
qerror_report(ERROR_CLASS_GENERIC_ERROR, "vvfat block driver requires "
"a 'dir' option");
ret = -EINVAL;
goto fail;
}
s->fat_type = qemu_opt_get_number(opts, "fat-type", 0);
floppy = qemu_opt_get_bool(opts, "floppy", false);
if (floppy) {
if (!s->fat_type) {
s->fat_type = 12;
secs = 36;
s->sectors_per_cluster = 2;
} else {
secs = s->fat_type == 12 ? 18 : 36;
s->sectors_per_cluster = 1;
}
s->first_sectors_number = 1;
cyls = 80;
heads = 2;
} else {
if (!s->fat_type) {
s->fat_type = 16;
}
cyls = s->fat_type == 12 ? 64 : 1024;
heads = 16;
secs = 63;
}
switch (s->fat_type) {
case 32:
fprintf(stderr, "Big fat greek warning: FAT32 has not been tested. "
"You are welcome to do so!\n");
break;
case 16:
case 12:
break;
default:
qerror_report(ERROR_CLASS_GENERIC_ERROR, "Valid FAT types are only "
"12, 16 and 32");
ret = -EINVAL;
goto fail;
}
s->bs = bs;
s->sectors_per_cluster=0x10;
s->current_cluster=0xffffffff;
s->first_sectors_number=0x40;
bs->read_only = 1;
s->qcow = s->write_target = NULL;
s->qcow_filename = NULL;
s->fat2 = NULL;
s->downcase_short_names = 1;
fprintf(stderr, "vvfat %s chs %d,%d,%d\n",
dirname, cyls, heads, secs);
s->sector_count = cyls * heads * secs - (s->first_sectors_number - 1);
if (qemu_opt_get_bool(opts, "rw", false)) {
if (enable_write_target(s)) {
ret = -EIO;
goto fail;
}
bs->read_only = 0;
}
bs->total_sectors = cyls * heads * secs;
if (init_directories(s, dirname, heads, secs)) {
ret = -EIO;
goto fail;
}
s->sector_count = s->faked_sectors + s->sectors_per_cluster*s->cluster_count;
if (s->first_sectors_number == 0x40) {
init_mbr(s, cyls, heads, secs);
}
qemu_co_mutex_init(&s->lock);
if (s->qcow) {
error_set(&s->migration_blocker,
QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
"vvfat (rw)", bs->device_name, "live migration");
migrate_add_blocker(s->migration_blocker);
}
ret = 0;
fail:
qemu_opts_del(opts);
return ret;
}
|
static int vvfat_open(BlockDriverState *bs, QDict *options, int flags)
{
BDRVVVFATState *s = bs->opaque;
int cyls, heads, secs;
bool floppy;
const char *dirname;
QemuOpts *opts;
Error *local_err = NULL;
int ret;
#ifdef DEBUG
vvv = s;
#endif
DLOG(if (stderr == NULL) {
stderr = fopen("vvfat.log", "a");
setbuf(stderr, NULL);
})
opts = qemu_opts_create_nofail(&runtime_opts);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (error_is_set(&local_err)) {
qerror_report_err(local_err);
error_free(local_err);
ret = -EINVAL;
goto fail;
}
dirname = qemu_opt_get(opts, "dir");
if (!dirname) {
qerror_report(ERROR_CLASS_GENERIC_ERROR, "vvfat block driver requires "
"a 'dir' option");
ret = -EINVAL;
goto fail;
}
s->fat_type = qemu_opt_get_number(opts, "fat-type", 0);
floppy = qemu_opt_get_bool(opts, "floppy", false);
if (floppy) {
if (!s->fat_type) {
s->fat_type = 12;
secs = 36;
s->sectors_per_cluster = 2;
} else {
secs = s->fat_type == 12 ? 18 : 36;
s->sectors_per_cluster = 1;
}
s->first_sectors_number = 1;
cyls = 80;
heads = 2;
} else {
if (!s->fat_type) {
s->fat_type = 16;
}
cyls = s->fat_type == 12 ? 64 : 1024;
heads = 16;
secs = 63;
}
switch (s->fat_type) {
case 32:
fprintf(stderr, "Big fat greek warning: FAT32 has not been tested. "
"You are welcome to do so!\n");
break;
case 16:
case 12:
break;
default:
qerror_report(ERROR_CLASS_GENERIC_ERROR, "Valid FAT types are only "
"12, 16 and 32");
ret = -EINVAL;
goto fail;
}
s->bs = bs;
s->sectors_per_cluster=0x10;
s->current_cluster=0xffffffff;
s->first_sectors_number=0x40;
bs->read_only = 1;
s->qcow = s->write_target = NULL;
s->qcow_filename = NULL;
s->fat2 = NULL;
s->downcase_short_names = 1;
fprintf(stderr, "vvfat %s chs %d,%d,%d\n",
dirname, cyls, heads, secs);
s->sector_count = cyls * heads * secs - (s->first_sectors_number - 1);
if (qemu_opt_get_bool(opts, "rw", false)) {
ret = enable_write_target(s);
if (ret < 0) {
goto fail;
}
bs->read_only = 0;
}
bs->total_sectors = cyls * heads * secs;
if (init_directories(s, dirname, heads, secs)) {
ret = -EIO;
goto fail;
}
s->sector_count = s->faked_sectors + s->sectors_per_cluster*s->cluster_count;
if (s->first_sectors_number == 0x40) {
init_mbr(s, cyls, heads, secs);
}
qemu_co_mutex_init(&s->lock);
if (s->qcow) {
error_set(&s->migration_blocker,
QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
"vvfat (rw)", bs->device_name, "live migration");
migrate_add_blocker(s->migration_blocker);
}
ret = 0;
fail:
qemu_opts_del(opts);
return ret;
}
| null | null | null |
qemu/commit/78f27bd02ceba4a2f6ac5c725f4d4410eec205ef
|
block: fix vvfat error path for enable_write_target
s->qcow and s->qcow_filename are allocated but not freed on error. Fix the
possible leaks, remove unnecessary check for bdrv_new(), propagate ret code of
bdrv_create() and also the one of enable_write_target().
Signed-off-by: Fam Zheng <famz@redhat.com>
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
|
./qemu/block/vvfat.c
|
c
|
2013-07-17T09:57:37Z
|
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));
break;
}
} else {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ZVAL_FALSE(&ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i+1]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
i++;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
|
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));
break;
}
} else {
ZVAL_FALSE(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i+1]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
i++;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
|
CVE-2017-11143
|
CWE-502
|
In PHP before 5.6.31, an invalid free in the WDDX deserialization of boolean parameters could be used by attackers able to inject XML for deserialization to crash the PHP interpreter, related to an invalid free for an empty boolean element in ext/wddx/wddx.c.
|
https://git.php.net/?p=php-src.git;a=commit;h=2aae60461c2ff7b7fbcdd194c789ac841d0747d7
| null | null | null | null |
bool IsIdentityConsumingSwitch(const MutableGraphView& graph,
const NodeDef& node) {
if ((IsIdentity(node) || IsIdentityNSingleInput(node)) &&
node.input_size() > 0) {
TensorId tensor_id = ParseTensorName(node.input(0));
if (IsTensorIdControlling(tensor_id)) {
return false;
}
NodeDef* input_node = graph.GetNode(tensor_id.node());
return IsSwitch(*input_node);
}
return false;
}
|
bool IsIdentityConsumingSwitch(const MutableGraphView& graph,
const NodeDef& node) {
if ((IsIdentity(node) || IsIdentityNSingleInput(node)) &&
node.input_size() > 0) {
TensorId tensor_id = ParseTensorName(node.input(0));
if (IsTensorIdControlling(tensor_id)) {
return false;
}
NodeDef* input_node = graph.GetNode(tensor_id.node());
if (input_node == nullptr) {
return false;
}
return IsSwitch(*input_node);
}
return false;
}
|
CVE-2022-23589
|
CWE-476
|
Tensorflow is an Open Source Machine Learning Framework. Under certain scenarios, Grappler component of TensorFlow can trigger a null pointer dereference. There are 2 places where this can occur, for the same malicious alteration of a `SavedModel` file (fixing the first one would trigger the same dereference in the second place). First, during constant folding, the `GraphDef` might not have the required nodes for the binary operation. If a node is missing, the correposning `mul_*child` would be null, and the dereference in the subsequent line would be incorrect. We have a similar issue during `IsIdentityConsumingSwitch`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
|
https://github.com/tensorflow/tensorflow/commit/045deec1cbdebb27d817008ad5df94d96a08b1bf
|
Prevent null pointer dereference in `mutable_graph_view`
PiperOrigin-RevId: 409684472
Change-Id: I577eb9d9ac470fcec0501423171e739a4ec0cb5c
|
mutable_graph_view.cc
|
cc
|
2021-11-13T18:12:22Z
|
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);
// Only int32 and int64 multipliers type is supported.
if (multipliers->type != kTfLiteInt32 && multipliers->type != kTfLiteInt64) {
context->ReportError(context,
"Multipliers of type '%s' are not supported by tile.",
TfLiteTypeGetName(multipliers->type));
return kTfLiteError;
}
if (IsConstantTensor(multipliers)) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
} else {
SetTensorToDynamic(output);
}
return kTfLiteOk;
}
|
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
const TfLiteTensor* multipliers;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kInputMultipliers, &multipliers));
// Only int32 and int64 multipliers type is supported.
if (multipliers->type != kTfLiteInt32 && multipliers->type != kTfLiteInt64) {
context->ReportError(context,
"Multipliers of type '%s' are not supported by tile.",
TfLiteTypeGetName(multipliers->type));
return kTfLiteError;
}
if (IsConstantTensor(multipliers)) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
} else {
SetTensorToDynamic(output);
}
return kTfLiteOk;
}
|
CVE-2020-15211
|
CWE-125,CWE-787
|
In TensorFlow Lite before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, saved models in the flatbuffer format use a double indexing scheme: a model has a set of subgraphs, each subgraph has a set of operators and each operator has a set of input/output tensors. The flatbuffer format uses indices for the tensors, indexing into an array of tensors that is owned by the subgraph. This results in a pattern of double array indexing when trying to get the data of each tensor. However, some operators can have some tensors be optional. To handle this scenario, the flatbuffer model uses a negative `-1` value as index for these tensors. This results in special casing during validation at model loading time. Unfortunately, this means that the `-1` index is a valid tensor index for any operator, including those that don't expect optional inputs and including for output tensors. Thus, this allows writing and reading from outside the bounds of heap allocated arrays, although only at a specific offset from the start of these arrays. This results in both read and write gadgets, albeit very limited in scope. The issue is patched in several commits (46d5b0852, 00302787b7, e11f5558, cd31fd0ce, 1970c21, and fff2c83), and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1. A potential workaround would be to add a custom `Verifier` to the model loading code to ensure that only operators which accept optional inputs use the `-1` special value and only for the tensors that they expect to be optional. Since this allow-list type approach is erro-prone, we advise upgrading to the patched code.
|
https://github.com/tensorflow/tensorflow/commit/1970c2158b1ffa416d159d03c3370b9a462aee35
|
[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56
|
add_n.cc
|
cc
|
2020-09-25T19:15:00Z
|
@Method(0x800ebb44L)
public static void FUN_800ebb44() {
final WMapStruct258 struct = struct258_800c66a8;
_800c86fc.setu(0x1L);
struct._24 = new WMapStruct258Sub60[24];
//LAB_800ebbb4
final VECTOR sp0x20 = new VECTOR();
for(int i = 0; i < 12; i++) {
final WMapStruct258Sub60 sp18 = new WMapStruct258Sub60();
struct._24[i] = sp18;
//LAB_800ebbd0
GsInitCoordinate2(null, sp18.coord2_00);
if((i & 0x1) == 0) {
sp0x20.set(
700 - rand() % 1400,
-70 - rand() % 40,
700 - rand() % 1400
);
sp18.coord2_00.coord.transfer.set(sp0x20);
} else {
//LAB_800ebd18
sp18.coord2_00.coord.transfer.set(sp0x20).sub(
rand() % 200 - 100,
rand() % 80 - 40,
rand() % 50 - 25
);
}
//LAB_800ebe24
sp18.rotation_50.set((short)0, (short)0, (short)0);
sp18._58 = (288 - rand() % 64) / 2;
sp18._5a = ( 80 - rand() % 32) / 2;
sp18._5c = 0;
sp18._5e = 0;
}
//LAB_800ebf2c
//LAB_800ebf30
for(int i = 0; i < 12; i++) {
final WMapStruct258Sub60 sp18 = struct._24[i + 12];
sp18.set(struct._24[i]);
sp18.coord2_00.coord.transfer.setY(0);
}
}
|
@Method(0x800ebb44L)
public static void FUN_800ebb44() {
final WMapStruct258 struct = struct258_800c66a8;
_800c86fc.setu(0x1L);
struct._24 = new WMapStruct258Sub60[24];
//LAB_800ebbb4
final VECTOR sp0x20 = new VECTOR();
for(int i = 0; i < 12; i++) {
final WMapStruct258Sub60 sp18 = new WMapStruct258Sub60();
struct._24[i] = sp18;
//LAB_800ebbd0
GsInitCoordinate2(null, sp18.coord2_00);
if((i & 0x1) == 0) {
sp0x20.set(
700 - rand() % 1400,
-70 - rand() % 40,
700 - rand() % 1400
);
sp18.coord2_00.coord.transfer.set(sp0x20);
} else {
//LAB_800ebd18
sp18.coord2_00.coord.transfer.set(sp0x20).sub(
rand() % 200 - 100,
rand() % 80 - 40,
rand() % 50 - 25
);
}
//LAB_800ebe24
sp18.rotation_50.set((short)0, (short)0, (short)0);
sp18._58 = (288 - rand() % 64) / 2;
sp18._5a = ( 80 - rand() % 32) / 2;
sp18._5c = 0;
sp18._5e = 0;
}
//LAB_800ebf2c
//LAB_800ebf30
for(int i = 0; i < 12; i++) {
final WMapStruct258Sub60 sp18 = new WMapStruct258Sub60();
struct._24[i + 12] = sp18;
sp18.set(struct._24[i]);
sp18.coord2_00.coord.transfer.setY(0);
}
}
| null | null | null |
https://github.com/Legend-of-Dragoon-Modding/Severed-Chains/commit/54e5a8cf898d43d53da9bcabdd49130a48a9e738
|
Fix crash on wmap
|
src/main/java/legend/game/WMap.java
|
java
|
2023-01-25T23:06:21Z
|
static int map_freeze(const union bpf_attr *attr)
{
int err = 0, ufd = attr->map_fd;
struct bpf_map *map;
struct fd f;
if (CHECK_ATTR(BPF_MAP_FREEZE))
return -EINVAL;
f = fdget(ufd);
map = __bpf_map_get(f);
if (IS_ERR(map))
return PTR_ERR(map);
if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS ||
map_value_has_timer(map)) {
fdput(f);
return -ENOTSUPP;
}
mutex_lock(&map->freeze_mutex);
if (map->writecnt) {
err = -EBUSY;
goto err_put;
}
if (READ_ONCE(map->frozen)) {
err = -EBUSY;
goto err_put;
}
if (!bpf_capable()) {
err = -EPERM;
goto err_put;
}
WRITE_ONCE(map->frozen, true);
err_put:
mutex_unlock(&map->freeze_mutex);
fdput(f);
return err;
}
|
static int map_freeze(const union bpf_attr *attr)
{
int err = 0, ufd = attr->map_fd;
struct bpf_map *map;
struct fd f;
if (CHECK_ATTR(BPF_MAP_FREEZE))
return -EINVAL;
f = fdget(ufd);
map = __bpf_map_get(f);
if (IS_ERR(map))
return PTR_ERR(map);
if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS ||
map_value_has_timer(map)) {
fdput(f);
return -ENOTSUPP;
}
mutex_lock(&map->freeze_mutex);
if (bpf_map_write_active(map)) {
err = -EBUSY;
goto err_put;
}
if (READ_ONCE(map->frozen)) {
err = -EBUSY;
goto err_put;
}
if (!bpf_capable()) {
err = -EPERM;
goto err_put;
}
WRITE_ONCE(map->frozen, true);
err_put:
mutex_unlock(&map->freeze_mutex);
fdput(f);
return err;
}
|
CVE-2021-4001
|
CWE-367
|
A race condition was found in the Linux kernel's ebpf verifier between bpf_map_update_elem and bpf_map_freeze due to a missing lock in kernel/bpf/syscall.c. In this flaw, a local user with a special privilege (cap_sys_admin or cap_bpf) can modify the frozen mapped address space. This flaw affects kernel versions prior to 5.16 rc2.
|
https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf.git/commit/?id=353050be4c19e102178ccc05988101887c25ae53
|
bpf: Fix toctou on read-only map's constant scalar tracking
Commit a23740ec43ba ("bpf: Track contents of read-only maps as scalars") is
checking whether maps are read-only both from BPF program side and user space
side, and then, given their content is constant, reading out their data via
map->ops->map_direct_value_addr() which is then subsequently used as known
scalar value for the register, that is, it is marked as __mark_reg_known()
with the read value at verification time. Before a23740ec43ba, the register
content was marked as an unknown scalar so the verifier could not make any
assumptions about the map content.
The current implementation however is prone to a TOCTOU race, meaning, the
value read as known scalar for the register is not guaranteed to be exactly
the same at a later point when the program is executed, and as such, the
prior made assumptions of the verifier with regards to the program will be
invalid which can cause issues such as OOB access, etc.
While the BPF_F_RDONLY_PROG map flag is always fixed and required to be
specified at map creation time, the map->frozen property is initially set to
false for the map given the map value needs to be populated, e.g. for global
data sections. Once complete, the loader "freezes" the map from user space
such that no subsequent updates/deletes are possible anymore. For the rest
of the lifetime of the map, this freeze one-time trigger cannot be undone
anymore after a successful BPF_MAP_FREEZE cmd return. Meaning, any new BPF_*
cmd calls which would update/delete map entries will be rejected with -EPERM
since map_get_sys_perms() removes the FMODE_CAN_WRITE permission. This also
means that pending update/delete map entries must still complete before this
guarantee is given. This corner case is not an issue for loaders since they
create and prepare such program private map in successive steps.
However, a malicious user is able to trigger this TOCTOU race in two different
ways: i) via userfaultfd, and ii) via batched updates. For i) userfaultfd is
used to expand the competition interval, so that map_update_elem() can modify
the contents of the map after map_freeze() and bpf_prog_load() were executed.
This works, because userfaultfd halts the parallel thread which triggered a
map_update_elem() at the time where we copy key/value from the user buffer and
this already passed the FMODE_CAN_WRITE capability test given at that time the
map was not "frozen". Then, the main thread performs the map_freeze() and
bpf_prog_load(), and once that had completed successfully, the other thread
is woken up to complete the pending map_update_elem() which then changes the
map content. For ii) the idea of the batched update is similar, meaning, when
there are a large number of updates to be processed, it can increase the
competition interval between the two. It is therefore possible in practice to
modify the contents of the map after executing map_freeze() and bpf_prog_load().
One way to fix both i) and ii) at the same time is to expand the use of the
map's map->writecnt. The latter was introduced in fc9702273e2e ("bpf: Add mmap()
support for BPF_MAP_TYPE_ARRAY") and further refined in 1f6cb19be2e2 ("bpf:
Prevent re-mmap()'ing BPF map as writable for initially r/o mapping") with
the rationale to make a writable mmap()'ing of a map mutually exclusive with
read-only freezing. The counter indicates writable mmap() mappings and then
prevents/fails the freeze operation. Its semantics can be expanded beyond
just mmap() by generally indicating ongoing write phases. This would essentially
span any parallel regular and batched flavor of update/delete operation and
then also have map_freeze() fail with -EBUSY. For the check_mem_access() in
the verifier we expand upon the bpf_map_is_rdonly() check ensuring that all
last pending writes have completed via bpf_map_write_active() test. Once the
map->frozen is set and bpf_map_write_active() indicates a map->writecnt of 0
only then we are really guaranteed to use the map's data as known constants.
For map->frozen being set and pending writes in process of still being completed
we fall back to marking that register as unknown scalar so we don't end up
making assumptions about it. With this, both TOCTOU reproducers from i) and
ii) are fixed.
Note that the map->writecnt has been converted into a atomic64 in the fix in
order to avoid a double freeze_mutex mutex_{un,}lock() pair when updating
map->writecnt in the various map update/delete BPF_* cmd flavors. Spanning
the freeze_mutex over entire map update/delete operations in syscall side
would not be possible due to then causing everything to be serialized.
Similarly, something like synchronize_rcu() after setting map->frozen to wait
for update/deletes to complete is not possible either since it would also
have to span the user copy which can sleep. On the libbpf side, this won't
break d66562fba1ce ("libbpf: Add BPF object skeleton support") as the
anonymous mmap()-ed "map initialization image" is remapped as a BPF map-backed
mmap()-ed memory where for .rodata it's non-writable.
Fixes: a23740ec43ba ("bpf: Track contents of read-only maps as scalars")
Reported-by: w1tcher.bupt@gmail.com
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Acked-by: Andrii Nakryiko <andrii@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
| null | null | null |
static struct prog_entry *
predicate_parse(const char *str, int nr_parens, int nr_preds,
parse_pred_fn parse_pred, void *data,
struct filter_parse_error *pe)
{
struct prog_entry *prog_stack;
struct prog_entry *prog;
const char *ptr = str;
char *inverts = NULL;
int *op_stack;
int *top;
int invert = 0;
int ret = -ENOMEM;
int len;
int N = 0;
int i;
nr_preds += 2; /* For TRUE and FALSE */
op_stack = kmalloc_array(nr_parens, sizeof(*op_stack), GFP_KERNEL);
if (!op_stack)
return ERR_PTR(-ENOMEM);
prog_stack = kmalloc_array(nr_preds, sizeof(*prog_stack), GFP_KERNEL);
if (!prog_stack) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL);
if (!inverts) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
top = op_stack;
prog = prog_stack;
*top = 0;
/* First pass */
while (*ptr) { /* #1 */
const char *next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case '(': /* #2 */
if (top - op_stack > nr_parens)
return ERR_PTR(-EINVAL);
*(++top) = invert;
continue;
case '!': /* #3 */
if (!is_not(next))
break;
invert = !invert;
continue;
}
if (N >= nr_preds) {
parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str);
goto out_free;
}
inverts[N] = invert; /* #4 */
prog[N].target = N-1;
len = parse_pred(next, data, ptr - str, pe, &prog[N].pred);
if (len < 0) {
ret = len;
goto out_free;
}
ptr = next + len;
N++;
ret = -1;
while (1) { /* #5 */
next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case ')':
case '\0':
break;
case '&':
case '|':
if (next[1] == next[0]) {
ptr++;
break;
}
default:
parse_error(pe, FILT_ERR_TOO_MANY_PREDS,
next - str);
goto out_free;
}
invert = *top & INVERT;
if (*top & PROCESS_AND) { /* #7 */
update_preds(prog, N - 1, invert);
*top &= ~PROCESS_AND;
}
if (*next == '&') { /* #8 */
*top |= PROCESS_AND;
break;
}
if (*top & PROCESS_OR) { /* #9 */
update_preds(prog, N - 1, !invert);
*top &= ~PROCESS_OR;
}
if (*next == '|') { /* #10 */
*top |= PROCESS_OR;
break;
}
if (!*next) /* #11 */
goto out;
if (top == op_stack) {
ret = -1;
/* Too few '(' */
parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, ptr - str);
goto out_free;
}
top--; /* #12 */
}
}
out:
if (top != op_stack) {
/* Too many '(' */
parse_error(pe, FILT_ERR_TOO_MANY_OPEN, ptr - str);
goto out_free;
}
prog[N].pred = NULL; /* #13 */
prog[N].target = 1; /* TRUE */
prog[N+1].pred = NULL;
prog[N+1].target = 0; /* FALSE */
prog[N-1].target = N;
prog[N-1].when_to_branch = false;
/* Second Pass */
for (i = N-1 ; i--; ) {
int target = prog[i].target;
if (prog[i].when_to_branch == prog[target].when_to_branch)
prog[i].target = prog[target].target;
}
/* Third Pass */
for (i = 0; i < N; i++) {
invert = inverts[i] ^ prog[i].when_to_branch;
prog[i].when_to_branch = invert;
/* Make sure the program always moves forward */
if (WARN_ON(prog[i].target <= i)) {
ret = -EINVAL;
goto out_free;
}
}
return prog;
out_free:
kfree(op_stack);
kfree(prog_stack);
kfree(inverts);
return ERR_PTR(ret);
}
|
static struct prog_entry *
predicate_parse(const char *str, int nr_parens, int nr_preds,
parse_pred_fn parse_pred, void *data,
struct filter_parse_error *pe)
{
struct prog_entry *prog_stack;
struct prog_entry *prog;
const char *ptr = str;
char *inverts = NULL;
int *op_stack;
int *top;
int invert = 0;
int ret = -ENOMEM;
int len;
int N = 0;
int i;
nr_preds += 2; /* For TRUE and FALSE */
op_stack = kmalloc_array(nr_parens, sizeof(*op_stack), GFP_KERNEL);
if (!op_stack)
return ERR_PTR(-ENOMEM);
prog_stack = kmalloc_array(nr_preds, sizeof(*prog_stack), GFP_KERNEL);
if (!prog_stack) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL);
if (!inverts) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
top = op_stack;
prog = prog_stack;
*top = 0;
/* First pass */
while (*ptr) { /* #1 */
const char *next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case '(': /* #2 */
if (top - op_stack > nr_parens)
return ERR_PTR(-EINVAL);
*(++top) = invert;
continue;
case '!': /* #3 */
if (!is_not(next))
break;
invert = !invert;
continue;
}
if (N >= nr_preds) {
parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str);
goto out_free;
}
inverts[N] = invert; /* #4 */
prog[N].target = N-1;
len = parse_pred(next, data, ptr - str, pe, &prog[N].pred);
if (len < 0) {
ret = len;
goto out_free;
}
ptr = next + len;
N++;
ret = -1;
while (1) { /* #5 */
next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case ')':
case '\0':
break;
case '&':
case '|':
if (next[1] == next[0]) {
ptr++;
break;
}
default:
parse_error(pe, FILT_ERR_TOO_MANY_PREDS,
next - str);
goto out_free;
}
invert = *top & INVERT;
if (*top & PROCESS_AND) { /* #7 */
update_preds(prog, N - 1, invert);
*top &= ~PROCESS_AND;
}
if (*next == '&') { /* #8 */
*top |= PROCESS_AND;
break;
}
if (*top & PROCESS_OR) { /* #9 */
update_preds(prog, N - 1, !invert);
*top &= ~PROCESS_OR;
}
if (*next == '|') { /* #10 */
*top |= PROCESS_OR;
break;
}
if (!*next) /* #11 */
goto out;
if (top == op_stack) {
ret = -1;
/* Too few '(' */
parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, ptr - str);
goto out_free;
}
top--; /* #12 */
}
}
out:
if (top != op_stack) {
/* Too many '(' */
parse_error(pe, FILT_ERR_TOO_MANY_OPEN, ptr - str);
goto out_free;
}
if (!N) {
/* No program? */
ret = -EINVAL;
parse_error(pe, FILT_ERR_NO_FILTER, ptr - str);
goto out_free;
}
prog[N].pred = NULL; /* #13 */
prog[N].target = 1; /* TRUE */
prog[N+1].pred = NULL;
prog[N+1].target = 0; /* FALSE */
prog[N-1].target = N;
prog[N-1].when_to_branch = false;
/* Second Pass */
for (i = N-1 ; i--; ) {
int target = prog[i].target;
if (prog[i].when_to_branch == prog[target].when_to_branch)
prog[i].target = prog[target].target;
}
/* Third Pass */
for (i = 0; i < N; i++) {
invert = inverts[i] ^ prog[i].when_to_branch;
prog[i].when_to_branch = invert;
/* Make sure the program always moves forward */
if (WARN_ON(prog[i].target <= i)) {
ret = -EINVAL;
goto out_free;
}
}
return prog;
out_free:
kfree(op_stack);
kfree(prog_stack);
kfree(inverts);
return ERR_PTR(ret);
}
| null | null | null |
https://github.com/torvalds/linux/commit/81f9c4e4177d31ced6f52a89bb70e93bfb77ca03
|
Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
|
kernel/trace/trace_events_filter.c
|
c
|
2018-06-23T22:23:28Z
|
jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr)
{
jp2_box_t *box;
int found;
jas_image_t *image;
jp2_dec_t *dec;
bool samedtype;
int dtype;
unsigned int i;
jp2_cmap_t *cmapd;
jp2_pclr_t *pclrd;
jp2_cdef_t *cdefd;
unsigned int channo;
int newcmptno;
int_fast32_t *lutents;
#if 0
jp2_cdefchan_t *cdefent;
int cmptno;
#endif
jp2_cmapent_t *cmapent;
jas_icchdr_t icchdr;
jas_iccprof_t *iccprof;
dec = 0;
box = 0;
image = 0;
JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr));
if (!(dec = jp2_dec_create())) {
goto error;
}
/* Get the first box. This should be a JP box. */
if (!(box = jp2_box_get(in))) {
jas_eprintf("error: cannot get box\n");
goto error;
}
if (box->type != JP2_BOX_JP) {
jas_eprintf("error: expecting signature box\n");
goto error;
}
if (box->data.jp.magic != JP2_JP_MAGIC) {
jas_eprintf("incorrect magic number\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get the second box. This should be a FTYP box. */
if (!(box = jp2_box_get(in))) {
goto error;
}
if (box->type != JP2_BOX_FTYP) {
jas_eprintf("expecting file type box\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get more boxes... */
found = 0;
while ((box = jp2_box_get(in))) {
if (jas_getdbglevel() >= 1) {
jas_eprintf("got box type %s\n", box->info->name);
}
switch (box->type) {
case JP2_BOX_JP2C:
found = 1;
break;
case JP2_BOX_IHDR:
if (!dec->ihdr) {
dec->ihdr = box;
box = 0;
}
break;
case JP2_BOX_BPCC:
if (!dec->bpcc) {
dec->bpcc = box;
box = 0;
}
break;
case JP2_BOX_CDEF:
if (!dec->cdef) {
dec->cdef = box;
box = 0;
}
break;
case JP2_BOX_PCLR:
if (!dec->pclr) {
dec->pclr = box;
box = 0;
}
break;
case JP2_BOX_CMAP:
if (!dec->cmap) {
dec->cmap = box;
box = 0;
}
break;
case JP2_BOX_COLR:
if (!dec->colr) {
dec->colr = box;
box = 0;
}
break;
}
if (box) {
jp2_box_destroy(box);
box = 0;
}
if (found) {
break;
}
}
if (!found) {
jas_eprintf("error: no code stream found\n");
goto error;
}
if (!(dec->image = jpc_decode(in, optstr))) {
jas_eprintf("error: cannot decode code stream\n");
goto error;
}
/* An IHDR box must be present. */
if (!dec->ihdr) {
jas_eprintf("error: missing IHDR box\n");
goto error;
}
/* Does the number of components indicated in the IHDR box match
the value specified in the code stream? */
if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("error: number of components mismatch (IHDR)\n");
goto error;
}
/* At least one component must be present. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
/* Determine if all components have the same data type. */
samedtype = true;
dtype = jas_image_cmptdtype(dec->image, 0);
for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
if (jas_image_cmptdtype(dec->image, i) != dtype) {
samedtype = false;
break;
}
}
/* Is the component data type indicated in the IHDR box consistent
with the data in the code stream? */
if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
(!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
jas_eprintf("error: component data type mismatch (IHDR)\n");
goto error;
}
/* Is the compression type supported? */
if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
jas_eprintf("error: unsupported compression type\n");
goto error;
}
if (dec->bpcc) {
/* Is the number of components indicated in the BPCC box
consistent with the code stream data? */
if (dec->bpcc->data.bpcc.numcmpts !=
JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) {
jas_eprintf("error: number of components mismatch (BPCC)\n");
goto error;
}
/* Is the component data type information indicated in the BPCC
box consistent with the code stream data? */
if (!samedtype) {
for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
++i) {
if (jas_image_cmptdtype(dec->image, i) !=
JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
jas_eprintf("error: component data type mismatch (BPCC)\n");
goto error;
}
}
} else {
jas_eprintf("warning: superfluous BPCC box\n");
}
}
/* A COLR box must be present. */
if (!dec->colr) {
jas_eprintf("error: no COLR box\n");
goto error;
}
switch (dec->colr->data.colr.method) {
case JP2_COLR_ENUM:
jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
break;
case JP2_COLR_ICC:
iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
dec->colr->data.colr.iccplen);
if (!iccprof) {
jas_eprintf("error: failed to parse ICC profile\n");
goto error;
}
jas_iccprof_gethdr(iccprof, &icchdr);
jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
if (!dec->image->cmprof_) {
jas_iccprof_destroy(iccprof);
goto error;
}
jas_iccprof_destroy(iccprof);
break;
}
/* If a CMAP box is present, a PCLR box must also be present. */
if (dec->cmap && !dec->pclr) {
jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
jp2_box_destroy(dec->cmap);
dec->cmap = 0;
}
/* If a CMAP box is not present, a PCLR box must not be present. */
if (!dec->cmap && dec->pclr) {
jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
jp2_box_destroy(dec->pclr);
dec->pclr = 0;
}
/* Determine the number of channels (which is essentially the number
of components after any palette mappings have been applied). */
dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans :
JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
/* Perform a basic sanity check on the CMAP box if present. */
if (dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
/* Is the component number reasonable? */
if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("error: invalid component number in CMAP box\n");
goto error;
}
/* Is the LUT index reasonable? */
if (dec->cmap->data.cmap.ents[i].pcol >=
dec->pclr->data.pclr.numchans) {
jas_eprintf("error: invalid CMAP LUT index\n");
goto error;
}
}
}
/* Allocate space for the channel-number to component-number LUT. */
if (!(dec->chantocmptlut = jas_alloc2(dec->numchans,
sizeof(uint_fast16_t)))) {
jas_eprintf("error: no memory\n");
goto error;
}
if (!dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
dec->chantocmptlut[i] = i;
}
} else {
cmapd = &dec->cmap->data.cmap;
pclrd = &dec->pclr->data.pclr;
cdefd = &dec->cdef->data.cdef;
for (channo = 0; channo < cmapd->numchans; ++channo) {
cmapent = &cmapd->ents[channo];
if (cmapent->map == JP2_CMAP_DIRECT) {
dec->chantocmptlut[channo] = channo;
} else if (cmapent->map == JP2_CMAP_PALETTE) {
if (!pclrd->numlutents) {
goto error;
}
lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));
if (!lutents) {
goto error;
}
for (i = 0; i < pclrd->numlutents; ++i) {
lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
}
newcmptno = jas_image_numcmpts(dec->image);
jas_image_depalettize(dec->image, cmapent->cmptno,
pclrd->numlutents, lutents,
JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
dec->chantocmptlut[channo] = newcmptno;
jas_free(lutents);
#if 0
if (dec->cdef) {
cdefent = jp2_cdef_lookup(cdefd, channo);
if (!cdefent) {
abort();
}
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
} else {
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
}
#else
/* suppress -Wunused-but-set-variable */
(void)cdefd;
#endif
} else {
jas_eprintf("error: invalid MTYP in CMAP box\n");
goto error;
}
}
}
/* Ensure that the number of channels being used by the decoder
matches the number of image components. */
if (dec->numchans != jas_image_numcmpts(dec->image)) {
jas_eprintf("error: mismatch in number of components (%d != %d)\n",
dec->numchans, jas_image_numcmpts(dec->image));
goto error;
}
/* Mark all components as being of unknown type. */
for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
}
/* Determine the type of each component. */
if (dec->cdef) {
for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) {
uint_fast16_t channo = dec->cdef->data.cdef.ents[i].channo;
/* Is the channel number reasonable? */
if (channo >= dec->numchans) {
jas_eprintf("error: invalid channel number in CDEF box (%d)\n",
channo);
goto error;
}
unsigned compno = dec->chantocmptlut[channo];
if (compno >= jas_image_numcmpts(dec->image)) {
jas_eprintf(
"error: invalid component reference in CDEF box (%d)\n",
compno);
goto error;
}
jas_image_setcmpttype(dec->image, compno,
jp2_getct(jas_image_clrspc(dec->image),
dec->cdef->data.cdef.ents[i].type,
dec->cdef->data.cdef.ents[i].assoc));
}
} else {
for (i = 0; i < dec->numchans; ++i) {
jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
}
}
/* Delete any components that are not of interest. */
for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
jas_image_delcmpt(dec->image, i - 1);
}
}
/* Ensure that some components survived. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
#if 0
jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
#endif
/* Prevent the image from being destroyed later. */
image = dec->image;
dec->image = 0;
jp2_dec_destroy(dec);
return image;
error:
if (box) {
jp2_box_destroy(box);
}
if (dec) {
jp2_dec_destroy(dec);
}
return 0;
}
|
jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr)
{
jp2_box_t *box;
int found;
jas_image_t *image;
jp2_dec_t *dec;
bool samedtype;
int dtype;
unsigned int i;
jp2_cmap_t *cmapd;
jp2_pclr_t *pclrd;
jp2_cdef_t *cdefd;
unsigned int channo;
int newcmptno;
int_fast32_t *lutents;
#if 0
jp2_cdefchan_t *cdefent;
int cmptno;
#endif
jp2_cmapent_t *cmapent;
jas_icchdr_t icchdr;
jas_iccprof_t *iccprof;
dec = 0;
box = 0;
image = 0;
JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr));
if (!(dec = jp2_dec_create())) {
goto error;
}
/* Get the first box. This should be a JP box. */
if (!(box = jp2_box_get(in))) {
jas_eprintf("error: cannot get box\n");
goto error;
}
if (box->type != JP2_BOX_JP) {
jas_eprintf("error: expecting signature box\n");
goto error;
}
if (box->data.jp.magic != JP2_JP_MAGIC) {
jas_eprintf("incorrect magic number\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get the second box. This should be a FTYP box. */
if (!(box = jp2_box_get(in))) {
goto error;
}
if (box->type != JP2_BOX_FTYP) {
jas_eprintf("expecting file type box\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get more boxes... */
found = 0;
while ((box = jp2_box_get(in))) {
if (jas_getdbglevel() >= 1) {
jas_eprintf("got box type %s\n", box->info->name);
}
switch (box->type) {
case JP2_BOX_JP2C:
found = 1;
break;
case JP2_BOX_IHDR:
if (!dec->ihdr) {
dec->ihdr = box;
box = 0;
}
break;
case JP2_BOX_BPCC:
if (!dec->bpcc) {
dec->bpcc = box;
box = 0;
}
break;
case JP2_BOX_CDEF:
if (!dec->cdef) {
dec->cdef = box;
box = 0;
}
break;
case JP2_BOX_PCLR:
if (!dec->pclr) {
dec->pclr = box;
box = 0;
}
break;
case JP2_BOX_CMAP:
if (!dec->cmap) {
dec->cmap = box;
box = 0;
}
break;
case JP2_BOX_COLR:
if (!dec->colr) {
dec->colr = box;
box = 0;
}
break;
}
if (box) {
jp2_box_destroy(box);
box = 0;
}
if (found) {
break;
}
}
if (!found) {
jas_eprintf("error: no code stream found\n");
goto error;
}
if (!(dec->image = jpc_decode(in, optstr))) {
jas_eprintf("error: cannot decode code stream\n");
goto error;
}
/* An IHDR box must be present. */
if (!dec->ihdr) {
jas_eprintf("error: missing IHDR box\n");
goto error;
}
/* Does the number of components indicated in the IHDR box match
the value specified in the code stream? */
if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("error: number of components mismatch (IHDR)\n");
goto error;
}
/* At least one component must be present. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
/* Determine if all components have the same data type. */
samedtype = true;
dtype = jas_image_cmptdtype(dec->image, 0);
for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
if (jas_image_cmptdtype(dec->image, i) != dtype) {
samedtype = false;
break;
}
}
/* Is the component data type indicated in the IHDR box consistent
with the data in the code stream? */
if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
(!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
jas_eprintf("error: component data type mismatch (IHDR)\n");
goto error;
}
/* Is the compression type supported? */
if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
jas_eprintf("error: unsupported compression type\n");
goto error;
}
if (dec->bpcc) {
/* Is the number of components indicated in the BPCC box
consistent with the code stream data? */
if (dec->bpcc->data.bpcc.numcmpts !=
JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) {
jas_eprintf("error: number of components mismatch (BPCC)\n");
goto error;
}
/* Is the component data type information indicated in the BPCC
box consistent with the code stream data? */
if (!samedtype) {
for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
++i) {
if (jas_image_cmptdtype(dec->image, i) !=
JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
jas_eprintf("error: component data type mismatch (BPCC)\n");
goto error;
}
}
} else {
jas_eprintf("warning: superfluous BPCC box\n");
}
}
/* A COLR box must be present. */
if (!dec->colr) {
jas_eprintf("error: no COLR box\n");
goto error;
}
switch (dec->colr->data.colr.method) {
case JP2_COLR_ENUM:
jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
break;
case JP2_COLR_ICC:
iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
dec->colr->data.colr.iccplen);
if (!iccprof) {
jas_eprintf("error: failed to parse ICC profile\n");
goto error;
}
jas_iccprof_gethdr(iccprof, &icchdr);
jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
if (!dec->image->cmprof_) {
jas_iccprof_destroy(iccprof);
goto error;
}
jas_iccprof_destroy(iccprof);
break;
}
/* If a CMAP box is present, a PCLR box must also be present. */
if (dec->cmap && !dec->pclr) {
jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
jp2_box_destroy(dec->cmap);
dec->cmap = 0;
}
/* If a CMAP box is not present, a PCLR box must not be present. */
if (!dec->cmap && dec->pclr) {
jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
jp2_box_destroy(dec->pclr);
dec->pclr = 0;
}
/* Determine the number of channels (which is essentially the number
of components after any palette mappings have been applied). */
dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans :
JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
/* Perform a basic sanity check on the CMAP box if present. */
if (dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
/* Is the component number reasonable? */
if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("error: invalid component number in CMAP box\n");
goto error;
}
/* Is the LUT index reasonable? */
if (dec->cmap->data.cmap.ents[i].pcol >=
dec->pclr->data.pclr.numchans) {
jas_eprintf("error: invalid CMAP LUT index\n");
goto error;
}
}
}
/* Allocate space for the channel-number to component-number LUT. */
if (!(dec->chantocmptlut = jas_alloc2(dec->numchans,
sizeof(uint_fast16_t)))) {
jas_eprintf("error: no memory\n");
goto error;
}
if (!dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
dec->chantocmptlut[i] = i;
}
} else {
cmapd = &dec->cmap->data.cmap;
pclrd = &dec->pclr->data.pclr;
cdefd = &dec->cdef->data.cdef;
for (channo = 0; channo < cmapd->numchans; ++channo) {
cmapent = &cmapd->ents[channo];
if (cmapent->map == JP2_CMAP_DIRECT) {
dec->chantocmptlut[channo] = channo;
} else if (cmapent->map == JP2_CMAP_PALETTE) {
if (!pclrd->numlutents) {
goto error;
}
lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));
if (!lutents) {
goto error;
}
for (i = 0; i < pclrd->numlutents; ++i) {
lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
}
newcmptno = jas_image_numcmpts(dec->image);
jas_image_depalettize(dec->image, cmapent->cmptno,
pclrd->numlutents, lutents,
JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
dec->chantocmptlut[channo] = newcmptno;
jas_free(lutents);
#if 0
if (dec->cdef) {
cdefent = jp2_cdef_lookup(cdefd, channo);
if (!cdefent) {
abort();
}
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
} else {
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
}
#else
/* suppress -Wunused-but-set-variable */
(void)cdefd;
#endif
} else {
jas_eprintf("error: invalid MTYP in CMAP box\n");
goto error;
}
}
}
/* Ensure that the number of channels being used by the decoder
matches the number of image components. */
if (dec->numchans != jas_image_numcmpts(dec->image)) {
jas_eprintf("error: mismatch in number of components (%d != %d)\n",
dec->numchans, jas_image_numcmpts(dec->image));
goto error;
}
/* Mark all components as being of unknown type. */
for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
}
/* Determine the type of each component. */
if (dec->cdef) {
for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) {
uint_fast16_t channo = dec->cdef->data.cdef.ents[i].channo;
/* Is the channel number reasonable? */
if (channo >= dec->numchans) {
jas_eprintf("error: invalid channel number in CDEF box (%d)\n",
channo);
goto error;
}
unsigned compno = dec->chantocmptlut[channo];
if (compno >= jas_image_numcmpts(dec->image)) {
jas_eprintf(
"error: invalid component reference in CDEF box (%d)\n",
compno);
goto error;
}
jas_image_setcmpttype(dec->image, compno,
jp2_getct(jas_image_clrspc(dec->image),
dec->cdef->data.cdef.ents[i].type,
dec->cdef->data.cdef.ents[i].assoc));
}
} else {
for (i = 0; i < dec->numchans; ++i) {
unsigned compno = dec->chantocmptlut[i];
if (compno >= jas_image_numcmpts(dec->image)) {
jas_eprintf(
"error: invalid component reference (%d)\n", compno);
goto error;
}
jas_image_setcmpttype(dec->image, compno,
jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
}
}
/* Delete any components that are not of interest. */
for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
jas_image_delcmpt(dec->image, i - 1);
}
}
/* Ensure that some components survived. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
#if 0
jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
#endif
/* Prevent the image from being destroyed later. */
image = dec->image;
dec->image = 0;
jp2_dec_destroy(dec);
return image;
error:
if (box) {
jp2_box_destroy(box);
}
if (dec) {
jp2_dec_destroy(dec);
}
return 0;
}
|
CVE-2021-3443
|
CWE-476
|
A NULL pointer dereference flaw was found in the way Jasper versions before 2.0.27 handled component references in the JP2 image format decoder. A specially crafted JP2 image file could cause an application using the Jasper library to crash when opened.
|
https://github.com/jasper-software/jasper/commit/f94e7499a8b1471a4905c4f9c9e12e60fe88264b
|
Fixes #269.
Added a check for an invalid component reference in the JP2 decoder.
Added a related test case for the JP2 codec.
| null | null |
2021-03-14T04:04:58Z
|
static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct raw6_frag_vec rfv;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (!opt)
opt = np->opt;
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
rfv.msg = msg;
rfv.hlen = 0;
err = rawv6_probe_proto_opt(&rfv, &fl6);
if (err)
goto out;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
if (inet->hdrincl)
fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH;
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags);
else {
lock_sock(sk);
err = ip6_append_data(sk, raw6_getfrag, &rfv,
len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
|
static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions *opt_to_free = NULL;
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct raw6_frag_vec rfv;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (!opt) {
opt = txopt_get(np);
opt_to_free = opt;
}
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
rfv.msg = msg;
rfv.hlen = 0;
err = rawv6_probe_proto_opt(&rfv, &fl6);
if (err)
goto out;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
if (inet->hdrincl)
fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH;
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags);
else {
lock_sock(sk);
err = ip6_append_data(sk, raw6_getfrag, &rfv,
len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
txopt_put(opt_to_free);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
| null |
CWE-416, CWE-284, CWE-264
| null |
https://github.com/torvalds/linux/commit/45f6fad84cc305103b28d73482b344d7f5b76f39
|
ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <dvyukov@google.com>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
| null | null |
2015-11-30T03:37:57Z
|
static int frame_thread_init(AVCodecContext *avctx)
{
int thread_count = avctx->thread_count;
AVCodec *codec = avctx->codec;
AVCodecContext *src = avctx;
FrameThreadContext *fctx;
int i, err = 0;
if (thread_count <= 1) {
avctx->active_thread_type = 0;
return 0;
}
avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
pthread_mutex_init(&fctx->buffer_mutex, NULL);
fctx->delaying = 1;
for (i = 0; i < thread_count; i++) {
AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
PerThreadContext *p = &fctx->threads[i];
pthread_mutex_init(&p->mutex, NULL);
pthread_mutex_init(&p->progress_mutex, NULL);
pthread_cond_init(&p->input_cond, NULL);
pthread_cond_init(&p->progress_cond, NULL);
pthread_cond_init(&p->output_cond, NULL);
p->parent = fctx;
p->avctx = copy;
if (!copy) {
err = AVERROR(ENOMEM);
goto error;
}
*copy = *src;
copy->thread_opaque = p;
copy->pkt = &p->avpkt;
if (!i) {
src = copy;
if (codec->init)
err = codec->init(copy);
update_context_from_thread(avctx, copy, 1);
} else {
copy->priv_data = av_malloc(codec->priv_data_size);
if (!copy->priv_data) {
err = AVERROR(ENOMEM);
goto error;
}
memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
copy->internal = av_malloc(sizeof(AVCodecInternal));
if (!copy->internal) {
err = AVERROR(ENOMEM);
goto error;
}
*(copy->internal) = *(src->internal);
copy->internal->is_copy = 1;
if (codec->init_thread_copy)
err = codec->init_thread_copy(copy);
}
if (err) goto error;
pthread_create(&p->thread, NULL, frame_worker_thread, p);
}
return 0;
error:
frame_thread_free(avctx, i+1);
return err;
}
|
static int frame_thread_init(AVCodecContext *avctx)
{
int thread_count = avctx->thread_count;
AVCodec *codec = avctx->codec;
AVCodecContext *src = avctx;
FrameThreadContext *fctx;
int i, err = 0;
if (thread_count <= 1) {
avctx->active_thread_type = 0;
return 0;
}
avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
pthread_mutex_init(&fctx->buffer_mutex, NULL);
fctx->delaying = 1;
for (i = 0; i < thread_count; i++) {
AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
PerThreadContext *p = &fctx->threads[i];
pthread_mutex_init(&p->mutex, NULL);
pthread_mutex_init(&p->progress_mutex, NULL);
pthread_cond_init(&p->input_cond, NULL);
pthread_cond_init(&p->progress_cond, NULL);
pthread_cond_init(&p->output_cond, NULL);
p->parent = fctx;
p->avctx = copy;
if (!copy) {
err = AVERROR(ENOMEM);
goto error;
}
*copy = *src;
copy->thread_opaque = p;
copy->pkt = &p->avpkt;
if (!i) {
src = copy;
if (codec->init)
err = codec->init(copy);
update_context_from_thread(avctx, copy, 1);
} else {
copy->priv_data = av_malloc(codec->priv_data_size);
if (!copy->priv_data) {
err = AVERROR(ENOMEM);
goto error;
}
memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
copy->internal = av_malloc(sizeof(AVCodecInternal));
if (!copy->internal) {
err = AVERROR(ENOMEM);
goto error;
}
*(copy->internal) = *(src->internal);
copy->internal->is_copy = 1;
if (codec->init_thread_copy)
err = codec->init_thread_copy(copy);
}
if (err) goto error;
p->thread_created= !pthread_create(&p->thread, NULL, frame_worker_thread, p);
}
return 0;
error:
frame_thread_free(avctx, i+1);
return err;
}
| null | null | null |
FFmpeg/commit/2bb79b23fe106a45eab6ff80d7ef7519d542d1f7
|
pthread: next try on freeing threads without crashing.
This should fix mingw
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
|
./ffmpeg/libavcodec/pthread.c
|
c
|
2011-11-27T04:55:20Z
|
static unsigned tget_long(const uint8_t **p, int le)
{
unsigned v = le ? AV_RL32(*p) : AV_RB32(*p);
*p += 4;
return v;
}
|
static unsigned tget_long(GetByteContext *gb, int le)
{
return le ? bytestream2_get_le32(gb) : bytestream2_get_be32(gb);
}
| null | null | null |
FFmpeg/commit/0a467a9b594dd67aa96bad687d05f8845b009f18
|
tiffdec: use bytestream2 to simplify overread/overwrite protection
Based on a patch by Paul B Mahol <onemda@gmail.com>
CC:libav-stable@libav.org
|
./ffmpeg/libavcodec/tiff.c
|
c
|
2013-09-29T23:47:55Z
|
@Override
public void load(CompoundTag compoundTag) {
super.load(compoundTag);
this.color = compoundTag.contains(COLOR_TAG) ? compoundTag.getInt(COLOR_TAG) : DEFAULT_COLOR;
if (compoundTag.contains(STATUS_EFFECT_TAG) && !compoundTag.getString(STATUS_EFFECT_TAG).trim().equals("")) {
this.mobEffect = BuiltInRegistries.MOB_EFFECT.getOptional(new ResourceLocation(compoundTag.getString(STATUS_EFFECT_TAG))).orElse(null);
}
else {
this.mobEffect = null;
}
this.amplifier = compoundTag.contains(AMPLIFIER_TAG) ? compoundTag.getInt(AMPLIFIER_TAG) : 0;
this.maxDuration = compoundTag.contains(MAX_DURATION_TAG) ? compoundTag.getInt(MAX_DURATION_TAG) : DEFAULT_MAX_DURATION;
this.currentDuration = compoundTag.contains(CURRENT_DURATION_TAG) ? compoundTag.getInt(CURRENT_DURATION_TAG) : 0;
this.instantStartTime = compoundTag.contains(INSTANT_START_TIME_TAG) ? compoundTag.getLong(INSTANT_START_TIME_TAG) : 0;
this.infinite = this.mobEffect == null || (compoundTag.contains(INFINITE_TAG) && compoundTag.getBoolean(INFINITE_TAG));
this.range = compoundTag.contains(RANGE_TAG) ? compoundTag.getInt(RANGE_TAG) : DEFAULT_RANGE;
this.lingerTime = compoundTag.contains(LINGER_TIME_TAG) ? compoundTag.getInt(LINGER_TIME_TAG) : DEFAULT_LINGER_TIME;
if (this.level instanceof ClientLevel) {
this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), 8);
}
}
|
@Override
public void load(CompoundTag compoundTag) {
super.load(compoundTag);
this.color = compoundTag.contains(COLOR_TAG) ? compoundTag.getInt(COLOR_TAG) : DEFAULT_COLOR;
if (compoundTag.contains(STATUS_EFFECT_TAG) && !compoundTag.getString(STATUS_EFFECT_TAG).trim().equals("")) {
this.mobEffect = BuiltInRegistries.MOB_EFFECT.getOptional(new ResourceLocation(compoundTag.getString(STATUS_EFFECT_TAG))).orElse(null);
}
else {
this.mobEffect = null;
}
this.amplifier = compoundTag.contains(AMPLIFIER_TAG) ? compoundTag.getInt(AMPLIFIER_TAG) : 0;
this.maxDuration = compoundTag.contains(MAX_DURATION_TAG) ? compoundTag.getInt(MAX_DURATION_TAG) : DEFAULT_MAX_DURATION;
this.currentDuration = compoundTag.contains(CURRENT_DURATION_TAG) ? compoundTag.getInt(CURRENT_DURATION_TAG) : 0;
this.instantStartTime = compoundTag.contains(INSTANT_START_TIME_TAG) ? compoundTag.getLong(INSTANT_START_TIME_TAG) : 0;
this.infinite = this.mobEffect == null || (compoundTag.contains(INFINITE_TAG) && compoundTag.getBoolean(INFINITE_TAG));
this.range = compoundTag.contains(RANGE_TAG) ? compoundTag.getInt(RANGE_TAG) : DEFAULT_RANGE;
this.lingerTime = compoundTag.contains(LINGER_TIME_TAG) ? compoundTag.getInt(LINGER_TIME_TAG) : DEFAULT_LINGER_TIME;
if (this.level != null && this.level.isClientSide()) {
this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), 8);
}
}
| null | null | null |
https://github.com/TelepathicGrunt/Bumblezone/commit/920145e344a09483c3be9eb9c1d761394e03c119
|
fixed incense candle server crash
|
src/main/java/com/telepathicgrunt/the_bumblezone/blocks/blockentities/IncenseCandleBlockEntity.java
|
java
|
2022-12-03T15:50:15Z
|
void CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[512], vpred[2][2], hpred[2];
fseek (ifp, 8, SEEK_CUR);
foveon_huff (huff);
roff[0] = 48;
FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
FORC3 {
fseek (ifp, data_offset+roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
image[row*width+col][c] = hpred[col & 1];
}
}
}
}
|
void CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[1024], vpred[2][2], hpred[2];
fseek (ifp, 8, SEEK_CUR);
foveon_huff (huff);
roff[0] = 48;
FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
FORC3 {
fseek (ifp, data_offset+roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
image[row*width+col][c] = hpred[col & 1];
}
}
}
}
| null |
CWE-119, CWE-787, CWE-190
| null |
https://github.com/LibRaw/LibRaw-demosaic-pack-GPL2/commit/194f592e205990ea8fce72b6c571c14350aca716
|
Fixed possible foveon buffer overrun (Secunia SA750000)
| null | null |
2017-03-04T16:55:24Z
|
private void blockIdOrDataChanged() {
int blockType = comboBoxBlockType.getSelectedIndex();
int dataValue = (Integer) spinnerDataValue.getValue();
material = Material.get(blockType, dataValue);
namespace = material.namespace;
simpleName = material.simpleName;
loadActualProperties();
updateModernIds();
firePropertyChange("material", null, getMaterial());
}
|
private void blockIdOrDataChanged() {
int blockType = comboBoxBlockType.getSelectedIndex();
int dataValue = (Integer) spinnerDataValue.getValue();
if ((blockType < 0) || (blockType > 4095) || (dataValue < 0) || (dataValue > 15)) {
// No idea why this happens, but it has been observed in the wild TODO find out why and fix the underlying
// cause
logger.error("blockIdOrDataChanged(): blockType = {}, dataValue = {}, comboBoxMinecraftName.selectedItem = {}, comboBoxNamespace.selectedItem = {}, comboBoxCustomName.selectedItem = {}", blockType, dataValue, comboBoxMinecraftName.getSelectedItem(), comboBoxNamespace.getSelectedItem(), comboBoxCustomName.getSelectedItem());
return;
}
material = Material.get(blockType, dataValue);
namespace = material.namespace;
simpleName = material.simpleName;
loadActualProperties();
updateModernIds();
firePropertyChange("material", null, getMaterial());
}
| null | null | null |
https://github.com/Captain-Chaos/WorldPainter/commit/020c7d3eb35f818f61931d073e9885bc8ce1bca8
|
Bug fix: actions that need a world and/or dimension to be set beep instead of crashing
Don't crash when stored hidden palette name does not exist as a palette (not clear how that can happen; perhaps it only contains hidden layers from CombinedLayers?)
|
WorldPainter/WPGUI/src/main/java/org/pepsoft/worldpainter/MaterialSelector.java
|
java
|
2022-10-23T12:19:29Z
|
public void addObjectLight(TileObject tileObject, int plane, int sizeX, int sizeY, int orientation)
{
for (Light l : OBJECT_LIGHTS.get(tileObject.getId()))
{
// prevent duplicate lights being spawned for the same object
if (sceneLights.stream().anyMatch(light -> light.object != null && tileObjectHash(light.object) == tileObjectHash(tileObject)))
{
continue;
}
WorldPoint worldLocation = tileObject.getWorldLocation();
SceneLight light = new SceneLight(
worldLocation.getX(), worldLocation.getY(), worldLocation.getPlane(), l.height, l.alignment, l.radius,
l.strength, l.color, l.type, l.duration, l.range, 0);
LocalPoint localLocation = tileObject.getLocalLocation();
light.x = localLocation.getX();
light.y = localLocation.getY();
int lightX = tileObject.getX();
int lightY = tileObject.getY();
int localSizeX = sizeX * Perspective.LOCAL_TILE_SIZE;
int localSizeY = sizeY * Perspective.LOCAL_TILE_SIZE;
if (orientation != -1 && light.alignment != Alignment.CENTER)
{
float radius = localSizeX / 2f;
if (!light.alignment.radial)
{
radius = (float) Math.sqrt(localSizeX * localSizeX + localSizeX * localSizeX) / 2;
}
if (!light.alignment.relative)
{
orientation = 0;
}
orientation += light.alignment.orientation;
orientation %= 2048;
float sine = Perspective.SINE[orientation] / 65536f;
float cosine = Perspective.COSINE[orientation] / 65536f;
cosine /= (float) localSizeX / (float) localSizeY;
int offsetX = (int) (radius * sine);
int offsetY = (int) (radius * cosine);
lightX += offsetX;
lightY += offsetY;
}
float tileX = (float) lightX / Perspective.LOCAL_TILE_SIZE;
float tileY = (float) lightY / Perspective.LOCAL_TILE_SIZE;
float lerpX = (lightX % Perspective.LOCAL_TILE_SIZE) / (float) Perspective.LOCAL_TILE_SIZE;
float lerpY = (lightY % Perspective.LOCAL_TILE_SIZE) / (float) Perspective.LOCAL_TILE_SIZE;
int tileMinX = (int) Math.floor(tileX);
int tileMinY = (int) Math.floor(tileY);
int tileMaxX = tileMinX + 1;
int tileMaxY = tileMinY + 1;
tileMinX = Ints.constrainToRange(tileMinX, 0, Constants.SCENE_SIZE - 1);
tileMinY = Ints.constrainToRange(tileMinY, 0, Constants.SCENE_SIZE - 1);
tileMaxX = Ints.constrainToRange(tileMaxX, 0, Constants.SCENE_SIZE - 1);
tileMaxY = Ints.constrainToRange(tileMaxY, 0, Constants.SCENE_SIZE - 1);
float heightNorth = HDUtils.lerp(
client.getTileHeights()[plane][tileMinX][tileMaxY],
client.getTileHeights()[plane][tileMaxX][tileMaxY],
lerpX);
float heightSouth = HDUtils.lerp(
client.getTileHeights()[plane][tileMinX][tileMinY],
client.getTileHeights()[plane][tileMaxX][tileMinY],
lerpX);
float tileHeight = HDUtils.lerp(heightSouth, heightNorth, lerpY);
light.x = lightX;
light.y = lightY;
light.z = (int) tileHeight - light.height - 1;
light.object = tileObject;
sceneLights.add(light);
}
}
|
public void addObjectLight(TileObject tileObject, int plane, int sizeX, int sizeY, int orientation)
{
for (Light l : OBJECT_LIGHTS.get(tileObject.getId()))
{
// prevent objects at plane -1 and under from having lights
if (tileObject.getPlane() <= -1) {
continue;
}
// prevent duplicate lights being spawned for the same object
if (sceneLights.stream().anyMatch(light -> light.object != null && tileObjectHash(light.object) == tileObjectHash(tileObject)))
{
continue;
}
WorldPoint worldLocation = tileObject.getWorldLocation();
SceneLight light = new SceneLight(
worldLocation.getX(), worldLocation.getY(), worldLocation.getPlane(), l.height, l.alignment, l.radius,
l.strength, l.color, l.type, l.duration, l.range, 0);
LocalPoint localLocation = tileObject.getLocalLocation();
light.x = localLocation.getX();
light.y = localLocation.getY();
int lightX = tileObject.getX();
int lightY = tileObject.getY();
int localSizeX = sizeX * Perspective.LOCAL_TILE_SIZE;
int localSizeY = sizeY * Perspective.LOCAL_TILE_SIZE;
if (orientation != -1 && light.alignment != Alignment.CENTER)
{
float radius = localSizeX / 2f;
if (!light.alignment.radial)
{
radius = (float) Math.sqrt(localSizeX * localSizeX + localSizeX * localSizeX) / 2;
}
if (!light.alignment.relative)
{
orientation = 0;
}
orientation += light.alignment.orientation;
orientation %= 2048;
float sine = Perspective.SINE[orientation] / 65536f;
float cosine = Perspective.COSINE[orientation] / 65536f;
cosine /= (float) localSizeX / (float) localSizeY;
int offsetX = (int) (radius * sine);
int offsetY = (int) (radius * cosine);
lightX += offsetX;
lightY += offsetY;
}
float tileX = (float) lightX / Perspective.LOCAL_TILE_SIZE;
float tileY = (float) lightY / Perspective.LOCAL_TILE_SIZE;
float lerpX = (lightX % Perspective.LOCAL_TILE_SIZE) / (float) Perspective.LOCAL_TILE_SIZE;
float lerpY = (lightY % Perspective.LOCAL_TILE_SIZE) / (float) Perspective.LOCAL_TILE_SIZE;
int tileMinX = (int) Math.floor(tileX);
int tileMinY = (int) Math.floor(tileY);
int tileMaxX = tileMinX + 1;
int tileMaxY = tileMinY + 1;
tileMinX = Ints.constrainToRange(tileMinX, 0, Constants.SCENE_SIZE - 1);
tileMinY = Ints.constrainToRange(tileMinY, 0, Constants.SCENE_SIZE - 1);
tileMaxX = Ints.constrainToRange(tileMaxX, 0, Constants.SCENE_SIZE - 1);
tileMaxY = Ints.constrainToRange(tileMaxY, 0, Constants.SCENE_SIZE - 1);
float heightNorth = HDUtils.lerp(
client.getTileHeights()[plane][tileMinX][tileMaxY],
client.getTileHeights()[plane][tileMaxX][tileMaxY],
lerpX);
float heightSouth = HDUtils.lerp(
client.getTileHeights()[plane][tileMinX][tileMinY],
client.getTileHeights()[plane][tileMaxX][tileMinY],
lerpX);
float tileHeight = HDUtils.lerp(heightSouth, heightNorth, lerpY);
light.x = lightX;
light.y = lightY;
light.z = (int) tileHeight - light.height - 1;
light.object = tileObject;
sceneLights.add(light);
}
}
| null | null | null |
https://github.com/RS117/RLHD/commit/300fe8495d5cd4d4d1bad9a9f36f694d08017950
|
Light Crash Fixes (#322)
* Light Crash Fixes
Made it to if the plane is -1 or under it defaults to 0 to stop any crashes
* Object 14419 is what was causing the issues
- Ignore Objects at -1 and below
- Ignore Npcs at -1 and below
|
src/main/java/rs117/hd/scene/lighting/LightManager.java
|
java
|
2022-07-01T23:41:47Z
|
static void nbd_co_receive_reply(NBDClientSession *s,
NBDRequest *request,
NBDReply *reply,
QEMUIOVector *qiov)
{
int ret;
qemu_coroutine_yield();
*reply = s->reply;
if (reply->handle != request->handle ||
!s->ioc) {
reply->error = EIO;
} else {
if (qiov && reply->error == 0) {
ret = nbd_rwv(s->ioc, qiov->iov, qiov->niov, request->len, true,
NULL);
if (ret != request->len) {
reply->error = EIO;
}
}
s->reply.handle = 0;
}
}
|
static void nbd_co_receive_reply(NBDClientSession *s,
NBDRequest *request,
NBDReply *reply,
QEMUIOVector *qiov)
{
int ret;
qemu_coroutine_yield();
*reply = s->reply;
if (reply->handle != request->handle || !s->ioc || s->quit) {
reply->error = EIO;
} else {
if (qiov && reply->error == 0) {
ret = nbd_rwv(s->ioc, qiov->iov, qiov->niov, request->len, true,
NULL);
if (ret != request->len) {
reply->error = EIO;
}
}
s->reply.handle = 0;
}
}
| null | null | null |
qemu/commit/72b6ffc76653214b69a94a7b1643ff80df134486
|
nbd-client: Fix regression when server sends garbage
When we switched NBD to use coroutines for qemu 2.9 (in particular,
commit a12a712a), we introduced a regression: if a server sends us
garbage (such as a corrupted magic number), we quit the read loop
but do not stop sending further queued commands, resulting in the
client hanging when it never reads the response to those additional
commands. In qemu 2.8, we properly detected that the server is no
longer reliable, and cancelled all existing pending commands with
EIO, then tore down the socket so that all further command attempts
get EPIPE.
Restore the proper behavior of quitting (almost) all communication
with a broken server: Once we know we are out of sync or otherwise
can't trust the server, we must assume that any further incoming
data is unreliable and therefore end all pending commands with EIO,
and quit trying to send any further commands. As an exception, we
still (try to) send NBD_CMD_DISC to let the server know we are going
away (in part, because it is easier to do that than to further
refactor nbd_teardown_connection, and in part because it is the
only command where we do not have to wait for a reply).
Based on a patch by Vladimir Sementsov-Ogievskiy.
A malicious server can be created with the following hack,
followed by setting NBD_SERVER_DEBUG to a non-zero value in the
environment when running qemu-nbd:
| --- a/nbd/server.c
| +++ b/nbd/server.c
| @@ -919,6 +919,17 @@ static int nbd_send_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)
| stl_be_p(buf + 4, reply->error)
| stq_be_p(buf + 8, reply->handle)
|
| + static int debug
| + static int count
| + if (!count++) {
| + const char *str = getenv("NBD_SERVER_DEBUG")
| + if (str) {
| + debug = atoi(str)
| + }
| + }
| + if (debug && !(count % debug)) {
| + buf[0] = 0
| + }
| return nbd_write(ioc, buf, sizeof(buf), errp)
| }
Reported-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
Message-Id: <20170814213426.24681-1-eblake@redhat.com>
Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com>
|
./qemu/block/nbd-client.c
|
c
|
2017-08-14T21:34:26Z
|
PUBLIC ssize httpWriteUploadData(HttpConn *conn, MprList *fileData, MprList *formData)
{
char *path, *pair, *key, *value, *name;
cchar *type;
ssize rc;
int next;
rc = 0;
if (formData) {
for (rc = next = 0; rc >= 0 && (pair = mprGetNextItem(formData, &next)) != 0; ) {
key = stok(sclone(pair), "=", &value);
rc += httpWrite(conn->writeq, "%s\r\nContent-Disposition: form-data; name=\"%s\";\r\n", conn->boundary, key);
rc += httpWrite(conn->writeq, "Content-Type: application/x-www-form-urlencoded\r\n\r\n%s\r\n", value);
}
}
if (fileData) {
for (rc = next = 0; rc >= 0 && (path = mprGetNextItem(fileData, &next)) != 0; ) {
if (!mprPathExists(path, R_OK)) {
httpError(conn, HTTP_CODE_NOT_FOUND, "Cannot open %s", path);
return MPR_ERR_CANT_OPEN;
}
name = mprGetPathBase(path);
rc += httpWrite(conn->writeq, "%s\r\nContent-Disposition: form-data; name=\"file%d\"; filename=\"%s\"\r\n",
conn->boundary, next - 1, name);
if ((type = mprLookupMime(MPR->mimeTypes, path)) != 0) {
rc += httpWrite(conn->writeq, "Content-Type: %s\r\n", mprLookupMime(MPR->mimeTypes, path));
}
httpWrite(conn->writeq, "\r\n");
if (blockingFileCopy(conn, path) < 0) {
return MPR_ERR_CANT_WRITE;
}
rc += httpWrite(conn->writeq, "\r\n");
}
}
rc += httpWrite(conn->writeq, "%s--\r\n--", conn->boundary);
return rc;
}
|
PUBLIC ssize httpWriteUploadData(HttpConn *conn, MprList *fileData, MprList *formData)
{
char *path, *pair, *key, *value, *name;
cchar *type;
ssize rc;
int next;
rc = 0;
if (formData) {
for (rc = next = 0; rc >= 0 && (pair = mprGetNextItem(formData, &next)) != 0; ) {
key = ssplit(sclone(pair), "=", &value);
rc += httpWrite(conn->writeq, "%s\r\nContent-Disposition: form-data; name=\"%s\";\r\n", conn->boundary, key);
rc += httpWrite(conn->writeq, "Content-Type: application/x-www-form-urlencoded\r\n\r\n%s\r\n", value);
}
}
if (fileData) {
for (rc = next = 0; rc >= 0 && (path = mprGetNextItem(fileData, &next)) != 0; ) {
if (!mprPathExists(path, R_OK)) {
httpError(conn, HTTP_CODE_NOT_FOUND, "Cannot open %s", path);
return MPR_ERR_CANT_OPEN;
}
name = mprGetPathBase(path);
rc += httpWrite(conn->writeq, "%s\r\nContent-Disposition: form-data; name=\"file%d\"; filename=\"%s\"\r\n",
conn->boundary, next - 1, name);
if ((type = mprLookupMime(MPR->mimeTypes, path)) != 0) {
rc += httpWrite(conn->writeq, "Content-Type: %s\r\n", mprLookupMime(MPR->mimeTypes, path));
}
httpWrite(conn->writeq, "\r\n");
if (blockingFileCopy(conn, path) < 0) {
return MPR_ERR_CANT_WRITE;
}
rc += httpWrite(conn->writeq, "\r\n");
}
}
rc += httpWrite(conn->writeq, "%s--\r\n--", conn->boundary);
return rc;
}
|
CVE-2014-9708
|
CWE-476
|
Embedthis Appweb before 4.6.6 and 5.x before 5.2.1 allows remote attackers to cause a denial of service (NULL pointer dereference) via a Range header with an empty value, as demonstrated by "Range: x=,".
|
https://github.com/embedthis/appweb/commit/7e6a925f5e86a19a7934a94bbd6959101d0b84eb
|
DEV: switch to use ssplit and mprReadJson
ssplit is more robust than stok because it does not return null
mprReadJson is faster, simpler and does not support dotted keys.
|
httpLib.c
|
c
|
2015-03-31T14:59:00Z
|
struct clock_source *dce100_clock_source_create(
struct dc_context *ctx,
struct dc_bios *bios,
enum clock_source_id id,
const struct dce110_clk_src_regs *regs,
bool dp_clk_src)
{
struct dce110_clk_src *clk_src =
kzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);
if (!clk_src)
return NULL;
if (dce110_clk_src_construct(clk_src, ctx, bios, id,
regs, &cs_shift, &cs_mask)) {
clk_src->base.dp_clk_src = dp_clk_src;
return &clk_src->base;
}
BREAK_TO_DEBUGGER();
return NULL;
}
|
struct clock_source *dce100_clock_source_create(
struct dc_context *ctx,
struct dc_bios *bios,
enum clock_source_id id,
const struct dce110_clk_src_regs *regs,
bool dp_clk_src)
{
struct dce110_clk_src *clk_src =
kzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);
if (!clk_src)
return NULL;
if (dce110_clk_src_construct(clk_src, ctx, bios, id,
regs, &cs_shift, &cs_mask)) {
clk_src->base.dp_clk_src = dp_clk_src;
return &clk_src->base;
}
kfree(clk_src);
BREAK_TO_DEBUGGER();
return NULL;
}
|
CVE-2019-19083
|
CWE-703
|
Memory leaks in *clock_source_create() functions under drivers/gpu/drm/amd/display/dc in the Linux kernel before 5.3.8 allow attackers to cause a denial of service (memory consumption). This affects the dce112_clock_source_create() function in drivers/gpu/drm/amd/display/dc/dce112/dce112_resource.c, the dce100_clock_source_create() function in drivers/gpu/drm/amd/display/dc/dce100/dce100_resource.c, the dcn10_clock_source_create() function in drivers/gpu/drm/amd/display/dc/dcn10/dcn10_resource.c, the dcn20_clock_source_create() function in drivers/gpu/drm/amd/display/dc/dcn20/dcn20_resource.c, the dce120_clock_source_create() function in drivers/gpu/drm/amd/display/dc/dce120/dce120_resource.c, the dce110_clock_source_create() function in drivers/gpu/drm/amd/display/dc/dce110/dce110_resource.c, and the dce80_clock_source_create() function in drivers/gpu/drm/amd/display/dc/dce80/dce80_resource.c, aka CID-055e547478a1.
|
https://github.com/torvalds/linux/commit/055e547478a11a6360c7ce05e2afc3e366968a12
|
drm/amd/display: memory leak
In dcn*_clock_source_create when dcn20_clk_src_construct fails allocated
clk_src needs release.
Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>
Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
|
dce100_resource.c
|
c
|
2019-09-17T03:20:44Z
|
get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp)
{
static gpols_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gpols_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
prime_arg = arg->exp;
if (prime_arg == NULL)
prime_arg = "*";
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_LIST, NULL, NULL)) {
ret.code = KADM5_AUTH_LIST;
log_unauth("kadm5_get_policies", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_policies((void *)handle,
arg->exp, &ret.pols,
&ret.count);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_policies", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
|
get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp)
{
static gpols_ret ret;
char *prime_arg;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gpols_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
prime_arg = arg->exp;
if (prime_arg == NULL)
prime_arg = "*";
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_LIST, NULL, NULL)) {
ret.code = KADM5_AUTH_LIST;
log_unauth("kadm5_get_policies", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_policies((void *)handle,
arg->exp, &ret.pols,
&ret.count);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_policies", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
|
CVE-2015-8631
|
CWE-772
|
Multiple memory leaks in kadmin/server/server_stubs.c in kadmind in MIT Kerberos 5 (aka krb5) before 1.13.4 and 1.14.x before 1.14.1 allow remote authenticated users to cause a denial of service (memory consumption) via a request specifying a NULL principal name.
|
https://github.com/krb5/krb5/commit/83ed75feba32e46f736fcce0d96a0445f29b96c2
|
Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
|
server_stubs.c
|
c
|
2016-01-08T18:16:54Z
|
scsi_nl_rcv_msg(struct sk_buff *skb)
{
struct nlmsghdr *nlh;
struct scsi_nl_hdr *hdr;
u32 rlen;
int err, tport;
while (skb->len >= NLMSG_HDRLEN) {
err = 0;
nlh = nlmsg_hdr(skb);
if ((nlh->nlmsg_len < (sizeof(*nlh) + sizeof(*hdr))) ||
(skb->len < nlh->nlmsg_len)) {
printk(KERN_WARNING "%s: discarding partial skb\n",
__func__);
return;
}
rlen = NLMSG_ALIGN(nlh->nlmsg_len);
if (rlen > skb->len)
rlen = skb->len;
if (nlh->nlmsg_type != SCSI_TRANSPORT_MSG) {
err = -EBADMSG;
goto next_msg;
}
hdr = nlmsg_data(nlh);
if ((hdr->version != SCSI_NL_VERSION) ||
(hdr->magic != SCSI_NL_MAGIC)) {
err = -EPROTOTYPE;
goto next_msg;
}
if (!capable(CAP_SYS_ADMIN)) {
err = -EPERM;
goto next_msg;
}
if (nlh->nlmsg_len < (sizeof(*nlh) + hdr->msglen)) {
printk(KERN_WARNING "%s: discarding partial message\n",
__func__);
goto next_msg;
}
/*
* Deliver message to the appropriate transport
*/
tport = hdr->transport;
if (tport == SCSI_NL_TRANSPORT) {
switch (hdr->msgtype) {
case SCSI_NL_SHOST_VENDOR:
/* Locate the driver that corresponds to the message */
err = -ESRCH;
break;
default:
err = -EBADR;
break;
}
if (err)
printk(KERN_WARNING "%s: Msgtype %d failed - err %d\n",
__func__, hdr->msgtype, err);
}
else
err = -ENOENT;
next_msg:
if ((err) || (nlh->nlmsg_flags & NLM_F_ACK))
netlink_ack(skb, nlh, err);
skb_pull(skb, rlen);
}
}
|
scsi_nl_rcv_msg(struct sk_buff *skb)
{
struct nlmsghdr *nlh;
struct scsi_nl_hdr *hdr;
u32 rlen;
int err, tport;
while (skb->len >= NLMSG_HDRLEN) {
err = 0;
nlh = nlmsg_hdr(skb);
if ((nlh->nlmsg_len < (sizeof(*nlh) + sizeof(*hdr))) ||
(skb->len < nlh->nlmsg_len)) {
printk(KERN_WARNING "%s: discarding partial skb\n",
__func__);
return;
}
rlen = NLMSG_ALIGN(nlh->nlmsg_len);
if (rlen > skb->len)
rlen = skb->len;
if (nlh->nlmsg_type != SCSI_TRANSPORT_MSG) {
err = -EBADMSG;
goto next_msg;
}
hdr = nlmsg_data(nlh);
if ((hdr->version != SCSI_NL_VERSION) ||
(hdr->magic != SCSI_NL_MAGIC)) {
err = -EPROTOTYPE;
goto next_msg;
}
if (!netlink_capable(skb, CAP_SYS_ADMIN)) {
err = -EPERM;
goto next_msg;
}
if (nlh->nlmsg_len < (sizeof(*nlh) + hdr->msglen)) {
printk(KERN_WARNING "%s: discarding partial message\n",
__func__);
goto next_msg;
}
/*
* Deliver message to the appropriate transport
*/
tport = hdr->transport;
if (tport == SCSI_NL_TRANSPORT) {
switch (hdr->msgtype) {
case SCSI_NL_SHOST_VENDOR:
/* Locate the driver that corresponds to the message */
err = -ESRCH;
break;
default:
err = -EBADR;
break;
}
if (err)
printk(KERN_WARNING "%s: Msgtype %d failed - err %d\n",
__func__, hdr->msgtype, err);
}
else
err = -ENOENT;
next_msg:
if ((err) || (nlh->nlmsg_flags & NLM_F_ACK))
netlink_ack(skb, nlh, err);
skb_pull(skb, rlen);
}
}
|
CVE-2014-0181
|
CWE-264
|
The Netlink implementation in the Linux kernel through 3.14.1 does not provide a mechanism for authorizing socket operations based on the opener of a socket, which allows local users to bypass intended access restrictions and modify network configurations by using a Netlink socket for the (1) stdout or (2) stderr of a setuid program.
|
https://git.kernel.org/cgit/linux/kernel/git/davem/net.git/commit/?id=90f62cf30a78721641e08737bda787552428061e
|
net: Use netlink_ns_capable to verify the permisions of netlink messages
It is possible by passing a netlink socket to a more privileged
executable and then to fool that executable into writing to the socket
data that happens to be valid netlink message to do something that
privileged executable did not intend to do.
To keep this from happening replace bare capable and ns_capable calls
with netlink_capable, netlink_net_calls and netlink_ns_capable calls.
Which act the same as the previous calls except they verify that the
opener of the socket had the desired permissions as well.
Reported-by: Andy Lutomirski <luto@amacapital.net>
Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
| null | null | null |
char* _multi_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc( len + 2 );
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
chr[ len ++ ] = '\0';
return chr;
}
|
char* _multi_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return NULL;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc( len + 2 );
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
chr[ len ++ ] = '\0';
return chr;
}
|
CVE-2018-7485
|
CWE-119
|
The SQLWriteFileDSN function in odbcinst/SQLWriteFileDSN.c in unixODBC 2.3.5 has strncpy arguments in the wrong order, which allows attackers to cause a denial of service or possibly have unspecified other impact.
|
https://github.com/lurcher/unixODBC/commit/45ef78e037f578b15fc58938a3a3251655e71d6f
|
New Pre Source
|
SQLSetDescField.c
|
c
|
2018-01-08T11:12:39Z
|
private NSBitmapImageRep createRepresentation(ImageData imageData, AlphaInfo alphaInfo) {
NSBitmapImageRep rep = (NSBitmapImageRep)new NSBitmapImageRep().alloc();
PaletteData palette = imageData.palette;
if (!(((imageData.depth == 1 || imageData.depth == 2 || imageData.depth == 4 || imageData.depth == 8) && !palette.isDirect) ||
((imageData.depth == 8) || (imageData.depth == 16 || imageData.depth == 24 || imageData.depth == 32) && palette.isDirect)))
SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH);
/* Create the image */
int dataSize = imageData.width * imageData.height * 4;
/* Initialize data */
int bpr = imageData.width * 4;
byte[] buffer = new byte[dataSize];
if (palette.isDirect) {
ImageData.blit(
imageData.data, imageData.depth, imageData.bytesPerLine, imageData.getByteOrder(), imageData.width, imageData.height, palette.redMask, palette.greenMask, palette.blueMask,
buffer, 32, bpr, ImageData.MSB_FIRST, imageData.width, imageData.height, 0xFF0000, 0xFF00, 0xFF,
false, false);
} else {
RGB[] rgbs = palette.getRGBs();
int length = rgbs.length;
byte[] srcReds = new byte[length];
byte[] srcGreens = new byte[length];
byte[] srcBlues = new byte[length];
for (int i = 0; i < rgbs.length; i++) {
RGB rgb = rgbs[i];
if (rgb == null) continue;
srcReds[i] = (byte)rgb.red;
srcGreens[i] = (byte)rgb.green;
srcBlues[i] = (byte)rgb.blue;
}
ImageData.blit(
imageData.width, imageData.height,
imageData.data, imageData.depth, imageData.bytesPerLine, imageData.getByteOrder(), srcReds, srcGreens, srcBlues,
buffer, 32, bpr, ImageData.MSB_FIRST, 0xFF0000, 0xFF00, 0xFF);
}
/* Initialize transparency */
int transparency = imageData.getTransparencyType();
boolean hasAlpha = transparency != SWT.TRANSPARENCY_NONE;
if (transparency == SWT.TRANSPARENCY_MASK || imageData.transparentPixel != -1) {
this.type = imageData.transparentPixel != -1 ? SWT.BITMAP : SWT.ICON;
if (imageData.transparentPixel != -1) {
int transRed = 0, transGreen = 0, transBlue = 0;
if (palette.isDirect) {
RGB rgb = palette.getRGB(imageData.transparentPixel);
transRed = rgb.red;
transGreen = rgb.green;
transBlue = rgb.blue;
} else {
RGB[] rgbs = palette.getRGBs();
if (imageData.transparentPixel < rgbs.length) {
RGB rgb = rgbs[imageData.transparentPixel];
transRed = rgb.red;
transGreen = rgb.green;
transBlue = rgb.blue;
}
}
alphaInfo.transparentPixel = transRed << 16 | transGreen << 8 | transBlue;
}
ImageData maskImage = imageData.getTransparencyMask();
byte[] maskData = maskImage.data;
int maskBpl = maskImage.bytesPerLine;
int offset = 0, maskOffset = 0;
for (int y = 0; y<imageData.height; y++) {
for (int x = 0; x<imageData.width; x++) {
buffer[offset] = ((maskData[maskOffset + (x >> 3)]) & (1 << (7 - (x & 0x7)))) != 0 ? (byte)0xff : 0;
offset += 4;
}
maskOffset += maskBpl;
}
} else {
this.type = SWT.BITMAP;
if (imageData.alpha != -1) {
hasAlpha = true;
alphaInfo.alpha = imageData.alpha;
byte a = (byte)alphaInfo.alpha;
for (int dataIndex=0; dataIndex<buffer.length; dataIndex+=4) {
buffer[dataIndex] = a;
}
} else if (imageData.alphaData != null) {
hasAlpha = true;
alphaInfo.alphaData = new byte[imageData.alphaData.length];
System.arraycopy(imageData.alphaData, 0, alphaInfo.alphaData, 0, alphaInfo.alphaData.length);
int offset = 0, alphaOffset = 0;
for (int y = 0; y<imageData.height; y++) {
for (int x = 0; x<imageData.width; x++) {
buffer[offset] = alphaInfo.alphaData[alphaOffset];
offset += 4;
alphaOffset += 1;
}
}
}
}
rep = rep.initWithBitmapDataPlanes(0, imageData.width, imageData.height, 8, hasAlpha ? 4 : 3, hasAlpha, false, OS.NSDeviceRGBColorSpace, OS.NSAlphaFirstBitmapFormat | OS.NSAlphaNonpremultipliedBitmapFormat, bpr, 32);
C.memmove(rep.bitmapData(), buffer, dataSize);
return rep;
}
|
private NSBitmapImageRep createRepresentation(ImageData imageData, AlphaInfo alphaInfo) {
NSBitmapImageRep rep = (NSBitmapImageRep)new NSBitmapImageRep().alloc();
PaletteData palette = imageData.palette;
if (!(((imageData.depth == 1 || imageData.depth == 2 || imageData.depth == 4 || imageData.depth == 8 || imageData.depth == 16) && !palette.isDirect) ||
((imageData.depth == 8) || (imageData.depth == 16 || imageData.depth == 24 || imageData.depth == 32) && palette.isDirect)))
SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH);
/* Create the image */
int dataSize = imageData.width * imageData.height * 4;
/* Initialize data */
int bpr = imageData.width * 4;
byte[] buffer = new byte[dataSize];
if (palette.isDirect) {
ImageData.blit(
imageData.data, imageData.depth, imageData.bytesPerLine, imageData.getByteOrder(), imageData.width, imageData.height, palette.redMask, palette.greenMask, palette.blueMask,
buffer, 32, bpr, ImageData.MSB_FIRST, imageData.width, imageData.height, 0xFF0000, 0xFF00, 0xFF,
false, false);
} else {
RGB[] rgbs = palette.getRGBs();
int length = rgbs.length;
byte[] srcReds = new byte[length];
byte[] srcGreens = new byte[length];
byte[] srcBlues = new byte[length];
for (int i = 0; i < rgbs.length; i++) {
RGB rgb = rgbs[i];
if (rgb == null) continue;
srcReds[i] = (byte)rgb.red;
srcGreens[i] = (byte)rgb.green;
srcBlues[i] = (byte)rgb.blue;
}
ImageData.blit(
imageData.width, imageData.height,
imageData.data, imageData.depth, imageData.bytesPerLine, imageData.getByteOrder(), srcReds, srcGreens, srcBlues,
buffer, 32, bpr, ImageData.MSB_FIRST, 0xFF0000, 0xFF00, 0xFF);
}
/* Initialize transparency */
int transparency = imageData.getTransparencyType();
boolean hasAlpha = transparency != SWT.TRANSPARENCY_NONE;
if (transparency == SWT.TRANSPARENCY_MASK || imageData.transparentPixel != -1) {
this.type = imageData.transparentPixel != -1 ? SWT.BITMAP : SWT.ICON;
if (imageData.transparentPixel != -1) {
int transRed = 0, transGreen = 0, transBlue = 0;
if (palette.isDirect) {
RGB rgb = palette.getRGB(imageData.transparentPixel);
transRed = rgb.red;
transGreen = rgb.green;
transBlue = rgb.blue;
} else {
RGB[] rgbs = palette.getRGBs();
if (imageData.transparentPixel < rgbs.length) {
RGB rgb = rgbs[imageData.transparentPixel];
transRed = rgb.red;
transGreen = rgb.green;
transBlue = rgb.blue;
}
}
alphaInfo.transparentPixel = transRed << 16 | transGreen << 8 | transBlue;
}
ImageData maskImage = imageData.getTransparencyMask();
byte[] maskData = maskImage.data;
int maskBpl = maskImage.bytesPerLine;
int offset = 0, maskOffset = 0;
for (int y = 0; y<imageData.height; y++) {
for (int x = 0; x<imageData.width; x++) {
buffer[offset] = ((maskData[maskOffset + (x >> 3)]) & (1 << (7 - (x & 0x7)))) != 0 ? (byte)0xff : 0;
offset += 4;
}
maskOffset += maskBpl;
}
} else {
this.type = SWT.BITMAP;
if (imageData.alpha != -1) {
hasAlpha = true;
alphaInfo.alpha = imageData.alpha;
byte a = (byte)alphaInfo.alpha;
for (int dataIndex=0; dataIndex<buffer.length; dataIndex+=4) {
buffer[dataIndex] = a;
}
} else if (imageData.alphaData != null) {
hasAlpha = true;
alphaInfo.alphaData = new byte[imageData.alphaData.length];
System.arraycopy(imageData.alphaData, 0, alphaInfo.alphaData, 0, alphaInfo.alphaData.length);
int offset = 0, alphaOffset = 0;
for (int y = 0; y<imageData.height; y++) {
for (int x = 0; x<imageData.width; x++) {
buffer[offset] = alphaInfo.alphaData[alphaOffset];
offset += 4;
alphaOffset += 1;
}
}
}
}
rep = rep.initWithBitmapDataPlanes(0, imageData.width, imageData.height, 8, hasAlpha ? 4 : 3, hasAlpha, false, OS.NSDeviceRGBColorSpace, OS.NSAlphaFirstBitmapFormat | OS.NSAlphaNonpremultipliedBitmapFormat, bpr, 32);
C.memmove(rep.bitmapData(), buffer, dataSize);
return rep;
}
| null | null | null |
https://github.com/eclipse-platform/eclipse.platform.swt/commit/5e05910ac3ed3bece28ee55762e3215542a69d73
|
Issue #232 - Add support for 16bpp indexed ImageData
Also, variables `srcStride`, `destStride` were hijacked into a different
meaning in the old code. I reworked them into new variables with proper
names `srcPixelsPerStride`, `dstPixelsPerStride`.
This commit only supports loading images. Other things remain
unsupported, such as saving images, `ImageData.setPixel()`, etc.
Signed-off-by: Alexandr Miloslavskiy <alexandr.miloslavskiy@syntevo.com>
|
bundles/org.eclipse.swt/Eclipse SWT/cocoa/org/eclipse/swt/graphics/Image.java
|
java
|
2022-07-07T20:14:12Z
|
void dtls1_reset_seq_numbers(SSL *s, int rw)
{
unsigned char *seq;
unsigned int seq_bytes = sizeof(s->s3->read_sequence);
if (rw & SSL3_CC_READ) {
seq = s->s3->read_sequence;
s->d1->r_epoch++;
memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
} else {
seq = s->s3->write_sequence;
memcpy(s->d1->last_write_sequence, seq,
sizeof(s->s3->write_sequence));
s->d1->w_epoch++;
}
memset(seq, 0x00, seq_bytes);
}
|
void dtls1_reset_seq_numbers(SSL *s, int rw)
{
unsigned char *seq;
unsigned int seq_bytes = sizeof(s->s3->read_sequence);
if (rw & SSL3_CC_READ) {
seq = s->s3->read_sequence;
s->d1->r_epoch++;
memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
/*
* We must not use any buffered messages received from the previous
* epoch
*/
dtls1_clear_received_buffer(s);
} else {
seq = s->s3->write_sequence;
memcpy(s->d1->last_write_sequence, seq,
sizeof(s->s3->write_sequence));
s->d1->w_epoch++;
}
memset(seq, 0x00, seq_bytes);
}
|
CVE-2016-2179
|
CWE-399
|
The DTLS implementation in OpenSSL before 1.1.0 does not properly restrict the lifetime of queue entries associated with unused out-of-order messages, which allows remote attackers to cause a denial of service (memory consumption) by maintaining many crafted DTLS sessions simultaneously, related to d1_lib.c, statem_dtls.c, statem_lib.c, and statem_srvr.c.
|
https://github.com/openssl/openssl/commit/cfd40fd39e69f5e3c654ae8fbf9acb1d2a051144
|
Prevent DTLS Finished message injection
Follow on from CVE-2016-2179
The investigation and analysis of CVE-2016-2179 highlighted a related flaw.
This commit fixes a security "near miss" in the buffered message handling
code. Ultimately this is not currently believed to be exploitable due to
the reasons outlined below, and therefore there is no CVE for this on its
own.
The issue this commit fixes is a MITM attack where the attacker can inject
a Finished message into the handshake. In the description below it is
assumed that the attacker injects the Finished message for the server to
receive it. The attack could work equally well the other way around (i.e
where the client receives the injected Finished message).
The MITM requires the following capabilities:
- The ability to manipulate the MTU that the client selects such that it
is small enough for the client to fragment Finished messages.
- The ability to selectively drop and modify records sent from the client
- The ability to inject its own records and send them to the server
The MITM forces the client to select a small MTU such that the client
will fragment the Finished message. Ideally for the attacker the first
fragment will contain all but the last byte of the Finished message,
with the second fragment containing the final byte.
During the handshake and prior to the client sending the CCS the MITM
injects a plaintext Finished message fragment to the server containing
all but the final byte of the Finished message. The message sequence
number should be the one expected to be used for the real Finished message.
OpenSSL will recognise that the received fragment is for the future and
will buffer it for later use.
After the client sends the CCS it then sends its own Finished message in
two fragments. The MITM causes the first of these fragments to be
dropped. The OpenSSL server will then receive the second of the fragments
and reassemble the complete Finished message consisting of the MITM
fragment and the final byte from the real client.
The advantage to the attacker in injecting a Finished message is that
this provides the capability to modify other handshake messages (e.g.
the ClientHello) undetected. A difficulty for the attacker is knowing in
advance what impact any of those changes might have on the final byte of
the handshake hash that is going to be sent in the "real" Finished
message. In the worst case for the attacker this means that only 1 in
256 of such injection attempts will succeed.
It may be possible in some situations for the attacker to improve this such
that all attempts succeed. For example if the handshake includes client
authentication then the final message flight sent by the client will
include a Certificate. Certificates are ASN.1 objects where the signed
portion is DER encoded. The non-signed portion could be BER encoded and so
the attacker could re-encode the certificate such that the hash for the
whole handshake comes to a different value. The certificate re-encoding
would not be detectable because only the non-signed portion is changed. As
this is the final flight of messages sent from the client the attacker
knows what the complete hanshake hash value will be that the client will
send - and therefore knows what the final byte will be. Through a process
of trial and error the attacker can re-encode the certificate until the
modified handhshake also has a hash with the same final byte. This means
that when the Finished message is verified by the server it will be
correct in all cases.
In practice the MITM would need to be able to perform the same attack
against both the client and the server. If the attack is only performed
against the server (say) then the server will not detect the modified
handshake, but the client will and will abort the connection.
Fortunately, although OpenSSL is vulnerable to Finished message
injection, it is not vulnerable if *both* client and server are OpenSSL.
The reason is that OpenSSL has a hard "floor" for a minimum MTU size
that it will never go below. This minimum means that a Finished message
will never be sent in a fragmented form and therefore the MITM does not
have one of its pre-requisites. Therefore this could only be exploited
if using OpenSSL and some other DTLS peer that had its own and separate
Finished message injection flaw.
The fix is to ensure buffered messages are cleared on epoch change.
Reviewed-by: Richard Levitte <levitte@openssl.org>
| null | null |
2016-06-30T14:06:27Z
|
static int override_release(char __user *release, int len)
{
int ret = 0;
char buf[65];
if (current->personality & UNAME26) {
char *rest = UTS_RELEASE;
int ndots = 0;
unsigned v;
while (*rest) {
if (*rest == '.' && ++ndots >= 3)
break;
if (!isdigit(*rest) && *rest != '.')
break;
rest++;
}
v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40;
snprintf(buf, len, "2.6.%u%s", v, rest);
ret = copy_to_user(release, buf, len);
}
return ret;
}
|
static int override_release(char __user *release, int len)
static int override_release(char __user *release, size_t len)
{
int ret = 0;
if (current->personality & UNAME26) {
const char *rest = UTS_RELEASE;
char buf[65] = { 0 };
int ndots = 0;
unsigned v;
size_t copy;
while (*rest) {
if (*rest == '.' && ++ndots >= 3)
break;
if (!isdigit(*rest) && *rest != '.')
break;
rest++;
}
v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40;
copy = min(sizeof(buf), max_t(size_t, 1, len));
copy = scnprintf(buf, copy, "2.6.%u%s", v, rest);
ret = copy_to_user(release, buf, copy + 1);
}
return ret;
}
|
CVE-2012-0957
|
CWE-16
|
The override_release function in kernel/sys.c in the Linux kernel before 3.4.16 allows local users to obtain sensitive information from kernel stack memory via a uname system call in conjunction with a UNAME26 personality.
|
https://github.com/torvalds/linux/commit/2702b1526c7278c4d65d78de209a465d4de2885e
|
kernel/sys.c: fix stack memory content leak via UNAME26
Calling uname() with the UNAME26 personality set allows a leak of kernel
stack contents. This fixes it by defensively calculating the length of
copy_to_user() call, making the len argument unsigned, and initializing
the stack buffer to zero (now technically unneeded, but hey, overkill).
CVE-2012-0957
Reported-by: PaX Team <pageexec@freemail.hu>
Signed-off-by: Kees Cook <keescook@chromium.org>
Cc: Andi Kleen <ak@linux.intel.com>
Cc: PaX Team <pageexec@freemail.hu>
Cc: Brad Spengler <spender@grsecurity.net>
Cc: <stable@vger.kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
|
kernel/sys.c
|
c
|
2012-10-19T20:56:51Z
|
@POST
@Consumes({MEDIA_TYPE_SCIM_JSON, MediaType.APPLICATION_JSON})
@Produces({MEDIA_TYPE_SCIM_JSON + UTF8_CHARSET_FRAGMENT, MediaType.APPLICATION_JSON + UTF8_CHARSET_FRAGMENT})
@HeaderParam("Accept") @DefaultValue(MEDIA_TYPE_SCIM_JSON)
@ProtectedApi(scopes = {"https://jans.io/scim/users.write"})
@RefAdjusted
public Response createUser(
UserResource user,
@QueryParam(QUERY_PARAM_ATTRIBUTES) String attrsList,
@QueryParam(QUERY_PARAM_EXCLUDED_ATTRS) String excludedAttrsList) {
Response response;
try {
log.debug("Executing web service method. createUser");
executeValidation(user);
checkUidExistence(user.getUserName());
assignMetaInformation(user);
ScimResourceUtil.adjustPrimarySubAttributes(user);
ScimCustomPerson person = scim2UserService.preCreateUser(user);
response = externalConstraintsService.applyEntityCheck(person, user,
httpHeaders, uriInfo, HttpMethod.POST, userResourceType);
if (response != null) return response;
scim2UserService.createUser(person, user, endpointUrl);
String json = resourceSerializer.serialize(user, attrsList, excludedAttrsList);
response = Response.created(new URI(user.getMeta().getLocation())).entity(json).build();
} catch (DuplicateEntryException e) {
log.error(e.getMessage());
response = getErrorResponse(Response.Status.CONFLICT, ErrorScimType.UNIQUENESS, e.getMessage());
} catch (SCIMException e) {
log.error("Validation check at createUser returned: {}", e.getMessage());
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_VALUE, e.getMessage());
} catch (Exception e) {
log.error("Failure at createUser method", e);
response = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Unexpected error: " + e.getMessage());
}
return response;
}
|
@POST
@Consumes({MEDIA_TYPE_SCIM_JSON, MediaType.APPLICATION_JSON})
@Produces({MEDIA_TYPE_SCIM_JSON + UTF8_CHARSET_FRAGMENT, MediaType.APPLICATION_JSON + UTF8_CHARSET_FRAGMENT})
@HeaderParam("Accept") @DefaultValue(MEDIA_TYPE_SCIM_JSON)
@ProtectedApi(scopes = {"https://jans.io/scim/users.write"})
@RefAdjusted
public Response createUser(
UserResource user,
@QueryParam(QUERY_PARAM_ATTRIBUTES) String attrsList,
@QueryParam(QUERY_PARAM_EXCLUDED_ATTRS) String excludedAttrsList) {
Response response;
try {
log.debug("Executing web service method. createUser");
executeValidation(user);
if (StringUtils.isEmpty(user.getUserName())) throw new SCIMException("Empty username not allowed");
checkUidExistence(user.getUserName());
assignMetaInformation(user);
ScimResourceUtil.adjustPrimarySubAttributes(user);
ScimCustomPerson person = scim2UserService.preCreateUser(user);
response = externalConstraintsService.applyEntityCheck(person, user,
httpHeaders, uriInfo, HttpMethod.POST, userResourceType);
if (response != null) return response;
scim2UserService.createUser(person, user, endpointUrl);
String json = resourceSerializer.serialize(user, attrsList, excludedAttrsList);
response = Response.created(new URI(user.getMeta().getLocation())).entity(json).build();
} catch (DuplicateEntryException e) {
log.error(e.getMessage());
response = getErrorResponse(Response.Status.CONFLICT, ErrorScimType.UNIQUENESS, e.getMessage());
} catch (SCIMException e) {
log.error("Validation check at createUser returned: {}", e.getMessage());
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_VALUE, e.getMessage());
} catch (Exception e) {
log.error("Failure at createUser method", e);
response = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Unexpected error: " + e.getMessage());
}
return response;
}
| null | null | null |
https://github.com/JanssenProject/jans/commit/4b239af72d8aa9e3a09ff6de19cf315b3863bda2
|
fix: update authn schemes in yaml descriptor #2414 (#2415)
|
jans-scim/server/src/main/java/io/jans/scim/ws/rs/scim2/UserWebService.java
|
java
|
2022-09-19T09:41:42Z
|
static Image *ReadEPTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
EPTInfo
ept_info;
Image
*image;
ImageInfo
*read_info;
MagickBooleanType
status;
MagickOffsetType
offset;
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
ept_info.magick=ReadBlobLSBLong(image);
if (ept_info.magick != 0xc6d3d0c5ul)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
ept_info.postscript_offset=(MagickOffsetType) ReadBlobLSBLong(image);
ept_info.postscript_length=ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
ept_info.tiff_offset=(MagickOffsetType) ReadBlobLSBLong(image);
ept_info.tiff_length=ReadBlobLSBLong(image);
(void) ReadBlobLSBShort(image);
ept_info.postscript=(unsigned char *) AcquireQuantumMemory(
ept_info.postscript_length+1,sizeof(*ept_info.postscript));
if (ept_info.postscript == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(ept_info.postscript,0,(ept_info.postscript_length+1)*
sizeof(*ept_info.postscript));
ept_info.tiff=(unsigned char *) AcquireQuantumMemory(ept_info.tiff_length+1,
sizeof(*ept_info.tiff));
if (ept_info.tiff == (unsigned char *) NULL)
{
ept_info.postscript=(unsigned char *) RelinquishMagickMemory(
ept_info.postscript);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) ResetMagickMemory(ept_info.tiff,0,(ept_info.tiff_length+1)*
sizeof(*ept_info.tiff));
offset=SeekBlob(image,ept_info.tiff_offset,SEEK_SET);
if ((ept_info.tiff_length != 0) && (offset < 30))
{
ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff);
ept_info.postscript=(unsigned char *) RelinquishMagickMemory(
ept_info.postscript);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,ept_info.tiff_length,ept_info.tiff);
if (count != (ssize_t) (ept_info.tiff_length))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageWarning,
"InsufficientImageDataInFile","`%s'",image->filename);
offset=SeekBlob(image,ept_info.postscript_offset,SEEK_SET);
if ((ept_info.postscript_length != 0) && (offset < 30))
{
ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff);
ept_info.postscript=(unsigned char *) RelinquishMagickMemory(
ept_info.postscript);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,ept_info.postscript_length,ept_info.postscript);
if (count != (ssize_t) (ept_info.postscript_length))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageWarning,
"InsufficientImageDataInFile","`%s'",image->filename);
(void) CloseBlob(image);
image=DestroyImage(image);
read_info=CloneImageInfo(image_info);
(void) CopyMagickString(read_info->magick,"EPS",MagickPathExtent);
image=BlobToImage(read_info,ept_info.postscript,ept_info.postscript_length,
exception);
if (image == (Image *) NULL)
{
(void) CopyMagickString(read_info->magick,"TIFF",MagickPathExtent);
image=BlobToImage(read_info,ept_info.tiff,ept_info.tiff_length,exception);
}
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"EPT",MagickPathExtent);
}
ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff);
ept_info.postscript=(unsigned char *) RelinquishMagickMemory(
ept_info.postscript);
return(image);
}
|
static Image *ReadEPTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
EPTInfo
ept_info;
Image
*image;
ImageInfo
*read_info;
MagickBooleanType
status;
MagickOffsetType
offset;
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
ept_info.magick=ReadBlobLSBLong(image);
if (ept_info.magick != 0xc6d3d0c5ul)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
ept_info.postscript_offset=(MagickOffsetType) ReadBlobLSBLong(image);
ept_info.postscript_length=ReadBlobLSBLong(image);
if (ept_info.postscript_length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
ept_info.tiff_offset=(MagickOffsetType) ReadBlobLSBLong(image);
ept_info.tiff_length=ReadBlobLSBLong(image);
if (ept_info.tiff_length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobLSBShort(image);
ept_info.postscript=(unsigned char *) AcquireQuantumMemory(
ept_info.postscript_length+1,sizeof(*ept_info.postscript));
if (ept_info.postscript == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(ept_info.postscript,0,(ept_info.postscript_length+1)*
sizeof(*ept_info.postscript));
ept_info.tiff=(unsigned char *) AcquireQuantumMemory(ept_info.tiff_length+1,
sizeof(*ept_info.tiff));
if (ept_info.tiff == (unsigned char *) NULL)
{
ept_info.postscript=(unsigned char *) RelinquishMagickMemory(
ept_info.postscript);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) ResetMagickMemory(ept_info.tiff,0,(ept_info.tiff_length+1)*
sizeof(*ept_info.tiff));
offset=SeekBlob(image,ept_info.tiff_offset,SEEK_SET);
if ((ept_info.tiff_length != 0) && (offset < 30))
{
ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff);
ept_info.postscript=(unsigned char *) RelinquishMagickMemory(
ept_info.postscript);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,ept_info.tiff_length,ept_info.tiff);
if (count != (ssize_t) (ept_info.tiff_length))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageWarning,
"InsufficientImageDataInFile","`%s'",image->filename);
offset=SeekBlob(image,ept_info.postscript_offset,SEEK_SET);
if ((ept_info.postscript_length != 0) && (offset < 30))
{
ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff);
ept_info.postscript=(unsigned char *) RelinquishMagickMemory(
ept_info.postscript);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,ept_info.postscript_length,ept_info.postscript);
if (count != (ssize_t) (ept_info.postscript_length))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageWarning,
"InsufficientImageDataInFile","`%s'",image->filename);
(void) CloseBlob(image);
image=DestroyImage(image);
read_info=CloneImageInfo(image_info);
(void) CopyMagickString(read_info->magick,"EPS",MagickPathExtent);
image=BlobToImage(read_info,ept_info.postscript,ept_info.postscript_length,
exception);
if (image == (Image *) NULL)
{
(void) CopyMagickString(read_info->magick,"TIFF",MagickPathExtent);
image=BlobToImage(read_info,ept_info.tiff,ept_info.tiff_length,exception);
}
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"EPT",MagickPathExtent);
}
ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff);
ept_info.postscript=(unsigned char *) RelinquishMagickMemory(
ept_info.postscript);
return(image);
}
| null | null | null |
https://github.com/ImageMagick/ImageMagick/commit/a14e7f1f78d99891132e061c05f83aefc59e049a
|
https://github.com/ImageMagick/ImageMagick/issues/524
|
coders/ept.c
|
c
|
2017-06-24T12:23:11Z
|
@Override
public void onDestroy() {
super.onDestroy();
runningProcess.destroy();
}
|
@Override
public void onDestroy() {
super.onDestroy();
if (null != runningProcess) {
runningProcess.destroy();
}
}
| null | null | null |
https://github.com/x0b/rcx/commit/047e5f5ea237729af3253d335d453cf7176154b3
|
StreamingService: Fix crash when service is killed
Ref: NullPointerException @ StreamingService.java:124
|
app/src/main/java/ca/pkay/rcloneexplorer/Services/StreamingService.java
|
java
|
2020-06-03T20:24:08Z
|
void Compute(OpKernelContext* ctx) override {
const Tensor& val = ctx->input(0);
int64 id = ctx->session_state()->GetNewId();
TensorStore::TensorAndKey tk{val, id, requested_device()};
OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));
Tensor* handle = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));
if (ctx->expected_output_dtype(0) == DT_RESOURCE) {
ResourceHandle resource_handle = MakeResourceHandle<Tensor>(
ctx, SessionState::kTensorHandleResourceTypeName,
tk.GetHandle(name()));
resource_handle.set_maybe_type_name(
SessionState::kTensorHandleResourceTypeName);
handle->scalar<ResourceHandle>()() = resource_handle;
} else {
// Legacy behavior in V1.
handle->flat<tstring>().setConstant(tk.GetHandle(name()));
}
}
|
void Compute(OpKernelContext* ctx) override {
const Tensor& val = ctx->input(0);
auto session_state = ctx->session_state();
OP_REQUIRES(ctx, session_state != nullptr,
errors::FailedPrecondition(
"GetSessionHandle called on null session state"));
int64 id = session_state->GetNewId();
TensorStore::TensorAndKey tk{val, id, requested_device()};
OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));
Tensor* handle = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));
if (ctx->expected_output_dtype(0) == DT_RESOURCE) {
ResourceHandle resource_handle = MakeResourceHandle<Tensor>(
ctx, SessionState::kTensorHandleResourceTypeName,
tk.GetHandle(name()));
resource_handle.set_maybe_type_name(
SessionState::kTensorHandleResourceTypeName);
handle->scalar<ResourceHandle>()() = resource_handle;
} else {
// Legacy behavior in V1.
handle->flat<tstring>().setConstant(tk.GetHandle(name()));
}
}
|
CVE-2020-15204
|
cwe-476
|
In eager mode, TensorFlow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1 does not set the session state. Hence, calling `tf.raw_ops.GetSessionHandle` or `tf.raw_ops.GetSessionHandleV2` results in a null pointer dereference In linked snippet, in eager mode, `ctx->session_state()` returns `nullptr`. Since code immediately dereferences this, we get a segmentation fault. The issue is patched in commit 9a133d73ae4b4664d22bd1aa6d654fec13c52ee1, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.
|
github.com/tensorflow/tensorflow/commit/9a133d73ae4b4664d22bd1aa6d654fec13c52ee1
|
Prevent segfault in `GetSessionHandle{,V2}`.
In eager mode, session state is null.
PiperOrigin-RevId: 332548597
Change-Id: If094812c2e094044220b9ba28f7d7601be042f38
|
session_ops.cc
|
cc
|
2020-09-18T23:23:20Z
|
static void *av_mallocz_static(unsigned int size)
{
void *ptr = av_mallocz(size);
if(ptr){
array_static =av_fast_realloc(array_static, &allocated_static, sizeof(void*)*(last_static+1));
if(!array_static)
return NULL;
array_static[last_static++] = ptr;
}
return ptr;
}
|
static void *av_mallocz_static(unsigned int size)
{
return av_mallocz(size);
}
| null | null | null |
FFmpeg/commit/b9c8388710a06544812739eedc0a40d3451491dc
|
As *_static are not deallocated anymore except on program termination
we do not need to keep track of them anymore.
Fixes CID117 RUN2 and various race conditions.
Originally committed as revision 13571 to svn://svn.ffmpeg.org/ffmpeg/trunk
|
./ffmpeg/libavcodec/bitstream.c
|
c
|
2008-05-30T23:26:09Z
|
protected OkHttpClient getHttpClient() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
Authenticator proxyAuthenticator = (route, response) -> {
String credential = Credentials.basic(System.getProperty(HTTP_PROXY_USER), System.getProperty(HTTP_PROXY_PASS));
return response.request().newBuilder()
.header(HEADER_PROXY_AUTH, credential)
.build();
};
OkHttpClient.Builder builder = okHttpClient.newBuilder();
if (logger != null) builder.addInterceptor(logger);
builder.addInterceptor(new RetryInterceptor(retryCount));
return builder.connectTimeout(timeout, timeoutUnit)
.writeTimeout(timeout, timeoutUnit)
.readTimeout(timeout, timeoutUnit)
.proxyAuthenticator(proxyAuthenticator)
.build();
}
|
protected OkHttpClient getHttpClient() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
Authenticator proxyAuthenticator = getAuthenticator();
OkHttpClient.Builder builder = okHttpClient.newBuilder();
if (logger != null) builder.addInterceptor(logger);
builder.addInterceptor(new RetryInterceptor(retryCount));
return builder.connectTimeout(timeout, timeoutUnit)
.writeTimeout(timeout, timeoutUnit)
.readTimeout(timeout, timeoutUnit)
.proxyAuthenticator(proxyAuthenticator)
.build();
}
| null | null | null |
https://github.com/hapifhir/org.hl7.fhir.core/commit/82972d5216f787a6f53dada3b219b23e61a55289
|
Add https-proxy param + fix proxy authorization header (#888)
Co-authored-by: dotasek <david.otasek@smilecdr.com>
|
org.hl7.fhir.r4b/src/main/java/org/hl7/fhir/r4b/utils/client/network/FhirRequestBuilder.java
|
java
|
2022-11-17T16:27:21Z
|
static void perf_event_init_cpu(int cpu)
{
struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
mutex_lock(&swhash->hlist_mutex);
swhash->online = true;
if (swhash->hlist_refcount > 0) {
struct swevent_hlist *hlist;
hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
WARN_ON(!hlist);
rcu_assign_pointer(swhash->swevent_hlist, hlist);
}
mutex_unlock(&swhash->hlist_mutex);
}
|
static void perf_event_init_cpu(int cpu)
{
struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
mutex_lock(&swhash->hlist_mutex);
if (swhash->hlist_refcount > 0) {
struct swevent_hlist *hlist;
hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
WARN_ON(!hlist);
rcu_assign_pointer(swhash->swevent_hlist, hlist);
}
mutex_unlock(&swhash->hlist_mutex);
}
| null |
CWE-416, CWE-362
| null |
https://github.com/torvalds/linux/commit/12ca6ad2e3a896256f086497a7c7406a547ee373
|
perf: Fix race in swevent hash
There's a race on CPU unplug where we free the swevent hash array
while it can still have events on. This will result in a
use-after-free which is BAD.
Simply do not free the hash array on unplug. This leaves the thing
around and no use-after-free takes place.
When the last swevent dies, we do a for_each_possible_cpu() iteration
anyway to clean these up, at which time we'll free it, so no leakage
will occur.
Reported-by: Sasha Levin <sasha.levin@oracle.com>
Tested-by: Sasha Levin <sasha.levin@oracle.com>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Cc: Arnaldo Carvalho de Melo <acme@redhat.com>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Jiri Olsa <jolsa@redhat.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Stephane Eranian <eranian@google.com>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: Vince Weaver <vincent.weaver@maine.edu>
Signed-off-by: Ingo Molnar <mingo@kernel.org>
| null | null |
2015-12-15T12:49:05Z
|
parse_array(JsonLexContext *lex, JsonSemAction *sem)
{
/*
* an array is a possibly empty sequence of array elements, separated by
* commas and surrounded by square brackets.
*/
json_struct_action astart = sem->array_start;
json_struct_action aend = sem->array_end;
json_struct_action astart = sem->array_start;
json_struct_action aend = sem->array_end;
if (astart != NULL)
(*astart) (sem->semstate);
* array end.
*/
lex->lex_level++;
lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
{
parse_array_element(lex, sem);
while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
parse_array_element(lex, sem);
}
lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
lex->lex_level--;
if (aend != NULL)
(*aend) (sem->semstate);
}
|
parse_array(JsonLexContext *lex, JsonSemAction *sem)
{
/*
* an array is a possibly empty sequence of array elements, separated by
* commas and surrounded by square brackets.
*/
json_struct_action astart = sem->array_start;
json_struct_action aend = sem->array_end;
json_struct_action astart = sem->array_start;
json_struct_action aend = sem->array_end;
check_stack_depth();
if (astart != NULL)
(*astart) (sem->semstate);
* array end.
*/
lex->lex_level++;
lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
{
parse_array_element(lex, sem);
while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
parse_array_element(lex, sem);
}
lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
lex->lex_level--;
if (aend != NULL)
(*aend) (sem->semstate);
}
|
CVE-2015-5289
|
CWE-119
|
Multiple stack-based buffer overflows in json parsing in PostgreSQL before 9.3.x before 9.3.10 and 9.4.x before 9.4.5 allow attackers to cause a denial of service (server crash) via unspecified vectors, which are not properly handled in (1) json or (2) jsonb values.
|
https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=08fa47c4850cea32c3116665975bca219fbf2fe6
| null | null |
c
| null |
static int xwma_read_header(AVFormatContext *s, AVFormatParameters *ap)
{
int64_t size, av_uninit(data_size);
uint32_t dpds_table_size = 0;
uint32_t *dpds_table = 0;
unsigned int tag;
AVIOContext *pb = s->pb;
AVStream *st;
XWMAContext *xwma = s->priv_data;
int i;
tag = avio_rl32(pb);
if (tag != MKTAG('R', 'I', 'F', 'F'))
return -1;
avio_rl32(pb);
tag = avio_rl32(pb);
if (tag != MKTAG('X', 'W', 'M', 'A'))
return -1;
tag = avio_rl32(pb);
if (tag != MKTAG('f', 'm', 't', ' '))
return -1;
size = avio_rl32(pb);
st = av_new_stream(s, 0);
if (!st)
return AVERROR(ENOMEM);
ff_get_wav_header(pb, st->codec, size);
st->need_parsing = AVSTREAM_PARSE_NONE;
if (st->codec->codec_id != CODEC_ID_WMAV2) {
av_log(s, AV_LOG_WARNING, "unexpected codec (tag 0x04%x; id %d)\n",
st->codec->codec_tag, st->codec->codec_id);
av_log_ask_for_sample(s, NULL);
} else {
if (st->codec->extradata_size != 0) {
av_log(s, AV_LOG_WARNING, "unexpected extradata (%d bytes)\n",
st->codec->extradata_size);
av_log_ask_for_sample(s, NULL);
} else {
st->codec->extradata_size = 6;
st->codec->extradata = av_mallocz(6 + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
st->codec->extradata[4] = 31;
}
}
av_set_pts_info(st, 64, 1, st->codec->sample_rate);
for (;;) {
if (pb->eof_reached)
return -1;
tag = avio_rl32(pb);
size = avio_rl32(pb);
if (tag == MKTAG('d', 'a', 't', 'a')) {
break;
} else if (tag == MKTAG('d','p','d','s')) {
if (dpds_table) {
av_log(s, AV_LOG_ERROR, "two dpds chunks present\n");
return -1;
}
if (size & 3) {
av_log(s, AV_LOG_WARNING, "dpds chunk size "PRId64" not divisible by 4\n", size);
}
dpds_table_size = size / 4;
if (dpds_table_size == 0 || dpds_table_size >= INT_MAX / 4) {
av_log(s, AV_LOG_ERROR, "dpds chunk size "PRId64" invalid\n", size);
return -1;
}
dpds_table = av_malloc(dpds_table_size * sizeof(uint32_t));
if (!dpds_table) {
return AVERROR(ENOMEM);
}
for (i = 0; i < dpds_table_size; ++i) {
dpds_table[i] = avio_rl32(pb);
size -= 4;
}
}
avio_skip(pb, size);
}
if (size < 0)
return -1;
if (!size) {
xwma->data_end = INT64_MAX;
} else
xwma->data_end = avio_tell(pb) + size;
if (dpds_table && dpds_table_size) {
int64_t cur_pos;
const uint32_t bytes_per_sample
= (st->codec->channels * st->codec->bits_per_coded_sample) >> 3;
const uint64_t total_decoded_bytes = dpds_table[dpds_table_size - 1];
st->duration = total_decoded_bytes / bytes_per_sample;
cur_pos = avio_tell(pb);
for (i = 0; i < dpds_table_size; ++i) {
av_add_index_entry(st,
cur_pos + (i+1) * st->codec->block_align,
dpds_table[i] / bytes_per_sample,
st->codec->block_align,
0,
AVINDEX_KEYFRAME);
}
} else if (st->codec->bit_rate) {
st->duration = (size<<3) * st->codec->sample_rate / st->codec->bit_rate;
}
av_free(dpds_table);
return 0;
}
|
static int xwma_read_header(AVFormatContext *s, AVFormatParameters *ap)
{
int64_t size, av_uninit(data_size);
int ret;
uint32_t dpds_table_size = 0;
uint32_t *dpds_table = 0;
unsigned int tag;
AVIOContext *pb = s->pb;
AVStream *st;
XWMAContext *xwma = s->priv_data;
int i;
tag = avio_rl32(pb);
if (tag != MKTAG('R', 'I', 'F', 'F'))
return -1;
avio_rl32(pb);
tag = avio_rl32(pb);
if (tag != MKTAG('X', 'W', 'M', 'A'))
return -1;
tag = avio_rl32(pb);
if (tag != MKTAG('f', 'm', 't', ' '))
return -1;
size = avio_rl32(pb);
st = av_new_stream(s, 0);
if (!st)
return AVERROR(ENOMEM);
ret = ff_get_wav_header(pb, st->codec, size);
if (ret < 0)
return ret;
st->need_parsing = AVSTREAM_PARSE_NONE;
if (st->codec->codec_id != CODEC_ID_WMAV2) {
av_log(s, AV_LOG_WARNING, "unexpected codec (tag 0x04%x; id %d)\n",
st->codec->codec_tag, st->codec->codec_id);
av_log_ask_for_sample(s, NULL);
} else {
if (st->codec->extradata_size != 0) {
av_log(s, AV_LOG_WARNING, "unexpected extradata (%d bytes)\n",
st->codec->extradata_size);
av_log_ask_for_sample(s, NULL);
} else {
st->codec->extradata_size = 6;
st->codec->extradata = av_mallocz(6 + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
st->codec->extradata[4] = 31;
}
}
av_set_pts_info(st, 64, 1, st->codec->sample_rate);
for (;;) {
if (pb->eof_reached)
return -1;
tag = avio_rl32(pb);
size = avio_rl32(pb);
if (tag == MKTAG('d', 'a', 't', 'a')) {
break;
} else if (tag == MKTAG('d','p','d','s')) {
if (dpds_table) {
av_log(s, AV_LOG_ERROR, "two dpds chunks present\n");
return -1;
}
if (size & 3) {
av_log(s, AV_LOG_WARNING, "dpds chunk size "PRId64" not divisible by 4\n", size);
}
dpds_table_size = size / 4;
if (dpds_table_size == 0 || dpds_table_size >= INT_MAX / 4) {
av_log(s, AV_LOG_ERROR, "dpds chunk size "PRId64" invalid\n", size);
return -1;
}
dpds_table = av_malloc(dpds_table_size * sizeof(uint32_t));
if (!dpds_table) {
return AVERROR(ENOMEM);
}
for (i = 0; i < dpds_table_size; ++i) {
dpds_table[i] = avio_rl32(pb);
size -= 4;
}
}
avio_skip(pb, size);
}
if (size < 0)
return -1;
if (!size) {
xwma->data_end = INT64_MAX;
} else
xwma->data_end = avio_tell(pb) + size;
if (dpds_table && dpds_table_size) {
int64_t cur_pos;
const uint32_t bytes_per_sample
= (st->codec->channels * st->codec->bits_per_coded_sample) >> 3;
const uint64_t total_decoded_bytes = dpds_table[dpds_table_size - 1];
st->duration = total_decoded_bytes / bytes_per_sample;
cur_pos = avio_tell(pb);
for (i = 0; i < dpds_table_size; ++i) {
av_add_index_entry(st,
cur_pos + (i+1) * st->codec->block_align,
dpds_table[i] / bytes_per_sample,
st->codec->block_align,
0,
AVINDEX_KEYFRAME);
}
} else if (st->codec->bit_rate) {
st->duration = (size<<3) * st->codec->sample_rate / st->codec->bit_rate;
}
av_free(dpds_table);
return 0;
}
| null | null | null |
FFmpeg/commit/ca402f32e392590a81a1381dab41c4f9c2c2f98a
|
handle malloc failures in ff_get_wav_header
ff_get_wav_header is reading data from a WAVE file and then uses it
(without validation) to malloc a buffer. It then proceeded to read
data into the buffer, without verifying that the allocation succeeded.
To address this, change ff_get_wav_header to return an error if
allocation failed, and adapted all calling code to handle that error.
Signed-off-by: Luca Barbato <lu_zero@gentoo.org>
|
./ffmpeg/libavformat/xwma.c
|
c
|
2011-04-12T15:44:20Z
|
void eb_read_bin(eb_t a, const uint8_t *bin, int len) {
if (len == 1) {
if (bin[0] == 0) {
eb_set_infty(a);
return;
} else {
RLC_THROW(ERR_NO_BUFFER);
return;
}
}
if (len != (RLC_FB_BYTES + 1) && len != (2 * RLC_FB_BYTES + 1)) {
RLC_THROW(ERR_NO_BUFFER);
return;
}
a->coord = BASIC;
fb_set_dig(a->z, 1);
fb_read_bin(a->x, bin + 1, RLC_FB_BYTES);
if (len == RLC_FB_BYTES + 1) {
switch(bin[0]) {
case 2:
fb_zero(a->y);
break;
case 3:
fb_zero(a->y);
fb_set_bit(a->y, 0, 1);
break;
default:
RLC_THROW(ERR_NO_VALID);
break;
}
eb_upk(a, a);
}
if (len == 2 * RLC_FB_BYTES + 1) {
if (bin[0] == 4) {
fb_read_bin(a->y, bin + RLC_FB_BYTES + 1, RLC_FB_BYTES);
} else {
RLC_THROW(ERR_NO_VALID);
return;
}
}
if (!eb_on_curve(a)) {
RLC_THROW(ERR_NO_VALID);
return;
}
}
|
void eb_read_bin(eb_t a, const uint8_t *bin, size_t len) {
if (len == 1) {
if (bin[0] == 0) {
eb_set_infty(a);
return;
} else {
RLC_THROW(ERR_NO_BUFFER);
return;
}
}
if (len != (RLC_FB_BYTES + 1) && len != (2 * RLC_FB_BYTES + 1)) {
RLC_THROW(ERR_NO_BUFFER);
return;
}
a->coord = BASIC;
fb_set_dig(a->z, 1);
fb_read_bin(a->x, bin + 1, RLC_FB_BYTES);
if (len == RLC_FB_BYTES + 1) {
switch(bin[0]) {
case 2:
fb_zero(a->y);
break;
case 3:
fb_zero(a->y);
fb_set_bit(a->y, 0, 1);
break;
default:
RLC_THROW(ERR_NO_VALID);
break;
}
eb_upk(a, a);
}
if (len == 2 * RLC_FB_BYTES + 1) {
if (bin[0] == 4) {
fb_read_bin(a->y, bin + RLC_FB_BYTES + 1, RLC_FB_BYTES);
} else {
RLC_THROW(ERR_NO_VALID);
return;
}
}
if (!eb_on_curve(a)) {
RLC_THROW(ERR_NO_VALID);
return;
}
}
| null | null | null |
https://github.com/relic-toolkit/relic/commit/34580d840469361ba9b5f001361cad659687b9ab
|
Huge commit improving the API to use size_t instead of int.
|
src/eb/relic_eb_util.c
|
c
|
2022-11-14T20:47:12Z
|
static char *expandRequestTokens(HttpConn *conn, char *str)
{
HttpRx *rx;
HttpTx *tx;
HttpRoute *route;
MprBuf *buf;
HttpLang *lang;
char *tok, *cp, *key, *value, *field, *header, *defaultValue, *state, *v, *p;
assert(conn);
assert(str);
rx = conn->rx;
route = rx->route;
tx = conn->tx;
buf = mprCreateBuf(-1, -1);
tok = 0;
for (cp = str; cp && *cp; ) {
if ((tok = strstr(cp, "${")) == 0) {
break;
}
if (tok > cp) {
mprPutBlockToBuf(buf, cp, tok - cp);
}
if ((key = stok(&tok[2], ".:}", &value)) == 0) {
continue;
}
stok(value, "}", &cp);
if (smatch(key, "header")) {
header = stok(value, "=", &defaultValue);
if ((value = (char*) httpGetHeader(conn, header)) == 0) {
value = defaultValue ? defaultValue : "";
}
mprPutStringToBuf(buf, value);
} else if (smatch(key, "param")) {
field = stok(value, "=", &defaultValue);
if (defaultValue == 0) {
defaultValue = "";
}
mprPutStringToBuf(buf, httpGetParam(conn, field, defaultValue));
} else if (smatch(key, "request")) {
value = stok(value, "=", &defaultValue);
// OPT with switch on first char
if (smatch(value, "authenticated")) {
mprPutStringToBuf(buf, rx->authenticated ? "true" : "false");
} else if (smatch(value, "clientAddress")) {
mprPutStringToBuf(buf, conn->ip);
} else if (smatch(value, "clientPort")) {
mprPutIntToBuf(buf, conn->port);
} else if (smatch(value, "error")) {
mprPutStringToBuf(buf, conn->errorMsg);
} else if (smatch(value, "ext")) {
mprPutStringToBuf(buf, rx->parsedUri->ext);
} else if (smatch(value, "extraPath")) {
mprPutStringToBuf(buf, rx->extraPath);
} else if (smatch(value, "filename")) {
mprPutStringToBuf(buf, tx->filename);
} else if (scaselessmatch(value, "language")) {
if (!defaultValue) {
defaultValue = route->defaultLanguage;
}
if ((lang = httpGetLanguage(conn, route->languages, defaultValue)) != 0) {
mprPutStringToBuf(buf, lang->suffix);
} else {
mprPutStringToBuf(buf, defaultValue);
}
} else if (scaselessmatch(value, "languageDir")) {
lang = httpGetLanguage(conn, route->languages, 0);
if (!defaultValue) {
defaultValue = ".";
}
mprPutStringToBuf(buf, lang ? lang->path : defaultValue);
} else if (smatch(value, "host")) {
/* Includes port if present */
mprPutStringToBuf(buf, rx->parsedUri->host);
} else if (smatch(value, "method")) {
mprPutStringToBuf(buf, rx->method);
} else if (smatch(value, "originalUri")) {
mprPutStringToBuf(buf, rx->originalUri);
} else if (smatch(value, "pathInfo")) {
mprPutStringToBuf(buf, rx->pathInfo);
} else if (smatch(value, "prefix")) {
mprPutStringToBuf(buf, route->prefix);
} else if (smatch(value, "query")) {
mprPutStringToBuf(buf, rx->parsedUri->query);
} else if (smatch(value, "reference")) {
mprPutStringToBuf(buf, rx->parsedUri->reference);
} else if (smatch(value, "scheme")) {
if (rx->parsedUri->scheme) {
mprPutStringToBuf(buf, rx->parsedUri->scheme);
} else {
mprPutStringToBuf(buf, (conn->secure) ? "https" : "http");
}
} else if (smatch(value, "scriptName")) {
mprPutStringToBuf(buf, rx->scriptName);
} else if (smatch(value, "serverAddress")) {
/* Pure IP address, no port. See "serverPort" */
mprPutStringToBuf(buf, conn->sock->acceptIp);
} else if (smatch(value, "serverPort")) {
mprPutIntToBuf(buf, conn->sock->acceptPort);
} else if (smatch(value, "uri")) {
mprPutStringToBuf(buf, rx->uri);
}
} else if (smatch(key, "ssl")) {
value = stok(value, "=", &defaultValue);
if (smatch(value, "state")) {
mprPutStringToBuf(buf, mprGetSocketState(conn->sock));
} else {
state = mprGetSocketState(conn->sock);
if ((p = scontains(state, value)) != 0) {
stok(p, "=", &v);
mprPutStringToBuf(buf, stok(v, ", ", NULL));
}
}
}
}
assert(cp);
if (tok) {
if (tok > cp) {
mprPutBlockToBuf(buf, tok, tok - cp);
}
} else {
mprPutStringToBuf(buf, cp);
}
mprAddNullToBuf(buf);
return sclone(mprGetBufStart(buf));
}
|
static char *expandRequestTokens(HttpConn *conn, char *str)
{
HttpRx *rx;
HttpTx *tx;
HttpRoute *route;
MprBuf *buf;
HttpLang *lang;
char *tok, *cp, *key, *value, *field, *header, *defaultValue, *state, *v, *p;
assert(conn);
assert(str);
rx = conn->rx;
route = rx->route;
tx = conn->tx;
buf = mprCreateBuf(-1, -1);
tok = 0;
for (cp = str; cp && *cp; ) {
if ((tok = strstr(cp, "${")) == 0) {
break;
}
if (tok > cp) {
mprPutBlockToBuf(buf, cp, tok - cp);
}
if ((key = stok(&tok[2], ".:}", &value)) == 0) {
continue;
}
if ((stok(value, "}", &cp)) == 0) {
continue;
}
if (smatch(key, "header")) {
header = stok(value, "=", &defaultValue);
if ((value = (char*) httpGetHeader(conn, header)) == 0) {
value = defaultValue ? defaultValue : "";
}
mprPutStringToBuf(buf, value);
} else if (smatch(key, "param")) {
field = stok(value, "=", &defaultValue);
if (defaultValue == 0) {
defaultValue = "";
}
mprPutStringToBuf(buf, httpGetParam(conn, field, defaultValue));
} else if (smatch(key, "request")) {
value = stok(value, "=", &defaultValue);
// OPT with switch on first char
if (smatch(value, "authenticated")) {
mprPutStringToBuf(buf, rx->authenticated ? "true" : "false");
} else if (smatch(value, "clientAddress")) {
mprPutStringToBuf(buf, conn->ip);
} else if (smatch(value, "clientPort")) {
mprPutIntToBuf(buf, conn->port);
} else if (smatch(value, "error")) {
mprPutStringToBuf(buf, conn->errorMsg);
} else if (smatch(value, "ext")) {
mprPutStringToBuf(buf, rx->parsedUri->ext);
} else if (smatch(value, "extraPath")) {
mprPutStringToBuf(buf, rx->extraPath);
} else if (smatch(value, "filename")) {
mprPutStringToBuf(buf, tx->filename);
} else if (scaselessmatch(value, "language")) {
if (!defaultValue) {
defaultValue = route->defaultLanguage;
}
if ((lang = httpGetLanguage(conn, route->languages, defaultValue)) != 0) {
mprPutStringToBuf(buf, lang->suffix);
} else {
mprPutStringToBuf(buf, defaultValue);
}
} else if (scaselessmatch(value, "languageDir")) {
lang = httpGetLanguage(conn, route->languages, 0);
if (!defaultValue) {
defaultValue = ".";
}
mprPutStringToBuf(buf, lang ? lang->path : defaultValue);
} else if (smatch(value, "host")) {
/* Includes port if present */
mprPutStringToBuf(buf, rx->parsedUri->host);
} else if (smatch(value, "method")) {
mprPutStringToBuf(buf, rx->method);
} else if (smatch(value, "originalUri")) {
mprPutStringToBuf(buf, rx->originalUri);
} else if (smatch(value, "pathInfo")) {
mprPutStringToBuf(buf, rx->pathInfo);
} else if (smatch(value, "prefix")) {
mprPutStringToBuf(buf, route->prefix);
} else if (smatch(value, "query")) {
mprPutStringToBuf(buf, rx->parsedUri->query);
} else if (smatch(value, "reference")) {
mprPutStringToBuf(buf, rx->parsedUri->reference);
} else if (smatch(value, "scheme")) {
if (rx->parsedUri->scheme) {
mprPutStringToBuf(buf, rx->parsedUri->scheme);
} else {
mprPutStringToBuf(buf, (conn->secure) ? "https" : "http");
}
} else if (smatch(value, "scriptName")) {
mprPutStringToBuf(buf, rx->scriptName);
} else if (smatch(value, "serverAddress")) {
/* Pure IP address, no port. See "serverPort" */
mprPutStringToBuf(buf, conn->sock->acceptIp);
} else if (smatch(value, "serverPort")) {
mprPutIntToBuf(buf, conn->sock->acceptPort);
} else if (smatch(value, "uri")) {
mprPutStringToBuf(buf, rx->uri);
}
} else if (smatch(key, "ssl")) {
value = stok(value, "=", &defaultValue);
if (smatch(value, "state")) {
mprPutStringToBuf(buf, mprGetSocketState(conn->sock));
} else {
state = mprGetSocketState(conn->sock);
if ((p = scontains(state, value)) != 0) {
stok(p, "=", &v);
mprPutStringToBuf(buf, stok(v, ", ", NULL));
}
}
}
}
assert(cp);
if (tok) {
if (tok > cp) {
mprPutBlockToBuf(buf, tok, tok - cp);
}
} else {
mprPutStringToBuf(buf, cp);
}
mprAddNullToBuf(buf);
return sclone(mprGetBufStart(buf));
}
|
CVE-2014-9708
|
CWE-476
|
Embedthis Appweb before 4.6.6 and 5.x before 5.2.1 allows remote attackers to cause a denial of service (NULL pointer dereference) via a Range header with an empty value, as demonstrated by "Range: x=,".
|
https://github.com/embedthis/appweb/commit/7e6a925f5e86a19a7934a94bbd6959101d0b84eb
|
DEV: switch to use ssplit and mprReadJson
ssplit is more robust than stok because it does not return null
mprReadJson is faster, simpler and does not support dotted keys.
|
httpLib.c
|
c
|
2015-03-31T14:59:00Z
|
static void
lexer_parse_number (parser_context_t *context_p) /**< context */
{
const uint8_t *source_p = context_p->source_p;
const uint8_t *source_end_p = context_p->source_end_p;
bool can_be_float = false;
#if ENABLED (JERRY_BUILTIN_BIGINT)
bool can_be_bigint = true;
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
size_t length;
context_p->token.type = LEXER_LITERAL;
context_p->token.extra_value = LEXER_NUMBER_DECIMAL;
context_p->token.lit_location.char_p = source_p;
context_p->token.lit_location.type = LEXER_NUMBER_LITERAL;
context_p->token.lit_location.has_escape = false;
if (source_p[0] == LIT_CHAR_0
&& source_p + 1 < source_end_p)
{
#if ENABLED (JERRY_ESNEXT)
if (source_p[1] == LIT_CHAR_UNDERSCORE)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);
}
#endif /* ENABLED (JERRY_ESNEXT) */
if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_X)
{
context_p->token.extra_value = LEXER_NUMBER_HEXADECIMAL;
source_p += 2;
if (source_p >= source_end_p
|| !lit_char_is_hex_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_HEX_DIGIT);
}
do
{
source_p++;
#if ENABLED (JERRY_ESNEXT)
if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)
{
source_p++;
if (!lit_char_is_hex_digit (source_p[0]) || source_p == source_end_p)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);
}
}
#endif /* ENABLED (JERRY_ESNEXT) */
}
while (source_p < source_end_p
&& lit_char_is_hex_digit (source_p[0]));
}
#if ENABLED (JERRY_ESNEXT)
else if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_O)
{
context_p->token.extra_value = LEXER_NUMBER_OCTAL;
source_p += 2;
if (source_p >= source_end_p
|| !lit_char_is_octal_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_OCTAL_DIGIT);
}
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_7, false);
}
#endif /* ENABLED (JERRY_ESNEXT) */
else if (source_p[1] >= LIT_CHAR_0
&& source_p[1] <= LIT_CHAR_9)
{
context_p->token.extra_value = LEXER_NUMBER_OCTAL;
#if ENABLED (JERRY_BUILTIN_BIGINT)
can_be_bigint = false;
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_OCTAL_NUMBER_NOT_ALLOWED);
}
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_7, true);
if (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_8
&& source_p[0] <= LIT_CHAR_9)
{
#if ENABLED (JERRY_ESNEXT)
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, true);
context_p->token.extra_value = LEXER_NUMBER_DECIMAL;
#else /* !ENABLED (JERRY_ESNEXT) */
parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER);
#endif /* ENABLED (JERRY_ESNEXT) */
}
}
#if ENABLED (JERRY_ESNEXT)
else if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_B)
{
context_p->token.extra_value = LEXER_NUMBER_BINARY;
source_p += 2;
if (source_p >= source_end_p
|| !lit_char_is_binary_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_BIN_DIGIT);
}
do
{
source_p++;
if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)
{
source_p++;
if (source_p == source_end_p
|| source_p[0] > LIT_CHAR_9
|| source_p[0] < LIT_CHAR_0)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);
}
}
}
while (source_p < source_end_p
&& lit_char_is_binary_digit (source_p[0]));
}
#endif /* ENABLED (JERRY_ESNEXT) */
else
{
can_be_float = true;
source_p++;
}
}
else
{
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);
can_be_float = true;
}
if (can_be_float)
{
if (source_p < source_end_p
&& source_p[0] == LIT_CHAR_DOT)
{
source_p++;
#if ENABLED (JERRY_BUILTIN_BIGINT)
can_be_bigint = false;
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
#if ENABLED (JERRY_ESNEXT)
if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);
}
#endif /* ENABLED (JERRY_ESNEXT) */
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);
}
if (source_p < source_end_p
&& LEXER_TO_ASCII_LOWERCASE (source_p[0]) == LIT_CHAR_LOWERCASE_E)
{
source_p++;
#if ENABLED (JERRY_BUILTIN_BIGINT)
can_be_bigint = false;
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
if (source_p < source_end_p
&& (source_p[0] == LIT_CHAR_PLUS || source_p[0] == LIT_CHAR_MINUS))
{
source_p++;
}
if (source_p >= source_end_p
|| source_p[0] < LIT_CHAR_0
|| source_p[0] > LIT_CHAR_9)
{
parser_raise_error (context_p, PARSER_ERR_MISSING_EXPONENT);
}
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);
}
}
#if ENABLED (JERRY_BUILTIN_BIGINT)
if (source_p < source_end_p && source_p[0] == LIT_CHAR_LOWERCASE_N)
{
if (!can_be_bigint)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_BIGINT);
}
context_p->token.extra_value = LEXER_NUMBER_BIGINT;
source_p++;
}
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
length = (size_t) (source_p - context_p->source_p);
if (length > PARSER_MAXIMUM_STRING_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_NUMBER_TOO_LONG);
}
context_p->token.lit_location.length = (prop_length_t) length;
PARSER_PLUS_EQUAL_LC (context_p->column, length);
context_p->source_p = source_p;
if (source_p < source_end_p && lexer_parse_identifier (context_p, LEXER_PARSE_CHECK_START_AND_RETURN))
{
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_AFTER_NUMBER);
}
}
|
static void
lexer_parse_number (parser_context_t *context_p) /**< context */
{
const uint8_t *source_p = context_p->source_p;
const uint8_t *source_end_p = context_p->source_end_p;
bool can_be_float = false;
#if ENABLED (JERRY_BUILTIN_BIGINT)
bool can_be_bigint = true;
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
size_t length;
context_p->token.type = LEXER_LITERAL;
context_p->token.extra_value = LEXER_NUMBER_DECIMAL;
context_p->token.lit_location.char_p = source_p;
context_p->token.lit_location.type = LEXER_NUMBER_LITERAL;
context_p->token.lit_location.has_escape = false;
if (source_p[0] == LIT_CHAR_0
&& source_p + 1 < source_end_p)
{
#if ENABLED (JERRY_ESNEXT)
if (source_p[1] == LIT_CHAR_UNDERSCORE)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);
}
#endif /* ENABLED (JERRY_ESNEXT) */
if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_X)
{
context_p->token.extra_value = LEXER_NUMBER_HEXADECIMAL;
source_p += 2;
if (source_p >= source_end_p
|| !lit_char_is_hex_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_HEX_DIGIT);
}
do
{
source_p++;
#if ENABLED (JERRY_ESNEXT)
if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)
{
source_p++;
if (source_p == source_end_p || !lit_char_is_hex_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);
}
}
#endif /* ENABLED (JERRY_ESNEXT) */
}
while (source_p < source_end_p
&& lit_char_is_hex_digit (source_p[0]));
}
#if ENABLED (JERRY_ESNEXT)
else if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_O)
{
context_p->token.extra_value = LEXER_NUMBER_OCTAL;
source_p += 2;
if (source_p >= source_end_p
|| !lit_char_is_octal_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_OCTAL_DIGIT);
}
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_7, false);
}
#endif /* ENABLED (JERRY_ESNEXT) */
else if (source_p[1] >= LIT_CHAR_0
&& source_p[1] <= LIT_CHAR_9)
{
context_p->token.extra_value = LEXER_NUMBER_OCTAL;
#if ENABLED (JERRY_BUILTIN_BIGINT)
can_be_bigint = false;
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_OCTAL_NUMBER_NOT_ALLOWED);
}
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_7, true);
if (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_8
&& source_p[0] <= LIT_CHAR_9)
{
#if ENABLED (JERRY_ESNEXT)
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, true);
context_p->token.extra_value = LEXER_NUMBER_DECIMAL;
#else /* !ENABLED (JERRY_ESNEXT) */
parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER);
#endif /* ENABLED (JERRY_ESNEXT) */
}
}
#if ENABLED (JERRY_ESNEXT)
else if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_B)
{
context_p->token.extra_value = LEXER_NUMBER_BINARY;
source_p += 2;
if (source_p >= source_end_p
|| !lit_char_is_binary_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_BIN_DIGIT);
}
do
{
source_p++;
if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)
{
source_p++;
if (source_p == source_end_p
|| source_p[0] > LIT_CHAR_9
|| source_p[0] < LIT_CHAR_0)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);
}
}
}
while (source_p < source_end_p
&& lit_char_is_binary_digit (source_p[0]));
}
#endif /* ENABLED (JERRY_ESNEXT) */
else
{
can_be_float = true;
source_p++;
}
}
else
{
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);
can_be_float = true;
}
if (can_be_float)
{
if (source_p < source_end_p
&& source_p[0] == LIT_CHAR_DOT)
{
source_p++;
#if ENABLED (JERRY_BUILTIN_BIGINT)
can_be_bigint = false;
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
#if ENABLED (JERRY_ESNEXT)
if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER);
}
#endif /* ENABLED (JERRY_ESNEXT) */
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);
}
if (source_p < source_end_p
&& LEXER_TO_ASCII_LOWERCASE (source_p[0]) == LIT_CHAR_LOWERCASE_E)
{
source_p++;
#if ENABLED (JERRY_BUILTIN_BIGINT)
can_be_bigint = false;
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
if (source_p < source_end_p
&& (source_p[0] == LIT_CHAR_PLUS || source_p[0] == LIT_CHAR_MINUS))
{
source_p++;
}
if (source_p >= source_end_p
|| source_p[0] < LIT_CHAR_0
|| source_p[0] > LIT_CHAR_9)
{
parser_raise_error (context_p, PARSER_ERR_MISSING_EXPONENT);
}
lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false);
}
}
#if ENABLED (JERRY_BUILTIN_BIGINT)
if (source_p < source_end_p && source_p[0] == LIT_CHAR_LOWERCASE_N)
{
if (!can_be_bigint)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_BIGINT);
}
context_p->token.extra_value = LEXER_NUMBER_BIGINT;
source_p++;
}
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
length = (size_t) (source_p - context_p->source_p);
if (length > PARSER_MAXIMUM_STRING_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_NUMBER_TOO_LONG);
}
context_p->token.lit_location.length = (prop_length_t) length;
PARSER_PLUS_EQUAL_LC (context_p->column, length);
context_p->source_p = source_p;
if (source_p < source_end_p && lexer_parse_identifier (context_p, LEXER_PARSE_CHECK_START_AND_RETURN))
{
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_AFTER_NUMBER);
}
}
| null | null | null |
https://github.com/jerryscript-project/jerryscript/commit/a2a1c97bfbbd856e2ee9b5bafd10b1d18ce7d1fe
|
Fix underscore lookahead in hex literal parsing
This patch fixes #4442.
JerryScript-DCO-1.0-Signed-off-by: Robert Fancsik frobert@inf.u-szeged.hu
|
jerry-core/parser/js/js-lexer.c
|
c
|
2021-01-11T14:52:59Z
|
BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
{
int i;
BIO *out = NULL, *btmp = NULL;
X509_ALGOR *xa = NULL;
const EVP_CIPHER *evp_cipher = NULL;
STACK_OF(X509_ALGOR) *md_sk = NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
X509_ALGOR *xalg = NULL;
PKCS7_RECIP_INFO *ri = NULL;
EVP_PKEY *pkey;
ASN1_OCTET_STRING *os = NULL;
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
switch (i) {
case NID_pkcs7_signed:
md_sk = p7->d.sign->md_algs;
os = PKCS7_get_octet_string(p7->d.sign->contents);
break;
case NID_pkcs7_signedAndEnveloped:
rsk = p7->d.signed_and_enveloped->recipientinfo;
md_sk = p7->d.signed_and_enveloped->md_algs;
xalg = p7->d.signed_and_enveloped->enc_data->algorithm;
evp_cipher = p7->d.signed_and_enveloped->enc_data->cipher;
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
goto err;
}
break;
case NID_pkcs7_enveloped:
rsk = p7->d.enveloped->recipientinfo;
xalg = p7->d.enveloped->enc_data->algorithm;
evp_cipher = p7->d.enveloped->enc_data->cipher;
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
goto err;
}
break;
case NID_pkcs7_digest:
xa = p7->d.digest->md;
os = PKCS7_get_octet_string(p7->d.digest->contents);
break;
default:
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++)
if (!PKCS7_bio_add_digest(&out, sk_X509_ALGOR_value(md_sk, i)))
goto err;
if (xa && !PKCS7_bio_add_digest(&out, xa))
goto err;
if (evp_cipher != NULL) {
unsigned char key[EVP_MAX_KEY_LENGTH];
unsigned char iv[EVP_MAX_IV_LENGTH];
int keylen, ivlen;
int jj, max;
unsigned char *tmp;
EVP_CIPHER_CTX *ctx;
if ((btmp = BIO_new(BIO_f_cipher())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_BIO_LIB);
goto err;
}
BIO_get_cipher_ctx(btmp, &ctx);
keylen = EVP_CIPHER_key_length(evp_cipher);
ivlen = EVP_CIPHER_iv_length(evp_cipher);
xalg->algorithm = OBJ_nid2obj(EVP_CIPHER_type(evp_cipher));
if (ivlen > 0)
if (RAND_pseudo_bytes(iv, ivlen) <= 0)
goto err;
if (EVP_CipherInit_ex(ctx, evp_cipher, NULL, NULL, NULL, 1) <= 0)
goto err;
if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
goto err;
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1) <= 0)
goto err;
if (ivlen > 0) {
if (xalg->parameter == NULL) {
xalg->parameter = ASN1_TYPE_new();
if (xalg->parameter == NULL)
goto err;
}
if (EVP_CIPHER_param_to_asn1(ctx, xalg->parameter) < 0)
goto err;
}
/* Lets do the pub key stuff :-) */
max = 0;
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if (ri->cert == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT,
PKCS7_R_MISSING_CERIPEND_INFO);
goto err;
}
if ((pkey = X509_get_pubkey(ri->cert)) == NULL)
goto err;
jj = EVP_PKEY_size(pkey);
EVP_PKEY_free(pkey);
if (max < jj)
max = jj;
}
if ((tmp = (unsigned char *)OPENSSL_malloc(max)) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_MALLOC_FAILURE);
goto err;
}
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if ((pkey = X509_get_pubkey(ri->cert)) == NULL)
goto err;
jj = EVP_PKEY_encrypt(tmp, key, keylen, pkey);
EVP_PKEY_free(pkey);
if (jj <= 0) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_EVP_LIB);
OPENSSL_free(tmp);
goto err;
}
if (!M_ASN1_OCTET_STRING_set(ri->enc_key, tmp, jj)) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_MALLOC_FAILURE);
OPENSSL_free(tmp);
goto err;
}
}
OPENSSL_free(tmp);
OPENSSL_cleanse(key, keylen);
if (out == NULL)
out = btmp;
else
BIO_push(out, btmp);
btmp = NULL;
}
if (bio == NULL) {
if (PKCS7_is_detached(p7))
bio = BIO_new(BIO_s_null());
else if (os && os->length > 0)
bio = BIO_new_mem_buf(os->data, os->length);
if (bio == NULL) {
bio = BIO_new(BIO_s_mem());
if (bio == NULL)
goto err;
BIO_set_mem_eof_return(bio, 0);
}
}
BIO_push(out, bio);
bio = NULL;
if (0) {
err:
if (out != NULL)
BIO_free_all(out);
if (btmp != NULL)
BIO_free_all(btmp);
out = NULL;
}
return (out);
}
|
BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
{
int i;
BIO *out = NULL, *btmp = NULL;
X509_ALGOR *xa = NULL;
const EVP_CIPHER *evp_cipher = NULL;
STACK_OF(X509_ALGOR) *md_sk = NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
X509_ALGOR *xalg = NULL;
PKCS7_RECIP_INFO *ri = NULL;
EVP_PKEY *pkey;
ASN1_OCTET_STRING *os = NULL;
if (p7 == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_INVALID_NULL_POINTER);
return NULL;
}
/*
* The content field in the PKCS7 ContentInfo is optional, but that really
* only applies to inner content (precisely, detached signatures).
*
* When reading content, missing outer content is therefore treated as an
* error.
*
* When creating content, PKCS7_content_new() must be called before
* calling this method, so a NULL p7->d is always an error.
*/
if (p7->d.ptr == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_NO_CONTENT);
return NULL;
}
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
switch (i) {
case NID_pkcs7_signed:
md_sk = p7->d.sign->md_algs;
os = PKCS7_get_octet_string(p7->d.sign->contents);
break;
case NID_pkcs7_signedAndEnveloped:
rsk = p7->d.signed_and_enveloped->recipientinfo;
md_sk = p7->d.signed_and_enveloped->md_algs;
xalg = p7->d.signed_and_enveloped->enc_data->algorithm;
evp_cipher = p7->d.signed_and_enveloped->enc_data->cipher;
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
goto err;
}
break;
case NID_pkcs7_enveloped:
rsk = p7->d.enveloped->recipientinfo;
xalg = p7->d.enveloped->enc_data->algorithm;
evp_cipher = p7->d.enveloped->enc_data->cipher;
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
goto err;
}
break;
case NID_pkcs7_digest:
xa = p7->d.digest->md;
os = PKCS7_get_octet_string(p7->d.digest->contents);
break;
default:
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++)
if (!PKCS7_bio_add_digest(&out, sk_X509_ALGOR_value(md_sk, i)))
goto err;
if (xa && !PKCS7_bio_add_digest(&out, xa))
goto err;
if (evp_cipher != NULL) {
unsigned char key[EVP_MAX_KEY_LENGTH];
unsigned char iv[EVP_MAX_IV_LENGTH];
int keylen, ivlen;
int jj, max;
unsigned char *tmp;
EVP_CIPHER_CTX *ctx;
if ((btmp = BIO_new(BIO_f_cipher())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_BIO_LIB);
goto err;
}
BIO_get_cipher_ctx(btmp, &ctx);
keylen = EVP_CIPHER_key_length(evp_cipher);
ivlen = EVP_CIPHER_iv_length(evp_cipher);
xalg->algorithm = OBJ_nid2obj(EVP_CIPHER_type(evp_cipher));
if (ivlen > 0)
if (RAND_pseudo_bytes(iv, ivlen) <= 0)
goto err;
if (EVP_CipherInit_ex(ctx, evp_cipher, NULL, NULL, NULL, 1) <= 0)
goto err;
if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
goto err;
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1) <= 0)
goto err;
if (ivlen > 0) {
if (xalg->parameter == NULL) {
xalg->parameter = ASN1_TYPE_new();
if (xalg->parameter == NULL)
goto err;
}
if (EVP_CIPHER_param_to_asn1(ctx, xalg->parameter) < 0)
goto err;
}
/* Lets do the pub key stuff :-) */
max = 0;
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if (ri->cert == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT,
PKCS7_R_MISSING_CERIPEND_INFO);
goto err;
}
if ((pkey = X509_get_pubkey(ri->cert)) == NULL)
goto err;
jj = EVP_PKEY_size(pkey);
EVP_PKEY_free(pkey);
if (max < jj)
max = jj;
}
if ((tmp = (unsigned char *)OPENSSL_malloc(max)) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_MALLOC_FAILURE);
goto err;
}
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if ((pkey = X509_get_pubkey(ri->cert)) == NULL)
goto err;
jj = EVP_PKEY_encrypt(tmp, key, keylen, pkey);
EVP_PKEY_free(pkey);
if (jj <= 0) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_EVP_LIB);
OPENSSL_free(tmp);
goto err;
}
if (!M_ASN1_OCTET_STRING_set(ri->enc_key, tmp, jj)) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_MALLOC_FAILURE);
OPENSSL_free(tmp);
goto err;
}
}
OPENSSL_free(tmp);
OPENSSL_cleanse(key, keylen);
if (out == NULL)
out = btmp;
else
BIO_push(out, btmp);
btmp = NULL;
}
if (bio == NULL) {
if (PKCS7_is_detached(p7))
bio = BIO_new(BIO_s_null());
else if (os && os->length > 0)
bio = BIO_new_mem_buf(os->data, os->length);
if (bio == NULL) {
bio = BIO_new(BIO_s_mem());
if (bio == NULL)
goto err;
BIO_set_mem_eof_return(bio, 0);
}
}
BIO_push(out, bio);
bio = NULL;
if (0) {
err:
if (out != NULL)
BIO_free_all(out);
if (btmp != NULL)
BIO_free_all(btmp);
out = NULL;
}
return (out);
}
|
CVE-2015-0289
| null |
The PKCS#7 implementation in OpenSSL before 0.9.8zf, 1.0.0 before 1.0.0r, 1.0.1 before 1.0.1m, and 1.0.2 before 1.0.2a does not properly handle a lack of outer ContentInfo, which allows attackers to cause a denial of service (NULL pointer dereference and application crash) by leveraging an application that processes arbitrary PKCS#7 data and providing malformed data with ASN.1 encoding, related to crypto/pkcs7/pk7_doit.c and crypto/pkcs7/pk7_lib.c.
|
https://git.openssl.org/?p=openssl.git;a=commitdiff;h=544e3e3b69d080ee87721bd03c37b4d450384fb9
|
PKCS#7: avoid NULL pointer dereferences with missing content
In PKCS#7, the ASN.1 content component is optional.
This typically applies to inner content (detached signatures),
however we must also handle unexpected missing outer content
correctly.
This patch only addresses functions reachable from parsing,
decryption and verification, and functions otherwise associated
with reading potentially untrusted data.
Correcting all low-level API calls requires further work.
CVE-2015-0289
Thanks to Michal Zalewski (Google) for reporting this issue.
Reviewed-by: Steve Henson <steve@openssl.org>
Conflicts:
crypto/pkcs7/pk7_doit.c
| null | null | null |
hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
{
unsigned long orun = 1;
ktime_t delta;
delta = ktime_sub(now, timer->expires);
if (delta.tv64 < 0)
return 0;
if (interval.tv64 < timer->base->resolution.tv64)
interval.tv64 = timer->base->resolution.tv64;
if (unlikely(delta.tv64 >= interval.tv64)) {
s64 incr = ktime_to_ns(interval);
orun = ktime_divns(delta, incr);
timer->expires = ktime_add_ns(timer->expires, incr * orun);
if (timer->expires.tv64 > now.tv64)
return orun;
/*
* This (and the ktime_add() below) is the
* correction for exact:
*/
orun++;
}
timer->expires = ktime_add(timer->expires, interval);
return orun;
}
|
hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
{
unsigned long orun = 1;
ktime_t delta;
delta = ktime_sub(now, timer->expires);
if (delta.tv64 < 0)
return 0;
if (interval.tv64 < timer->base->resolution.tv64)
interval.tv64 = timer->base->resolution.tv64;
if (unlikely(delta.tv64 >= interval.tv64)) {
s64 incr = ktime_to_ns(interval);
orun = ktime_divns(delta, incr);
timer->expires = ktime_add_ns(timer->expires, incr * orun);
if (timer->expires.tv64 > now.tv64)
return orun;
/*
* This (and the ktime_add() below) is the
* correction for exact:
*/
orun++;
}
timer->expires = ktime_add(timer->expires, interval);
/*
* Make sure, that the result did not wrap with a very large
* interval.
*/
if (timer->expires.tv64 < 0)
timer->expires = ktime_set(KTIME_SEC_MAX, 0);
return orun;
}
|
CVE-2007-6712
|
CWE-189
|
Integer overflow in the hrtimer_forward function (hrtimer.c) in Linux kernel 2.6.21-rc4, when running on 64-bit systems, allows local users to cause a denial of service (infinite loop) via a timer with a large expiry value, which causes the timer to always be expired.
|
http://git.kernel.org/?p=linux/kernel/git/chris/linux-2.6.git;a=commitdiff;h=13788ccc41ceea5893f9c747c59bc0b28f2416c2
|
[PATCH] hrtimer: prevent overrun DoS in hrtimer_forward()
hrtimer_forward() does not check for the possible overflow of
timer->expires. This can happen on 64 bit machines with large interval
values and results currently in an endless loop in the softirq because the
expiry value becomes negative and therefor the timer is expired all the
time.
Check for this condition and set the expiry value to the max. expiry time
in the future. The fix should be applied to stable kernel series as well.
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Acked-by: Ingo Molnar <mingo@elte.hu>
Cc: <stable@kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
| null | null | null |
static void ExpandMirrorKernelInfo(KernelInfo *kernel)
{
KernelInfo
*clone,
*last;
last = kernel;
clone = CloneKernelInfo(last);
RotateKernelInfo(clone, 180); /* flip */
LastKernelInfo(last)->next = clone;
last = clone;
clone = CloneKernelInfo(last);
RotateKernelInfo(clone, 90); /* transpose */
LastKernelInfo(last)->next = clone;
last = clone;
clone = CloneKernelInfo(last);
RotateKernelInfo(clone, 180); /* flop */
LastKernelInfo(last)->next = clone;
return;
}
|
static void ExpandMirrorKernelInfo(KernelInfo *kernel)
{
KernelInfo
*clone,
*last;
last = kernel;
clone = CloneKernelInfo(last);
if (clone == (KernelInfo *) NULL)
return;
RotateKernelInfo(clone, 180); /* flip */
LastKernelInfo(last)->next = clone;
last = clone;
clone = CloneKernelInfo(last);
if (clone == (KernelInfo *) NULL)
return;
RotateKernelInfo(clone, 90); /* transpose */
LastKernelInfo(last)->next = clone;
last = clone;
clone = CloneKernelInfo(last);
if (clone == (KernelInfo *) NULL)
return;
RotateKernelInfo(clone, 180); /* flop */
LastKernelInfo(last)->next = clone;
return;
}
| null | null | null |
https://github.com/ImageMagick/ImageMagick/commit/a88493a9f25187e194f1ab8d15f346e87d8ebad0
|
https://github.com/ImageMagick/ImageMagick/issues/77
|
magick/morphology.c
|
c
|
2017-09-22T13:07:41Z
|
async def impl(request: Request, handler: _Handler) -> StreamResponse:
if isinstance(request.match_info.route, SystemRoute):
paths_to_check = []
if "?" in request.raw_path:
path, query = request.raw_path.split("?", 1)
query = "?" + query
else:
query = ""
path = request.raw_path
if merge_slashes:
paths_to_check.append(re.sub("//+", "/", path))
if append_slash and not request.path.endswith("/"):
paths_to_check.append(path + "/")
if remove_slash and request.path.endswith("/"):
paths_to_check.append(path[:-1])
if merge_slashes and append_slash:
paths_to_check.append(re.sub("//+", "/", path + "/"))
if merge_slashes and remove_slash and path.endswith("/"):
merged_slashes = re.sub("//+", "/", path)
paths_to_check.append(merged_slashes[:-1])
for path in paths_to_check:
resolves, request = await _check_request_resolves(request, path)
if resolves:
raise redirect_class(request.raw_path + query)
return await handler(request)
|
async def impl(request: Request, handler: _Handler) -> StreamResponse:
if isinstance(request.match_info.route, SystemRoute):
paths_to_check = []
if "?" in request.raw_path:
path, query = request.raw_path.split("?", 1)
query = "?" + query
else:
query = ""
path = request.raw_path
if merge_slashes:
paths_to_check.append(re.sub("//+", "/", path))
if append_slash and not request.path.endswith("/"):
paths_to_check.append(path + "/")
if remove_slash and request.path.endswith("/"):
paths_to_check.append(path[:-1])
if merge_slashes and append_slash:
paths_to_check.append(re.sub("//+", "/", path + "/"))
if merge_slashes and remove_slash and path.endswith("/"):
merged_slashes = re.sub("//+", "/", path)
paths_to_check.append(merged_slashes[:-1])
for path in paths_to_check:
path = re.sub("^//+", "/", path) # SECURITY: GHSA-v6wp-4m6f-gcjg
resolves, request = await _check_request_resolves(request, path)
if resolves:
raise redirect_class(request.raw_path + query)
return await handler(request)
| null | null | null |
https://github.com/aio-libs/aiohttp/commit/2545222a3853e31ace15d87ae0e2effb7da0c96b
|
Merge branch 'ghsa-v6wp-4m6f-gcjg' into master
This patch fixes an open redirect vulnerability bug in
`aiohttp.web_middlewares.normalize_path_middleware` by
making sure that there's at most one slash at the
beginning of the `Location` header value.
Refs:
* https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html
* https://github.com/aio-libs/aiohttp/security/advisories/GHSA-v6wp-4m6f-gcjg
|
aiohttp/web_middlewares.py
|
py
|
2021-02-25T17:58:51Z
|
static av_cold int libgsm_close(AVCodecContext *avctx) {
gsm_destroy(avctx->priv_data);
avctx->priv_data = NULL;
return 0;
}
|
static av_cold int libgsm_close(AVCodecContext *avctx) {
av_freep(&avctx->coded_frame);
gsm_destroy(avctx->priv_data);
avctx->priv_data = NULL;
return 0;
}
| null | null | null |
FFmpeg/commit/916ff02261f79e759d996c76670958276276bf2a
|
Fix memory leak in libgsm wrapper.
Patch by Martin Storsjö, martin at martin dot st
Originally committed as revision 15798 to svn://svn.ffmpeg.org/ffmpeg/trunk
|
./ffmpeg/libavcodec/libgsm.c
|
c
|
2008-11-10T20:02:00Z
|
int avpriv_unlock_avformat(void)
{
if (lockmgr_cb) {
if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
return -1;
}
return 0;
}
|
int avpriv_unlock_avformat(void)
{
return ff_mutex_unlock(&avformat_mutex) ? -1 : 0;
}
| null | null | null |
FFmpeg/commit/a04c2c707de2ce850f79870e84ac9d7ec7aa9143
|
lavc: replace and deprecate the lock manager
Use static mutexes instead of requiring a lock manager. The behavior
should be roughly the same before and after this change for API users
which did not set the lock manager at all (except that a minor memory
leak disappears).
|
./ffmpeg/libavcodec/utils.c
|
c
|
2017-12-21T21:39:24Z
|
static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len)
{
char
temp[MagickPathExtent];
unsigned int
foundiptc,
tagsfound;
unsigned char
recnum,
dataset;
unsigned char
*readable,
*str;
ssize_t
tagindx,
taglen;
int
i,
tagcount = (int) (sizeof(tags) / sizeof(tag_spec));
int
c;
foundiptc = 0; /* found the IPTC-Header */
tagsfound = 0; /* number of tags found */
while (len > 0)
{
c = *s++; len--;
if (c == 0x1c)
foundiptc = 1;
else
{
if (foundiptc)
return -1;
else
continue;
}
/*
We found the 0x1c tag and now grab the dataset and record number tags.
*/
c = *s++; len--;
if (len < 0) return -1;
dataset = (unsigned char) c;
c = *s++; len--;
if (len < 0) return -1;
recnum = (unsigned char) c;
/* try to match this record to one of the ones in our named table */
for (i=0; i< tagcount; i++)
if (tags[i].id == (short) recnum)
break;
if (i < tagcount)
readable=(unsigned char *) tags[i].name;
else
readable=(unsigned char *) "";
/*
We decode the length of the block that follows - ssize_t or short fmt.
*/
c=(*s++);
len--;
if (len < 0)
return(-1);
if (c & (unsigned char) 0x80)
return(0);
else
{
s--;
len++;
taglen=readWordFromBuffer(&s, &len);
}
if (taglen < 0)
return(-1);
if (taglen > 65535)
return(-1);
/* make a buffer to hold the tag datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MagickPathExtent),
sizeof(*str));
if (str == (unsigned char *) NULL)
printf("MemoryAllocationFailed");
for (tagindx=0; tagindx<taglen; tagindx++)
{
c = *s++; len--;
if (len < 0)
return(-1);
str[tagindx]=(unsigned char) c;
}
str[taglen]=0;
/* now finish up by formatting this binary data into ASCII equivalent */
if (strlen((char *)readable) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=",
(unsigned int) dataset,(unsigned int) recnum, readable);
else
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=",
(unsigned int) dataset,(unsigned int) recnum);
(void) WriteBlobString(ofile,temp);
formatString( ofile, (char *)str, taglen );
str=(unsigned char *) RelinquishMagickMemory(str);
tagsfound++;
}
return ((int) tagsfound);
}
|
static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len)
{
char
temp[MagickPathExtent];
unsigned int
foundiptc,
tagsfound;
unsigned char
recnum,
dataset;
unsigned char
*readable,
*str;
ssize_t
tagindx,
taglen;
int
i,
tagcount = (int) (sizeof(tags) / sizeof(tag_spec));
int
c;
foundiptc = 0; /* found the IPTC-Header */
tagsfound = 0; /* number of tags found */
while (len > 0)
{
c = *s++; len--;
if (c == 0x1c)
foundiptc = 1;
else
{
if (foundiptc)
return -1;
else
continue;
}
/*
We found the 0x1c tag and now grab the dataset and record number tags.
*/
c = *s++; len--;
if (len < 0) return -1;
dataset = (unsigned char) c;
c = *s++; len--;
if (len < 0) return -1;
recnum = (unsigned char) c;
/* try to match this record to one of the ones in our named table */
for (i=0; i< tagcount; i++)
if (tags[i].id == (short) recnum)
break;
if (i < tagcount)
readable=(unsigned char *) tags[i].name;
else
readable=(unsigned char *) "";
/*
We decode the length of the block that follows - ssize_t or short fmt.
*/
c=(*s++);
len--;
if (len < 0)
return(-1);
if (c & (unsigned char) 0x80)
return(0);
else
{
s--;
len++;
taglen=readWordFromBuffer(&s, &len);
}
if (taglen < 0)
return(-1);
if (taglen > 65535)
return(-1);
/* make a buffer to hold the tag datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+
MagickPathExtent),sizeof(*str));
if (str == (unsigned char *) NULL)
{
(void) printf("MemoryAllocationFailed");
return 0;
}
for (tagindx=0; tagindx<taglen; tagindx++)
{
c = *s++; len--;
if (len < 0)
{
str=(unsigned char *) RelinquishMagickMemory(str);
return(-1);
}
str[tagindx]=(unsigned char) c;
}
str[taglen]=0;
/* now finish up by formatting this binary data into ASCII equivalent */
if (strlen((char *)readable) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=",
(unsigned int) dataset,(unsigned int) recnum, readable);
else
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=",
(unsigned int) dataset,(unsigned int) recnum);
(void) WriteBlobString(ofile,temp);
formatString( ofile, (char *)str, taglen );
str=(unsigned char *) RelinquishMagickMemory(str);
tagsfound++;
}
return ((int) tagsfound);
}
| null | null | null |
https://github.com/ImageMagick/ImageMagick/commit/33d1b9590c401d4aee666ffd10b16868a38cf705
|
https://github.com/ImageMagick/ImageMagick/issues/1118
|
coders/meta.c
|
c
|
2018-05-01T23:22:19Z
|
@Override public Object read(JsonReader in) throws IOException {
JsonToken token = in.peek();
switch (token) {
case BEGIN_ARRAY:
List<Object> list = new ArrayList<>();
in.beginArray();
while (in.hasNext()) {
list.add(read(in));
}
in.endArray();
return list;
case BEGIN_OBJECT:
Map<String, Object> map = new LinkedTreeMap<>();
in.beginObject();
while (in.hasNext()) {
map.put(in.nextName(), read(in));
}
in.endObject();
return map;
case STRING:
return in.nextString();
case NUMBER:
return toNumberStrategy.readNumber(in);
case BOOLEAN:
return in.nextBoolean();
case NULL:
in.nextNull();
return null;
default:
throw new IllegalStateException();
}
}
|
@Override public Object read(JsonReader in) throws IOException {
// Either List or Map
Object current;
JsonToken peeked = in.peek();
current = tryBeginNesting(in, peeked);
if (current == null) {
return readTerminal(in, peeked);
}
Deque<Object> stack = new ArrayDeque<>();
while (true) {
while (in.hasNext()) {
String name = null;
// Name is only used for JSON object members
if (current instanceof Map) {
name = in.nextName();
}
peeked = in.peek();
Object value = tryBeginNesting(in, peeked);
boolean isNesting = value != null;
if (value == null) {
value = readTerminal(in, peeked);
}
if (current instanceof List) {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) current;
list.add(value);
} else {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) current;
map.put(name, value);
}
if (isNesting) {
stack.addLast(current);
current = value;
}
}
// End current element
if (current instanceof List) {
in.endArray();
} else {
in.endObject();
}
if (stack.isEmpty()) {
return current;
} else {
// Continue with enclosing element
current = stack.removeLast();
}
}
}
| null | null | null |
https://github.com/google/gson/commit/2d01d6a20f39881c692977564c1ea591d9f39027
|
Make `Object` and `JsonElement` deserialization iterative (#1912)
* Make Object and JsonElement deserialization iterative
Often when Object and JsonElement are deserialized the format of the JSON
data is unknown and it might come from an untrusted source. To avoid a
StackOverflowError from maliciously crafted JSON, deserialize Object and
JsonElement iteratively instead of recursively.
Concept based on https://github.com/FasterXML/jackson-databind/commit/51fd2faab70c9c8eb7ae43c200f8480f24ba74d8
But implementation is not based on it.
* Improve imports grouping
* Address review feedback
|
gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java
|
java
|
2022-06-23T00:42:19Z
|
int ff_hevc_parse_sps(HEVCSPS *sps, GetBitContext *gb, unsigned int *sps_id,
int apply_defdispwin, AVBufferRef **vps_list, AVCodecContext *avctx)
{
HEVCWindow *ow;
int ret = 0;
int log2_diff_max_min_transform_block_size;
int bit_depth_chroma, start, vui_present, sublayer_ordering_info;
int i;
sps->vps_id = get_bits(gb, 4);
if (sps->vps_id >= HEVC_MAX_VPS_COUNT) {
av_log(avctx, AV_LOG_ERROR, "VPS id out of range: %d\n", sps->vps_id);
if (vps_list && !vps_list[sps->vps_id]) {
av_log(avctx, AV_LOG_ERROR, "VPS %d does not exist\n",
sps->vps_id);
sps->max_sub_layers = get_bits(gb, 3) + 1;
if (sps->max_sub_layers > HEVC_MAX_SUB_LAYERS) {
av_log(avctx, AV_LOG_ERROR, "sps_max_sub_layers out of range: %d\n",
sps->max_sub_layers);
skip_bits1(gb);
parse_ptl(gb, avctx, &sps->ptl, sps->max_sub_layers);
*sps_id = get_ue_golomb_long(gb);
if (*sps_id >= HEVC_MAX_SPS_COUNT) {
av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", *sps_id);
sps->chroma_format_idc = get_ue_golomb_long(gb);
if (sps->chroma_format_idc != 1) {
avpriv_report_missing_feature(avctx, "chroma_format_idc %d",
sps->chroma_format_idc);
ret = AVERROR_PATCHWELCOME;
if (sps->chroma_format_idc == 3)
sps->separate_colour_plane_flag = get_bits1(gb);
sps->width = get_ue_golomb_long(gb);
sps->height = get_ue_golomb_long(gb);
if ((ret = av_image_check_size(sps->width,
sps->height, 0, avctx)) < 0)
if (get_bits1(gb)) {
sps->pic_conf_win.left_offset = get_ue_golomb_long(gb) * 2;
sps->pic_conf_win.right_offset = get_ue_golomb_long(gb) * 2;
sps->pic_conf_win.top_offset = get_ue_golomb_long(gb) * 2;
sps->pic_conf_win.bottom_offset = get_ue_golomb_long(gb) * 2;
if (avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {
av_log(avctx, AV_LOG_DEBUG,
"discarding sps conformance window, "
"original values are l:%u r:%u t:%u b:%u\n",
sps->pic_conf_win.left_offset,
sps->pic_conf_win.right_offset,
sps->pic_conf_win.top_offset,
sps->pic_conf_win.bottom_offset);
sps->pic_conf_win.left_offset =
sps->pic_conf_win.right_offset =
sps->pic_conf_win.top_offset =
sps->pic_conf_win.bottom_offset = 0;
sps->output_window = sps->pic_conf_win;
sps->bit_depth = get_ue_golomb_long(gb) + 8;
bit_depth_chroma = get_ue_golomb_long(gb) + 8;
if (bit_depth_chroma != sps->bit_depth) {
av_log(avctx, AV_LOG_ERROR,
"Luma bit depth (%d) is different from chroma bit depth (%d), "
"this is unsupported.\n",
sps->bit_depth, bit_depth_chroma);
ret = map_pixel_format(avctx, sps);
if (ret < 0)
sps->log2_max_poc_lsb = get_ue_golomb_long(gb) + 4;
if (sps->log2_max_poc_lsb > 16) {
av_log(avctx, AV_LOG_ERROR, "log2_max_pic_order_cnt_lsb_minus4 out range: %d\n",
sps->log2_max_poc_lsb - 4);
sublayer_ordering_info = get_bits1(gb);
start = sublayer_ordering_info ? 0 : sps->max_sub_layers - 1;
for (i = start; i < sps->max_sub_layers; i++) {
sps->temporal_layer[i].max_dec_pic_buffering = get_ue_golomb_long(gb) + 1;
sps->temporal_layer[i].num_reorder_pics = get_ue_golomb_long(gb);
sps->temporal_layer[i].max_latency_increase = get_ue_golomb_long(gb) - 1;
if (sps->temporal_layer[i].max_dec_pic_buffering > HEVC_MAX_DPB_SIZE) {
av_log(avctx, AV_LOG_ERROR, "sps_max_dec_pic_buffering_minus1 out of range: %d\n",
sps->temporal_layer[i].max_dec_pic_buffering - 1);
if (sps->temporal_layer[i].num_reorder_pics > sps->temporal_layer[i].max_dec_pic_buffering - 1) {
av_log(avctx, AV_LOG_WARNING, "sps_max_num_reorder_pics out of range: %d\n",
sps->temporal_layer[i].num_reorder_pics);
if (avctx->err_recognition & AV_EF_EXPLODE ||
sps->temporal_layer[i].num_reorder_pics > HEVC_MAX_DPB_SIZE - 1) {
sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[i].num_reorder_pics + 1;
if (!sublayer_ordering_info) {
for (i = 0; i < start; i++) {
sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[start].max_dec_pic_buffering;
sps->temporal_layer[i].num_reorder_pics = sps->temporal_layer[start].num_reorder_pics;
sps->temporal_layer[i].max_latency_increase = sps->temporal_layer[start].max_latency_increase;
sps->log2_min_cb_size = get_ue_golomb_long(gb) + 3;
sps->log2_diff_max_min_coding_block_size = get_ue_golomb_long(gb);
sps->log2_min_tb_size = get_ue_golomb_long(gb) + 2;
log2_diff_max_min_transform_block_size = get_ue_golomb_long(gb);
sps->log2_max_trafo_size = log2_diff_max_min_transform_block_size +
sps->log2_min_tb_size;
if (sps->log2_min_tb_size >= sps->log2_min_cb_size) {
av_log(avctx, AV_LOG_ERROR, "Invalid value for log2_min_tb_size");
sps->max_transform_hierarchy_depth_inter = get_ue_golomb_long(gb);
sps->max_transform_hierarchy_depth_intra = get_ue_golomb_long(gb);
sps->scaling_list_enable_flag = get_bits1(gb);
if (sps->scaling_list_enable_flag) {
set_default_scaling_list_data(&sps->scaling_list);
if (get_bits1(gb)) {
ret = scaling_list_data(gb, avctx, &sps->scaling_list);
if (ret < 0)
sps->amp_enabled_flag = get_bits1(gb);
sps->sao_enabled = get_bits1(gb);
sps->pcm_enabled_flag = get_bits1(gb);
if (sps->pcm_enabled_flag) {
sps->pcm.bit_depth = get_bits(gb, 4) + 1;
sps->pcm.bit_depth_chroma = get_bits(gb, 4) + 1;
sps->pcm.log2_min_pcm_cb_size = get_ue_golomb_long(gb) + 3;
sps->pcm.log2_max_pcm_cb_size = sps->pcm.log2_min_pcm_cb_size +
get_ue_golomb_long(gb);
if (sps->pcm.bit_depth > sps->bit_depth) {
av_log(avctx, AV_LOG_ERROR,
"PCM bit depth (%d) is greater than normal bit depth (%d)\n",
sps->pcm.bit_depth, sps->bit_depth);
sps->pcm.loop_filter_disable_flag = get_bits1(gb);
sps->nb_st_rps = get_ue_golomb_long(gb);
if (sps->nb_st_rps > HEVC_MAX_SHORT_TERM_REF_PIC_SETS) {
av_log(avctx, AV_LOG_ERROR, "Too many short term RPS: %d.\n",
sps->nb_st_rps);
for (i = 0; i < sps->nb_st_rps; i++) {
if ((ret = ff_hevc_decode_short_term_rps(gb, avctx, &sps->st_rps[i],
sps, 0)) < 0)
sps->long_term_ref_pics_present_flag = get_bits1(gb);
if (sps->long_term_ref_pics_present_flag) {
sps->num_long_term_ref_pics_sps = get_ue_golomb_long(gb);
for (i = 0; i < sps->num_long_term_ref_pics_sps; i++) {
sps->lt_ref_pic_poc_lsb_sps[i] = get_bits(gb, sps->log2_max_poc_lsb);
sps->used_by_curr_pic_lt_sps_flag[i] = get_bits1(gb);
sps->sps_temporal_mvp_enabled_flag = get_bits1(gb);
sps->sps_strong_intra_smoothing_enable_flag = get_bits1(gb);
sps->vui.sar = (AVRational){0, 1};
vui_present = get_bits1(gb);
if (vui_present)
decode_vui(gb, avctx, apply_defdispwin, sps);
skip_bits1(gb);
if (apply_defdispwin) {
sps->output_window.left_offset += sps->vui.def_disp_win.left_offset;
sps->output_window.right_offset += sps->vui.def_disp_win.right_offset;
sps->output_window.top_offset += sps->vui.def_disp_win.top_offset;
sps->output_window.bottom_offset += sps->vui.def_disp_win.bottom_offset;
ow = &sps->output_window;
if (ow->left_offset >= INT_MAX - ow->right_offset ||
ow->top_offset >= INT_MAX - ow->bottom_offset ||
ow->left_offset + ow->right_offset >= sps->width ||
ow->top_offset + ow->bottom_offset >= sps->height) {
av_log(avctx, AV_LOG_WARNING, "Invalid cropping offsets: %u/%u/%u/%u\n",
ow->left_offset, ow->right_offset, ow->top_offset, ow->bottom_offset);
if (avctx->err_recognition & AV_EF_EXPLODE) {
av_log(avctx, AV_LOG_WARNING,
"Displaying the whole video surface.\n");
memset(ow, 0, sizeof(*ow));
sps->log2_ctb_size = sps->log2_min_cb_size +
sps->log2_diff_max_min_coding_block_size;
sps->log2_min_pu_size = sps->log2_min_cb_size - 1;
sps->ctb_width = (sps->width + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size;
sps->ctb_height = (sps->height + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size;
sps->ctb_size = sps->ctb_width * sps->ctb_height;
sps->min_cb_width = sps->width >> sps->log2_min_cb_size;
sps->min_cb_height = sps->height >> sps->log2_min_cb_size;
sps->min_tb_width = sps->width >> sps->log2_min_tb_size;
sps->min_tb_height = sps->height >> sps->log2_min_tb_size;
sps->min_pu_width = sps->width >> sps->log2_min_pu_size;
sps->min_pu_height = sps->height >> sps->log2_min_pu_size;
sps->qp_bd_offset = 6 * (sps->bit_depth - 8);
if (sps->width & ((1 << sps->log2_min_cb_size) - 1) ||
sps->height & ((1 << sps->log2_min_cb_size) - 1)) {
av_log(avctx, AV_LOG_ERROR, "Invalid coded frame dimensions.\n");
if (sps->log2_ctb_size > HEVC_MAX_LOG2_CTB_SIZE) {
av_log(avctx, AV_LOG_ERROR, "CTB size out of range: 2^%d\n", sps->log2_ctb_size);
if (sps->max_transform_hierarchy_depth_inter > sps->log2_ctb_size - sps->log2_min_tb_size) {
av_log(avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_inter out of range: %d\n",
sps->max_transform_hierarchy_depth_inter);
if (sps->max_transform_hierarchy_depth_intra > sps->log2_ctb_size - sps->log2_min_tb_size) {
av_log(avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_intra out of range: %d\n",
sps->max_transform_hierarchy_depth_intra);
if (sps->log2_max_trafo_size > FFMIN(sps->log2_ctb_size, 5)) {
av_log(avctx, AV_LOG_ERROR,
"max transform block size out of range: %d\n",
sps->log2_max_trafo_size);
return 0;
err:
return ret < 0 ? ret : AVERROR_INVALIDDATA;
|
int ff_hevc_parse_sps(HEVCSPS *sps, GetBitContext *gb, unsigned int *sps_id,
int apply_defdispwin, AVBufferRef **vps_list, AVCodecContext *avctx)
{
HEVCWindow *ow;
int ret = 0;
int log2_diff_max_min_transform_block_size;
int bit_depth_chroma, start, vui_present, sublayer_ordering_info;
int i;
sps->vps_id = get_bits(gb, 4);
if (sps->vps_id >= HEVC_MAX_VPS_COUNT) {
av_log(avctx, AV_LOG_ERROR, "VPS id out of range: %d\n", sps->vps_id);
ret = AVERROR_INVALIDDATA;
goto err;
}
if (vps_list && !vps_list[sps->vps_id]) {
av_log(avctx, AV_LOG_ERROR, "VPS %d does not exist\n",
sps->vps_id);
ret = AVERROR_INVALIDDATA;
goto err;
}
sps->max_sub_layers = get_bits(gb, 3) + 1;
if (sps->max_sub_layers > HEVC_MAX_SUB_LAYERS) {
av_log(avctx, AV_LOG_ERROR, "sps_max_sub_layers out of range: %d\n",
sps->max_sub_layers);
ret = AVERROR_INVALIDDATA;
goto err;
}
skip_bits1(gb);
parse_ptl(gb, avctx, &sps->ptl, sps->max_sub_layers);
*sps_id = get_ue_golomb_long(gb);
if (*sps_id >= HEVC_MAX_SPS_COUNT) {
av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", *sps_id);
ret = AVERROR_INVALIDDATA;
goto err;
}
sps->chroma_format_idc = get_ue_golomb_long(gb);
if (sps->chroma_format_idc != 1) {
avpriv_report_missing_feature(avctx, "chroma_format_idc %d",
sps->chroma_format_idc);
ret = AVERROR_PATCHWELCOME;
goto err;
}
if (sps->chroma_format_idc == 3)
sps->separate_colour_plane_flag = get_bits1(gb);
sps->width = get_ue_golomb_long(gb);
sps->height = get_ue_golomb_long(gb);
if ((ret = av_image_check_size(sps->width,
sps->height, 0, avctx)) < 0)
goto err;
if (get_bits1(gb)) {
sps->pic_conf_win.left_offset = get_ue_golomb_long(gb) * 2;
sps->pic_conf_win.right_offset = get_ue_golomb_long(gb) * 2;
sps->pic_conf_win.top_offset = get_ue_golomb_long(gb) * 2;
sps->pic_conf_win.bottom_offset = get_ue_golomb_long(gb) * 2;
if (avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {
av_log(avctx, AV_LOG_DEBUG,
"discarding sps conformance window, "
"original values are l:%u r:%u t:%u b:%u\n",
sps->pic_conf_win.left_offset,
sps->pic_conf_win.right_offset,
sps->pic_conf_win.top_offset,
sps->pic_conf_win.bottom_offset);
sps->pic_conf_win.left_offset =
sps->pic_conf_win.right_offset =
sps->pic_conf_win.top_offset =
sps->pic_conf_win.bottom_offset = 0;
}
sps->output_window = sps->pic_conf_win;
}
sps->bit_depth = get_ue_golomb_long(gb) + 8;
bit_depth_chroma = get_ue_golomb_long(gb) + 8;
if (bit_depth_chroma != sps->bit_depth) {
av_log(avctx, AV_LOG_ERROR,
"Luma bit depth (%d) is different from chroma bit depth (%d), "
"this is unsupported.\n",
sps->bit_depth, bit_depth_chroma);
ret = AVERROR_INVALIDDATA;
goto err;
}
ret = map_pixel_format(avctx, sps);
if (ret < 0)
goto err;
sps->log2_max_poc_lsb = get_ue_golomb_long(gb) + 4;
if (sps->log2_max_poc_lsb > 16) {
av_log(avctx, AV_LOG_ERROR, "log2_max_pic_order_cnt_lsb_minus4 out range: %d\n",
sps->log2_max_poc_lsb - 4);
ret = AVERROR_INVALIDDATA;
goto err;
}
sublayer_ordering_info = get_bits1(gb);
start = sublayer_ordering_info ? 0 : sps->max_sub_layers - 1;
for (i = start; i < sps->max_sub_layers; i++) {
sps->temporal_layer[i].max_dec_pic_buffering = get_ue_golomb_long(gb) + 1;
sps->temporal_layer[i].num_reorder_pics = get_ue_golomb_long(gb);
sps->temporal_layer[i].max_latency_increase = get_ue_golomb_long(gb) - 1;
if (sps->temporal_layer[i].max_dec_pic_buffering > HEVC_MAX_DPB_SIZE) {
av_log(avctx, AV_LOG_ERROR, "sps_max_dec_pic_buffering_minus1 out of range: %d\n",
sps->temporal_layer[i].max_dec_pic_buffering - 1);
ret = AVERROR_INVALIDDATA;
goto err;
}
if (sps->temporal_layer[i].num_reorder_pics > sps->temporal_layer[i].max_dec_pic_buffering - 1) {
av_log(avctx, AV_LOG_WARNING, "sps_max_num_reorder_pics out of range: %d\n",
sps->temporal_layer[i].num_reorder_pics);
if (avctx->err_recognition & AV_EF_EXPLODE ||
sps->temporal_layer[i].num_reorder_pics > HEVC_MAX_DPB_SIZE - 1) {
ret = AVERROR_INVALIDDATA;
goto err;
}
sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[i].num_reorder_pics + 1;
}
}
if (!sublayer_ordering_info) {
for (i = 0; i < start; i++) {
sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[start].max_dec_pic_buffering;
sps->temporal_layer[i].num_reorder_pics = sps->temporal_layer[start].num_reorder_pics;
sps->temporal_layer[i].max_latency_increase = sps->temporal_layer[start].max_latency_increase;
}
}
sps->log2_min_cb_size = get_ue_golomb_long(gb) + 3;
sps->log2_diff_max_min_coding_block_size = get_ue_golomb_long(gb);
sps->log2_min_tb_size = get_ue_golomb_long(gb) + 2;
log2_diff_max_min_transform_block_size = get_ue_golomb_long(gb);
sps->log2_max_trafo_size = log2_diff_max_min_transform_block_size +
sps->log2_min_tb_size;
if (sps->log2_min_tb_size >= sps->log2_min_cb_size) {
av_log(avctx, AV_LOG_ERROR, "Invalid value for log2_min_tb_size");
ret = AVERROR_INVALIDDATA;
goto err;
}
sps->max_transform_hierarchy_depth_inter = get_ue_golomb_long(gb);
sps->max_transform_hierarchy_depth_intra = get_ue_golomb_long(gb);
sps->scaling_list_enable_flag = get_bits1(gb);
if (sps->scaling_list_enable_flag) {
set_default_scaling_list_data(&sps->scaling_list);
if (get_bits1(gb)) {
ret = scaling_list_data(gb, avctx, &sps->scaling_list);
if (ret < 0)
goto err;
}
}
sps->amp_enabled_flag = get_bits1(gb);
sps->sao_enabled = get_bits1(gb);
sps->pcm_enabled_flag = get_bits1(gb);
if (sps->pcm_enabled_flag) {
sps->pcm.bit_depth = get_bits(gb, 4) + 1;
sps->pcm.bit_depth_chroma = get_bits(gb, 4) + 1;
sps->pcm.log2_min_pcm_cb_size = get_ue_golomb_long(gb) + 3;
sps->pcm.log2_max_pcm_cb_size = sps->pcm.log2_min_pcm_cb_size +
get_ue_golomb_long(gb);
if (sps->pcm.bit_depth > sps->bit_depth) {
av_log(avctx, AV_LOG_ERROR,
"PCM bit depth (%d) is greater than normal bit depth (%d)\n",
sps->pcm.bit_depth, sps->bit_depth);
ret = AVERROR_INVALIDDATA;
goto err;
}
sps->pcm.loop_filter_disable_flag = get_bits1(gb);
}
sps->nb_st_rps = get_ue_golomb_long(gb);
if (sps->nb_st_rps > HEVC_MAX_SHORT_TERM_REF_PIC_SETS) {
av_log(avctx, AV_LOG_ERROR, "Too many short term RPS: %d.\n",
sps->nb_st_rps);
ret = AVERROR_INVALIDDATA;
goto err;
}
for (i = 0; i < sps->nb_st_rps; i++) {
if ((ret = ff_hevc_decode_short_term_rps(gb, avctx, &sps->st_rps[i],
sps, 0)) < 0)
goto err;
}
sps->long_term_ref_pics_present_flag = get_bits1(gb);
if (sps->long_term_ref_pics_present_flag) {
sps->num_long_term_ref_pics_sps = get_ue_golomb_long(gb);
if (sps->num_long_term_ref_pics_sps > HEVC_MAX_LONG_TERM_REF_PICS) {
av_log(avctx, AV_LOG_ERROR, "Too many long term ref pics: %d.\n",
sps->num_long_term_ref_pics_sps);
ret = AVERROR_INVALIDDATA;
goto err;
}
for (i = 0; i < sps->num_long_term_ref_pics_sps; i++) {
sps->lt_ref_pic_poc_lsb_sps[i] = get_bits(gb, sps->log2_max_poc_lsb);
sps->used_by_curr_pic_lt_sps_flag[i] = get_bits1(gb);
}
}
sps->sps_temporal_mvp_enabled_flag = get_bits1(gb);
sps->sps_strong_intra_smoothing_enable_flag = get_bits1(gb);
sps->vui.sar = (AVRational){0, 1};
vui_present = get_bits1(gb);
if (vui_present)
decode_vui(gb, avctx, apply_defdispwin, sps);
skip_bits1(gb);
if (apply_defdispwin) {
sps->output_window.left_offset += sps->vui.def_disp_win.left_offset;
sps->output_window.right_offset += sps->vui.def_disp_win.right_offset;
sps->output_window.top_offset += sps->vui.def_disp_win.top_offset;
sps->output_window.bottom_offset += sps->vui.def_disp_win.bottom_offset;
}
ow = &sps->output_window;
if (ow->left_offset >= INT_MAX - ow->right_offset ||
ow->top_offset >= INT_MAX - ow->bottom_offset ||
ow->left_offset + ow->right_offset >= sps->width ||
ow->top_offset + ow->bottom_offset >= sps->height) {
av_log(avctx, AV_LOG_WARNING, "Invalid cropping offsets: %u/%u/%u/%u\n",
ow->left_offset, ow->right_offset, ow->top_offset, ow->bottom_offset);
if (avctx->err_recognition & AV_EF_EXPLODE) {
ret = AVERROR_INVALIDDATA;
goto err;
}
av_log(avctx, AV_LOG_WARNING,
"Displaying the whole video surface.\n");
memset(ow, 0, sizeof(*ow));
}
sps->log2_ctb_size = sps->log2_min_cb_size +
sps->log2_diff_max_min_coding_block_size;
sps->log2_min_pu_size = sps->log2_min_cb_size - 1;
sps->ctb_width = (sps->width + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size;
sps->ctb_height = (sps->height + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size;
sps->ctb_size = sps->ctb_width * sps->ctb_height;
sps->min_cb_width = sps->width >> sps->log2_min_cb_size;
sps->min_cb_height = sps->height >> sps->log2_min_cb_size;
sps->min_tb_width = sps->width >> sps->log2_min_tb_size;
sps->min_tb_height = sps->height >> sps->log2_min_tb_size;
sps->min_pu_width = sps->width >> sps->log2_min_pu_size;
sps->min_pu_height = sps->height >> sps->log2_min_pu_size;
sps->qp_bd_offset = 6 * (sps->bit_depth - 8);
if (sps->width & ((1 << sps->log2_min_cb_size) - 1) ||
sps->height & ((1 << sps->log2_min_cb_size) - 1)) {
av_log(avctx, AV_LOG_ERROR, "Invalid coded frame dimensions.\n");
goto err;
}
if (sps->log2_ctb_size > HEVC_MAX_LOG2_CTB_SIZE) {
av_log(avctx, AV_LOG_ERROR, "CTB size out of range: 2^%d\n", sps->log2_ctb_size);
goto err;
}
if (sps->max_transform_hierarchy_depth_inter > sps->log2_ctb_size - sps->log2_min_tb_size) {
av_log(avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_inter out of range: %d\n",
sps->max_transform_hierarchy_depth_inter);
goto err;
}
if (sps->max_transform_hierarchy_depth_intra > sps->log2_ctb_size - sps->log2_min_tb_size) {
av_log(avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_intra out of range: %d\n",
sps->max_transform_hierarchy_depth_intra);
goto err;
}
if (sps->log2_max_trafo_size > FFMIN(sps->log2_ctb_size, 5)) {
av_log(avctx, AV_LOG_ERROR,
"max transform block size out of range: %d\n",
sps->log2_max_trafo_size);
goto err;
}
return 0;
err:
return ret < 0 ? ret : AVERROR_INVALIDDATA;
}
| null | null | null |
FFmpeg/commit/1329c08ad6d2ddb304858f2972c67b508e8b0f0e
|
hevc: Validate the number of long term reference pictures
This would overflow if the stream contained a value greater than the
maximum allowed by the standard (32).
|
./ffmpeg/libavcodec/hevc_ps.c
|
c
|
2017-06-23T23:29:14Z
|
vu_queue_notify(VuDev *dev, VuVirtq *vq)
{
if (unlikely(dev->broken)) {
return;
}
if (!vring_notify(dev, vq)) {
DPRINT("skipped notify...\n");
return;
}
if (eventfd_write(vq->call_fd, 1) < 0) {
vu_panic(dev, "Error writing eventfd: %s", strerror(errno));
}
}
|
vu_queue_notify(VuDev *dev, VuVirtq *vq)
{
if (unlikely(dev->broken) ||
unlikely(!vq->vring.avail)) {
return;
}
if (!vring_notify(dev, vq)) {
DPRINT("skipped notify...\n");
return;
}
if (eventfd_write(vq->call_fd, 1) < 0) {
vu_panic(dev, "Error writing eventfd: %s", strerror(errno));
}
}
| null | null | null |
qemu/commit/640601c7cb1b6b41d3e1a435b986266c2b71e9bc
|
libvhost-user: fix crash when rings aren't ready
Calling libvhost-user functions like vu_queue_get_avail_bytes() when the
queue doesn't yet have addresses will result in the crashes like the
following:
Program received signal SIGSEGV, Segmentation fault.
0x000055c414112ce4 in vring_avail_idx (vq=0x55c41582fd68, vq=0x55c41582fd68)
at /home/dgilbert/git/qemu/contrib/libvhost-user/libvhost-user.c:940
940 vq->shadow_avail_idx = vq->vring.avail->idx
(gdb) p vq
$1 = (VuVirtq *) 0x55c41582fd68
(gdb) p vq->vring
$2 = {num = 0, desc = 0x0, avail = 0x0, used = 0x0, log_guest_addr = 0, flags = 0}
at /home/dgilbert/git/qemu/contrib/libvhost-user/libvhost-user.c:940
No locals.
at /home/dgilbert/git/qemu/contrib/libvhost-user/libvhost-user.c:960
num_heads = <optimized out>
out_bytes=out_bytes@entry=0x7fffd035d7c4, max_in_bytes=max_in_bytes@entry=0,
max_out_bytes=max_out_bytes@entry=0) at /home/dgilbert/git/qemu/contrib/libvhost-user/libvhost-user.c:1034
Add a pre-condition checks on vring.avail before accessing it.
Fix documentation and return type of vu_queue_empty() while at it.
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Tested-by: Dr. David Alan Gilbert <dgilbert@redhat.com>
Reviewed-by: Philippe Mathieu-Daudé <f4bug@amsat.org>
Reviewed-by: Michael S. Tsirkin <mst@redhat.com>
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
|
./qemu/contrib/libvhost-user/libvhost-user.c
|
c
|
2017-05-03T16:54:12Z
|
void ep_map_dst(ep_t p, const uint8_t *msg, int len, const uint8_t *dst,
int dst_len) {
/* enough space for two field elements plus extra bytes for uniformity */
const int len_per_elm = (FP_PRIME + ep_param_level() + 7) / 8;
uint8_t *pseudo_random_bytes = RLC_ALLOCA(uint8_t, 2 * len_per_elm);
RLC_TRY {
/* for hash_to_field, need to hash to a pseudorandom string */
/* XXX(rsw) the below assumes that we want to use MD_MAP for hashing.
* Consider making the hash function a per-curve option!
*/
md_xmd(pseudo_random_bytes, 2 * len_per_elm, msg, len, dst, dst_len);
ep_map_from_field(p, pseudo_random_bytes, 2 * len_per_elm);
}
RLC_CATCH_ANY {
RLC_THROW(ERR_CAUGHT);
}
|
void ep_map_dst(ep_t p, const uint8_t *msg, size_t len, const uint8_t *dst,
size_t dst_len) {
/* enough space for two field elements plus extra bytes for uniformity */
const int len_per_elm = (FP_PRIME + ep_param_level() + 7) / 8;
uint8_t *pseudo_random_bytes = RLC_ALLOCA(uint8_t, 2 * len_per_elm);
RLC_TRY {
/* for hash_to_field, need to hash to a pseudorandom string */
/* XXX(rsw) the below assumes that we want to use MD_MAP for hashing.
* Consider making the hash function a per-curve option!
*/
md_xmd(pseudo_random_bytes, 2 * len_per_elm, msg, len, dst, dst_len);
ep_map_from_field(p, pseudo_random_bytes, 2 * len_per_elm);
}
RLC_CATCH_ANY {
RLC_THROW(ERR_CAUGHT);
}
| null | null | null |
https://github.com/relic-toolkit/relic/commit/34580d840469361ba9b5f001361cad659687b9ab
|
Huge commit improving the API to use size_t instead of int.
|
src/ep/relic_ep_map.c
|
c
|
2022-11-14T20:47:12Z
|
AP4_Processor::Process(AP4_ByteStream& input,
AP4_ByteStream& output,
AP4_ByteStream* fragments,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
{
// read all atoms.
// keep all atoms except [mdat]
// keep a ref to [moov]
// put [moof] atoms in a separate list
AP4_AtomParent top_level;
AP4_MoovAtom* moov = NULL;
AP4_ContainerAtom* mfra = NULL;
AP4_SidxAtom* sidx = NULL;
AP4_List<AP4_AtomLocator> frags;
AP4_UI64 stream_offset = 0;
bool in_fragments = false;
unsigned int sidx_count = 0;
for (AP4_Atom* atom = NULL;
AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(input, atom));
input.Tell(stream_offset)) {
if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {
delete atom;
continue;
} else if (atom->GetType() == AP4_ATOM_TYPE_MOOV) {
moov = AP4_DYNAMIC_CAST(AP4_MoovAtom, atom);
if (fragments) break;
} else if (atom->GetType() == AP4_ATOM_TYPE_MFRA) {
mfra = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
continue;
} else if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {
// don't keep the index, it is likely to be invalidated, we will recompute it later
++sidx_count;
if (sidx == NULL) {
sidx = AP4_DYNAMIC_CAST(AP4_SidxAtom, atom);
} else {
delete atom;
continue;
}
} else if (atom->GetType() == AP4_ATOM_TYPE_SSIX) {
// don't keep the index, it is likely to be invalidated
delete atom;
continue;
} else if (!fragments && (in_fragments || atom->GetType() == AP4_ATOM_TYPE_MOOF)) {
in_fragments = true;
frags.Add(new AP4_AtomLocator(atom, stream_offset));
continue;
}
top_level.AddChild(atom);
}
// check that we have at most one sidx (we can't deal with multi-sidx streams here
if (sidx_count > 1) {
top_level.RemoveChild(sidx);
delete sidx;
sidx = NULL;
}
// if we have a fragments stream, get the fragment locators from there
if (fragments) {
stream_offset = 0;
for (AP4_Atom* atom = NULL;
AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(*fragments, atom));
fragments->Tell(stream_offset)) {
if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {
delete atom;
continue;
}
frags.Add(new AP4_AtomLocator(atom, stream_offset));
}
}
// initialize the processor
AP4_Result result = Initialize(top_level, input);
if (AP4_FAILED(result)) return result;
// process the tracks if we have a moov atom
AP4_Array<AP4_SampleLocator> locators;
AP4_Cardinal track_count = 0;
AP4_List<AP4_TrakAtom>* trak_atoms = NULL;
AP4_LargeSize mdat_payload_size = 0;
AP4_SampleCursor* cursors = NULL;
if (moov) {
// build an array of track sample locators
trak_atoms = &moov->GetTrakAtoms();
track_count = trak_atoms->ItemCount();
cursors = new AP4_SampleCursor[track_count];
m_TrackHandlers.SetItemCount(track_count);
m_TrackIds.SetItemCount(track_count);
for (AP4_Ordinal i=0; i<track_count; i++) {
m_TrackHandlers[i] = NULL;
m_TrackIds[i] = 0;
}
unsigned int index = 0;
for (AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem(); item; item=item->GetNext()) {
AP4_TrakAtom* trak = item->GetData();
// find the stsd atom
AP4_ContainerAtom* stbl = AP4_DYNAMIC_CAST(AP4_ContainerAtom, trak->FindChild("mdia/minf/stbl"));
if (stbl == NULL) continue;
// see if there's an external data source for this track
AP4_ByteStream* trak_data_stream = &input;
for (AP4_List<ExternalTrackData>::Item* ditem = m_ExternalTrackData.FirstItem(); ditem; ditem=ditem->GetNext()) {
ExternalTrackData* tdata = ditem->GetData();
if (tdata->m_TrackId == trak->GetId()) {
trak_data_stream = tdata->m_MediaData;
break;
}
}
// create the track handler
m_TrackHandlers[index] = CreateTrackHandler(trak);
m_TrackIds[index] = trak->GetId();
cursors[index].m_Locator.m_TrakIndex = index;
cursors[index].m_Locator.m_SampleTable = new AP4_AtomSampleTable(stbl, *trak_data_stream);
cursors[index].m_Locator.m_SampleIndex = 0;
cursors[index].m_Locator.m_ChunkIndex = 0;
if (cursors[index].m_Locator.m_SampleTable->GetSampleCount()) {
cursors[index].m_Locator.m_SampleTable->GetSample(0, cursors[index].m_Locator.m_Sample);
} else {
cursors[index].m_EndReached = true;
}
index++;
}
// figure out the layout of the chunks
for (;;) {
// see which is the next sample to write
AP4_UI64 min_offset = (AP4_UI64)(-1);
int cursor = -1;
for (unsigned int i=0; i<track_count; i++) {
if (!cursors[i].m_EndReached &&
cursors[i].m_Locator.m_Sample.GetOffset() <= min_offset) {
min_offset = cursors[i].m_Locator.m_Sample.GetOffset();
cursor = i;
}
}
// stop if all cursors are exhausted
if (cursor == -1) break;
// append this locator to the layout list
AP4_SampleLocator& locator = cursors[cursor].m_Locator;
locators.Append(locator);
// move the cursor to the next sample
locator.m_SampleIndex++;
if (locator.m_SampleIndex == locator.m_SampleTable->GetSampleCount()) {
// mark this track as completed
cursors[cursor].m_EndReached = true;
} else {
// get the next sample info
locator.m_SampleTable->GetSample(locator.m_SampleIndex, locator.m_Sample);
AP4_Ordinal skip, sdesc;
locator.m_SampleTable->GetChunkForSample(locator.m_SampleIndex,
locator.m_ChunkIndex,
skip, sdesc);
}
}
// update the stbl atoms and compute the mdat size
int current_track = -1;
int current_chunk = -1;
AP4_Position current_chunk_offset = 0;
AP4_Size current_chunk_size = 0;
for (AP4_Ordinal i=0; i<locators.ItemCount(); i++) {
AP4_SampleLocator& locator = locators[i];
if ((int)locator.m_TrakIndex != current_track ||
(int)locator.m_ChunkIndex != current_chunk) {
// start a new chunk for this track
current_chunk_offset += current_chunk_size;
current_chunk_size = 0;
current_track = locator.m_TrakIndex;
current_chunk = locator.m_ChunkIndex;
locator.m_SampleTable->SetChunkOffset(locator.m_ChunkIndex, current_chunk_offset);
}
AP4_Size sample_size;
TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];
if (handler) {
sample_size = handler->GetProcessedSampleSize(locator.m_Sample);
locator.m_SampleTable->SetSampleSize(locator.m_SampleIndex, sample_size);
} else {
sample_size = locator.m_Sample.GetSize();
}
current_chunk_size += sample_size;
mdat_payload_size += sample_size;
}
// process the tracks (ex: sample descriptions processing)
for (AP4_Ordinal i=0; i<track_count; i++) {
TrackHandler* handler = m_TrackHandlers[i];
if (handler) handler->ProcessTrack();
}
}
// finalize the processor
Finalize(top_level);
if (!fragments) {
// calculate the size of all atoms combined
AP4_UI64 atoms_size = 0;
top_level.GetChildren().Apply(AP4_AtomSizeAdder(atoms_size));
// see if we need a 64-bit or 32-bit mdat
AP4_Size mdat_header_size = AP4_ATOM_HEADER_SIZE;
if (mdat_payload_size+mdat_header_size > 0xFFFFFFFF) {
// we need a 64-bit size
mdat_header_size += 8;
}
// adjust the chunk offsets
for (AP4_Ordinal i=0; i<track_count; i++) {
AP4_TrakAtom* trak;
trak_atoms->Get(i, trak);
trak->AdjustChunkOffsets(atoms_size+mdat_header_size);
}
// write all atoms
top_level.GetChildren().Apply(AP4_AtomListWriter(output));
// write mdat header
if (mdat_payload_size) {
if (mdat_header_size == AP4_ATOM_HEADER_SIZE) {
// 32-bit size
output.WriteUI32((AP4_UI32)(mdat_header_size+mdat_payload_size));
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
} else {
// 64-bit size
output.WriteUI32(1);
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
output.WriteUI64(mdat_header_size+mdat_payload_size);
}
}
}
// write the samples
if (moov) {
if (!fragments) {
#if defined(AP4_DEBUG)
AP4_Position before;
output.Tell(before);
#endif
AP4_Sample sample;
AP4_DataBuffer data_in;
AP4_DataBuffer data_out;
for (unsigned int i=0; i<locators.ItemCount(); i++) {
AP4_SampleLocator& locator = locators[i];
locator.m_Sample.ReadData(data_in);
TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];
if (handler) {
result = handler->ProcessSample(data_in, data_out);
if (AP4_FAILED(result)) return result;
output.Write(data_out.GetData(), data_out.GetDataSize());
} else {
output.Write(data_in.GetData(), data_in.GetDataSize());
}
// notify the progress listener
if (listener) {
listener->OnProgress(i+1, locators.ItemCount());
}
}
#if defined(AP4_DEBUG)
AP4_Position after;
output.Tell(after);
AP4_ASSERT(after-before == mdat_payload_size);
#endif
}
// find the position of the sidx atom
AP4_Position sidx_position = 0;
if (sidx) {
for (AP4_List<AP4_Atom>::Item* item = top_level.GetChildren().FirstItem();
item;
item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {
break;
}
sidx_position += atom->GetSize();
}
}
// process the fragments, if any
result = ProcessFragments(moov, frags, mfra, sidx, sidx_position, fragments?*fragments:input, output);
if (AP4_FAILED(result)) return result;
// update and re-write the sidx if we have one
if (sidx && sidx_position) {
AP4_Position where = 0;
output.Tell(where);
output.Seek(sidx_position);
result = sidx->Write(output);
if (AP4_FAILED(result)) return result;
output.Seek(where);
}
if (!fragments) {
// write the mfra atom at the end if we have one
if (mfra) {
mfra->Write(output);
}
}
// cleanup
for (AP4_Ordinal i=0; i<track_count; i++) {
delete cursors[i].m_Locator.m_SampleTable;
delete m_TrackHandlers[i];
}
m_TrackHandlers.Clear();
delete[] cursors;
}
// cleanup
frags.DeleteReferences();
delete mfra;
return AP4_SUCCESS;
}
|
AP4_Processor::Process(AP4_ByteStream& input,
AP4_ByteStream& output,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
{
return Process(input, output, NULL, listener, atom_factory);
}
| null |
CWE-476, CWE-703
| null |
https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e
|
fixed possible crashes on malformed inputs.
| null | null |
2017-07-30T22:29:24Z
|
static int rtsx_usb_ms_drv_probe(struct platform_device *pdev)
{
struct memstick_host *msh;
struct rtsx_usb_ms *host;
struct rtsx_ucr *ucr;
int err;
ucr = usb_get_intfdata(to_usb_interface(pdev->dev.parent));
if (!ucr)
return -ENXIO;
dev_dbg(&(pdev->dev),
"Realtek USB Memstick controller found\n");
msh = memstick_alloc_host(sizeof(*host), &pdev->dev);
if (!msh)
return -ENOMEM;
host = memstick_priv(msh);
host->ucr = ucr;
host->msh = msh;
host->pdev = pdev;
host->power_mode = MEMSTICK_POWER_OFF;
platform_set_drvdata(pdev, host);
mutex_init(&host->host_mutex);
INIT_WORK(&host->handle_req, rtsx_usb_ms_handle_req);
INIT_DELAYED_WORK(&host->poll_card, rtsx_usb_ms_poll_card);
msh->request = rtsx_usb_ms_request;
msh->set_param = rtsx_usb_ms_set_param;
msh->caps = MEMSTICK_CAP_PAR4;
pm_runtime_get_noresume(ms_dev(host));
pm_runtime_set_active(ms_dev(host));
pm_runtime_enable(ms_dev(host));
err = memstick_add_host(msh);
if (err)
goto err_out;
pm_runtime_put(ms_dev(host));
return 0;
err_out:
memstick_free_host(msh);
pm_runtime_disable(ms_dev(host));
pm_runtime_put_noidle(ms_dev(host));
return err;
}
|
static int rtsx_usb_ms_drv_probe(struct platform_device *pdev)
{
struct memstick_host *msh;
struct rtsx_usb_ms *host;
struct rtsx_ucr *ucr;
int err;
ucr = usb_get_intfdata(to_usb_interface(pdev->dev.parent));
if (!ucr)
return -ENXIO;
dev_dbg(&(pdev->dev),
"Realtek USB Memstick controller found\n");
msh = memstick_alloc_host(sizeof(*host), &pdev->dev);
if (!msh)
return -ENOMEM;
host = memstick_priv(msh);
host->ucr = ucr;
host->msh = msh;
host->pdev = pdev;
host->power_mode = MEMSTICK_POWER_OFF;
platform_set_drvdata(pdev, host);
mutex_init(&host->host_mutex);
INIT_WORK(&host->handle_req, rtsx_usb_ms_handle_req);
INIT_DELAYED_WORK(&host->poll_card, rtsx_usb_ms_poll_card);
msh->request = rtsx_usb_ms_request;
msh->set_param = rtsx_usb_ms_set_param;
msh->caps = MEMSTICK_CAP_PAR4;
pm_runtime_get_noresume(ms_dev(host));
pm_runtime_set_active(ms_dev(host));
pm_runtime_enable(ms_dev(host));
err = memstick_add_host(msh);
if (err)
goto err_out;
pm_runtime_put(ms_dev(host));
return 0;
err_out:
pm_runtime_disable(ms_dev(host));
pm_runtime_put_noidle(ms_dev(host));
memstick_free_host(msh);
return err;
}
|
CVE-2022-0487
|
CWE-416
|
A use-after-free vulnerability was found in rtsx_usb_ms_drv_remove in drivers/memstick/host/rtsx_usb_ms.c in memstick in the Linux kernel. In this flaw, a local attacker with a user privilege may impact system Confidentiality. This flaw affects kernel versions prior to 5.14 rc1.
|
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=42933c8aa14be1caa9eda41f65cde8a3a95d3e39
|
memstick: rtsx_usb_ms: fix UAF
This patch fixes the following issues:
1. memstick_free_host() will free the host, so the use of ms_dev(host) after
it will be a problem. To fix this, move memstick_free_host() after when we
are done with ms_dev(host).
2. In rtsx_usb_ms_drv_remove(), pm need to be disabled before we remove
and free host otherwise memstick_check will be called and UAF will
happen.
[ 11.351173] BUG: KASAN: use-after-free in rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]
[ 11.357077] rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]
[ 11.357376] platform_remove+0x2a/0x50
[ 11.367531] Freed by task 298:
[ 11.368537] kfree+0xa4/0x2a0
[ 11.368711] device_release+0x51/0xe0
[ 11.368905] kobject_put+0xa2/0x120
[ 11.369090] rtsx_usb_ms_drv_remove+0x8c/0x140 [rtsx_usb_ms]
[ 11.369386] platform_remove+0x2a/0x50
[ 12.038408] BUG: KASAN: use-after-free in __mutex_lock.isra.0+0x3ec/0x7c0
[ 12.045432] mutex_lock+0xc9/0xd0
[ 12.046080] memstick_check+0x6a/0x578 [memstick]
[ 12.046509] process_one_work+0x46d/0x750
[ 12.052107] Freed by task 297:
[ 12.053115] kfree+0xa4/0x2a0
[ 12.053272] device_release+0x51/0xe0
[ 12.053463] kobject_put+0xa2/0x120
[ 12.053647] rtsx_usb_ms_drv_remove+0xc4/0x140 [rtsx_usb_ms]
[ 12.053939] platform_remove+0x2a/0x50
Signed-off-by: Tong Zhang <ztong0001@gmail.com>
Co-developed-by: Ulf Hansson <ulf.hansson@linaro.org>
Link: https://lore.kernel.org/r/20210511163944.1233295-1-ztong0001@gmail.com
Signed-off-by: Ulf Hansson <ulf.hansson@linaro.org>
| null | null | null |
X509::X509(const char* i, size_t iSz, const char* s, size_t sSz,
const char* b, int bSz, const char* a, int aSz)
: issuer_(i, iSz), subject_(s, sSz),
beforeDate_(b, bSz), afterDate_(a, aSz)
{}
|
X509::X509(const char* i, size_t iSz, const char* s, size_t sSz,
const char* b, int bSz, const char* a, int aSz, int issPos,
int issLen, int subPos, int subLen)
: issuer_(i, iSz, issPos, issLen), subject_(s, sSz, subPos, subLen),
beforeDate_(b, bSz), afterDate_(a, aSz)
{}
|
CVE-2016-2047
|
CWE-254
|
The ssl_verify_server_cert function in sql-common/client.c in MariaDB before 5.5.47, 10.0.x before 10.0.23, and 10.1.x before 10.1.10; Oracle MySQL 5.5.48 and earlier, 5.6.29 and earlier, and 5.7.11 and earlier; and Percona Server do not properly verify that the server hostname matches a domain name in the subject's Common Name (CN) or subjectAltName field of the X.509 certificate, which allows man-in-the-middle attackers to spoof SSL servers via a "/CN=" string in a field in a certificate, as demonstrated by "/OU=/CN=bar.com/CN=foo.com."
|
https://github.com/mysql/mysql-server/commit/e7061f7e5a96c66cb2e0bf46bec7f6ff35801a69
|
Bug #22738607: YASSL FUNCTION X509_NAME_GET_INDEX_BY_NID IS NOT WORKING AS EXPECTED.
| null | null |
2016-02-26T06:23:56Z
|
function f(t,e,r){if((e[0]&192)!==128){t.lastNeed=0;return"�"}if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128){t.lastNeed=1;return"�"}if(t.lastNeed>2&&e.length>2){if((e[2]&192)!==128){t.lastNeed=2;return"�"}}}}
|
function f(t,e,r){if(typeof r!=="number"){r=0}if(r+e.length>t.length){return false}else{return t.indexOf(e,r)!==-1}}
|
CVE-2021-4306
|
CWE-1333
|
A vulnerability classified as problematic has been found in cronvel terminal-kit up to 2.1.7. Affected is an unknown function. The manipulation leads to inefficient regular expression complexity. Upgrading to version 2.1.8 is able to address this issue. The name of the patch is a2e446cc3927b559d0281683feb9b821e83b758c. It is recommended to upgrade the affected component. The identifier of this vulnerability is VDB-217620.
|
https://github.com/cronvel/terminal-kit/commit/a2e446cc3927b559d0281683feb9b821e83b758c
|
Fix a possible ReDoS
|
browser/termkit.min.js
|
js
|
2021-10-12T09:55:03Z
|
def update(request, pk):
topic = Topic.objects.for_update_or_404(pk, request.user)
category_id = topic.category_id
form = TopicForm(
user=request.user,
data=post_data(request),
instance=topic)
if is_post(request) and form.is_valid():
topic = form.save()
if topic.category_id != category_id:
Comment.create_moderation_action(
user=request.user, topic=topic, action=Comment.MOVED)
return redirect(request.POST.get('next', topic.get_absolute_url()))
return render(
request=request,
template_name='spirit/topic/update.html',
context={'form': form})
|
def update(request, pk):
comment = Comment.objects.for_update_or_404(pk, request.user)
form = CommentForm(data=post_data(request), instance=comment)
if is_post(request) and form.is_valid():
pre_comment_update(comment=Comment.objects.get(pk=comment.pk))
comment = form.save()
post_comment_update(comment=comment)
return safe_redirect(request, 'next', comment.get_absolute_url(), method='POST')
return render(
request=request,
template_name='spirit/comment/update.html',
context={'form': form})
|
CVE-2022-0869
|
CWE-601,CWE-601
|
Multiple Open Redirect in GitHub repository nitely/spirit prior to 0.12.3.
|
https://github.com/nitely/spirit/commit/8f32f89654d6c30d56e0dd167059d32146fb32ef
|
fix unsafe redirect (#308)
|
views.py
|
py
|
2022-03-06T10:15:00Z
|
@Override
public void callSessionHoldReceived(ImsCallProfile profile) {
if (mListener != null) {
TelephonyUtils.runWithCleanCallingIdentity(()-> mListener.callSessionHoldReceived(
ImsCallSession.this, profile), mListenerExecutor);
}
}
|
@Override
public void callSessionHoldReceived(ImsCallProfile profile) {
TelephonyUtils.runWithCleanCallingIdentity(()-> {
if (mListener != null) {
mListener.callSessionHoldReceived(ImsCallSession.this, profile);
}
}, mListenerExecutor);
}
| null | null | null |
https://github.com/omnirom/android_frameworks_base/commit/be7c8dca0d1ac7dd3b4c0c476e37f2e42093c456
|
Fix for crash while merging 2 audio calls for initiating conference call
Null pointer exception occured while calling callsessionupdated on listener object.
Listener turned null at the time of executor method is on run. Null check is present before setting the call to executor.
Modified the null checks to be inside of the executor.
Test: Conference call in oriole userdebug
Bug: 210701681
Change-Id: Iffeedb669b4abb9b4f32f015aaea4ba3b99c00f5
Merged-In: Iffeedb669b4abb9b4f32f015aaea4ba3b99c00f5
|
telephony/java/android/telephony/ims/ImsCallSession.java
|
java
|
2022-01-12T04:43:58Z
|
block_crypto_open_opts_init(QCryptoBlockFormat format,
QemuOpts *opts,
Error **errp)
{
OptsVisitor *ov;
QCryptoBlockOpenOptions *ret = NULL;
Error *local_err = NULL;
ret = g_new0(QCryptoBlockOpenOptions, 1);
ret->format = format;
ov = opts_visitor_new(opts);
visit_start_struct(opts_get_visitor(ov),
NULL, NULL, 0, &local_err);
if (local_err) {
goto out;
}
switch (format) {
case Q_CRYPTO_BLOCK_FORMAT_LUKS:
visit_type_QCryptoBlockOptionsLUKS_members(
opts_get_visitor(ov), &ret->u.luks, &local_err);
break;
default:
error_setg(&local_err, "Unsupported block format %d", format);
break;
}
error_propagate(errp, local_err);
local_err = NULL;
visit_end_struct(opts_get_visitor(ov), &local_err);
out:
if (local_err) {
error_propagate(errp, local_err);
qapi_free_QCryptoBlockOpenOptions(ret);
ret = NULL;
}
opts_visitor_cleanup(ov);
return ret;
}
|
block_crypto_open_opts_init(QCryptoBlockFormat format,
QemuOpts *opts,
Error **errp)
{
OptsVisitor *ov;
QCryptoBlockOpenOptions *ret = NULL;
Error *local_err = NULL;
Error *end_err = NULL;
ret = g_new0(QCryptoBlockOpenOptions, 1);
ret->format = format;
ov = opts_visitor_new(opts);
visit_start_struct(opts_get_visitor(ov),
NULL, NULL, 0, &local_err);
if (local_err) {
goto out;
}
switch (format) {
case Q_CRYPTO_BLOCK_FORMAT_LUKS:
visit_type_QCryptoBlockOptionsLUKS_members(
opts_get_visitor(ov), &ret->u.luks, &local_err);
break;
default:
error_setg(&local_err, "Unsupported block format %d", format);
break;
}
visit_end_struct(opts_get_visitor(ov), &end_err);
error_propagate(&local_err, end_err);
out:
if (local_err) {
error_propagate(errp, local_err);
qapi_free_QCryptoBlockOpenOptions(ret);
ret = NULL;
}
opts_visitor_cleanup(ov);
return ret;
}
| null | null | null |
qemu/commit/95c3df5a24e2f18129b58691c2ebaf0d86808525
|
crypto: Avoid memory leak on failure
Commit 7836857 introduced a memory leak due to invalid use of
Error vs. visit_type_end(). If visiting the intermediate
members fails, we clear the error and unconditionally use
visit_end_struct() on the same error object but if that
cleanup succeeds, we then skip the qapi_free call.
Until a later patch adds visit_check_struct(), the only safe
approach is to use two separate error objects.
Signed-off-by: Eric Blake <eblake@redhat.com>
Message-id: 1459526222-30052-1-git-send-email-eblake@redhat.com
Signed-off-by: Max Reitz <mreitz@redhat.com>
|
./qemu/block/crypto.c
|
c
|
2016-04-01T15:57:02Z
|
static int send_sub_rect_jpeg(VncState *vs, int x, int y, int w, int h,
int bg, int fg, int colors,
VncPalette *palette, bool force)
{
int ret;
if (colors == 0) {
if (force || (tight_jpeg_conf[vs->tight.quality].jpeg_full &&
tight_detect_smooth_image(vs, w, h))) {
int quality = tight_conf[vs->tight.quality].jpeg_quality;
ret = send_jpeg_rect(vs, x, y, w, h, quality);
} else {
ret = send_full_color_rect(vs, x, y, w, h);
}
} else if (colors == 1) {
ret = send_solid_rect(vs);
} else if (colors == 2) {
ret = send_mono_rect(vs, x, y, w, h, bg, fg);
} else if (colors <= 256) {
if (force || (colors > 96 &&
tight_jpeg_conf[vs->tight.quality].jpeg_idx &&
tight_detect_smooth_image(vs, w, h))) {
int quality = tight_conf[vs->tight.quality].jpeg_quality;
ret = send_jpeg_rect(vs, x, y, w, h, quality);
} else {
ret = send_palette_rect(vs, x, y, w, h, palette);
}
} else {
ret = 0;
}
return ret;
}
|
static int send_sub_rect_jpeg(VncState *vs, int x, int y, int w, int h,
int bg, int fg, int colors,
VncPalette *palette, bool force)
{
int ret;
if (colors == 0) {
if (force || (tight_jpeg_conf[vs->tight->quality].jpeg_full &&
tight_detect_smooth_image(vs, w, h))) {
int quality = tight_conf[vs->tight->quality].jpeg_quality;
ret = send_jpeg_rect(vs, x, y, w, h, quality);
} else {
ret = send_full_color_rect(vs, x, y, w, h);
}
} else if (colors == 1) {
ret = send_solid_rect(vs);
} else if (colors == 2) {
ret = send_mono_rect(vs, x, y, w, h, bg, fg);
} else if (colors <= 256) {
if (force || (colors > 96 &&
tight_jpeg_conf[vs->tight->quality].jpeg_idx &&
tight_detect_smooth_image(vs, w, h))) {
int quality = tight_conf[vs->tight->quality].jpeg_quality;
ret = send_jpeg_rect(vs, x, y, w, h, quality);
} else {
ret = send_palette_rect(vs, x, y, w, h, palette);
}
} else {
ret = 0;
}
return ret;
}
|
CVE-2019-20382
|
CWE-401
|
QEMU 4.1.0 has a memory leak in zrle_compress_data in ui/vnc-enc-zrle.c during a VNC disconnect operation because libz is misused, resulting in a situation where memory allocated in deflateInit2 is not freed in deflateEnd.
|
https://git.qemu.org/?p=qemu.git;a=commitdiff;h=6bf21f3d83e95bcc4ba35a7a07cc6655e8b010b0
|
vnc: fix memory leak when vnc disconnect
Currently when qemu receives a vnc connect, it creates a 'VncState' to
represent this connection. In 'vnc_worker_thread_loop' it creates a
local 'VncState'. The connection 'VcnState' and local 'VncState' exchange
data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.
In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library
opaque data. The 'VncState' used in 'zrle_compress_data' is the local
'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz
library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection
'VncState'. In currently implementation there will be a memory leak when the
vnc disconnect. Following is the asan output backtrack:
Direct leak of 29760 byte(s) in 5 object(s) allocated from:
0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)
1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)
2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)
3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87
4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344
5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919
6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271
7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340
8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502
9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)
10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)
This is because the opaque allocated in 'deflateInit2' is not freed in
'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'
and in the latter will check whether 's->strm != strm'(libz's data structure).
This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and
not free the data allocated in 'deflateInit2'.
The reason this happens is that the 'VncState' contains the whole 'VncZrle',
so when calling 'deflateInit2', the 's->strm' will be the local address.
So 's->strm != strm' will be true.
To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.
Then the connection 'VncState' and local 'VncState' exchange mechanism will
work as expection. The 'tight' of 'VncState' has the same issue, let's also turn
it to a pointer.
Reported-by: Ying Fang <fangying1@huawei.com>
Signed-off-by: Li Qiang <liq3ea@163.com>
Message-id: 20190831153922.121308-1-liq3ea@163.com
Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
| null | null | null |
@Override
public void onResult (TdApi.Object object) {
switch (object.getConstructor()) {
case TdApi.WebPageInstantView.CONSTRUCTOR: {
final TdApi.WebPageInstantView instantView = (TdApi.WebPageInstantView) object;
tdlib.ui().post(() -> {
if (!isDestroyed()) {
if (!TD.hasInstantView(instantView.version)) {
UI.showToast(R.string.InstantViewUnsupported, Toast.LENGTH_SHORT);
UI.openUrl(getUrl());
} else {
getArgumentsStrict().instantView = instantView;
buildCells(true);
}
}
});
break;
}
case TdApi.Error.CONSTRUCTOR: {
UI.showError(object);
break;
}
default: {
Log.unexpectedTdlibResponse(object, TdApi.GetWebPageInstantView.class, TdApi.WebPageInstantView.class);
break;
}
}
}
|
@Override
public void onResult (TdApi.Object object) {
switch (object.getConstructor()) {
case TdApi.WebPageInstantView.CONSTRUCTOR: {
final TdApi.WebPageInstantView instantView = (TdApi.WebPageInstantView) object;
tdlib.ui().post(() -> {
if (!isDestroyed()) {
if (!TD.hasInstantView(instantView.version)) {
UI.showToast(R.string.InstantViewUnsupported, Toast.LENGTH_SHORT);
UI.openUrl(getUrl());
} else {
ArrayList<PageBlock> pageBlocks;
try {
pageBlocks = parsePageBlocks(instantView);
} catch (PageBlock.UnsupportedPageBlockException ignored) {
return;
}
getArgumentsStrict().instantView = instantView;
buildCells(pageBlocks, true);
}
}
});
break;
}
case TdApi.Error.CONSTRUCTOR: {
UI.showError(object);
break;
}
default: {
Log.unexpectedTdlibResponse(object, TdApi.GetWebPageInstantView.class, TdApi.WebPageInstantView.class);
break;
}
}
}
| null | null | null |
https://github.com/TGX-Android/Telegram-X/commit/8ad3464d3251418552c1df418089128b3d5c91e4
|
Fixed crash when unsupported `PageBlock` is returned in `GetWebPageInstantView` only with `forceFull == true`
|
app/src/main/java/org/thunderdog/challegram/ui/InstantViewController.java
|
java
|
2022-10-24T21:06:46Z
|
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentAppListBinding.inflate(getLayoutInflater(), container, false);
binding.appBar.setRaised(true);
String title;
if (module.userId != 0) {
title = String.format(Locale.US, "%s (%d)", module.getAppName(), module.userId);
} else {
title = module.getAppName();
}
binding.toolbar.setSubtitle(module.packageName);
scopeAdapter = new ScopeAdapter(this, module);
scopeAdapter.setHasStableIds(true);
binding.recyclerView.setAdapter(scopeAdapter);
binding.recyclerView.setHasFixedSize(true);
binding.recyclerView.setLayoutManager(new LinearLayoutManagerFix(requireActivity()));
RecyclerViewKt.addFastScroller(binding.recyclerView, binding.recyclerView);
RecyclerViewKt.fixEdgeEffect(binding.recyclerView, false, true);
binding.swipeRefreshLayout.setOnRefreshListener(() -> scopeAdapter.refresh(true));
searchListener = scopeAdapter.getSearchListener();
setupToolbar(binding.toolbar, title, R.menu.menu_app_list, view -> requireActivity().getOnBackPressedDispatcher().onBackPressed());
return binding.getRoot();
}
|
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentAppListBinding.inflate(getLayoutInflater(), container, false);
if (module == null) {
return binding.getRoot();
}
binding.appBar.setRaised(true);
String title;
if (module.userId != 0) {
title = String.format(Locale.US, "%s (%d)", module.getAppName(), module.userId);
} else {
title = module.getAppName();
}
binding.toolbar.setSubtitle(module.packageName);
scopeAdapter = new ScopeAdapter(this, module);
scopeAdapter.setHasStableIds(true);
binding.recyclerView.setAdapter(scopeAdapter);
binding.recyclerView.setHasFixedSize(true);
binding.recyclerView.setLayoutManager(new LinearLayoutManagerFix(requireActivity()));
RecyclerViewKt.addFastScroller(binding.recyclerView, binding.recyclerView);
RecyclerViewKt.fixEdgeEffect(binding.recyclerView, false, true);
binding.swipeRefreshLayout.setOnRefreshListener(() -> scopeAdapter.refresh(true));
searchListener = scopeAdapter.getSearchListener();
setupToolbar(binding.toolbar, title, R.menu.menu_app_list, view -> requireActivity().getOnBackPressedDispatcher().onBackPressed());
return binding.getRoot();
}
| null | null | null |
https://github.com/mywalkb/LSPosed_mod/commit/31e4254681aabcbce314bb03c2c802f9085a067f
|
[app] Fix crash when module not found (#744)
|
app/src/main/java/org/lsposed/manager/ui/fragment/AppListFragment.java
|
java
|
2021-06-11T15:37:14Z
|
static void vnc_dpy_setdata(DisplayChangeListener *dcl,
DisplayState *ds)
{
VncDisplay *vd = ds->opaque;
qemu_pixman_image_unref(vd->guest.fb);
vd->guest.fb = pixman_image_ref(ds->surface->image);
vd->guest.format = ds->surface->format;
vnc_dpy_update(dcl, ds, 0, 0, ds_get_width(ds), ds_get_height(ds));
}
|
static void vnc_dpy_setdata(DisplayChangeListener *dcl,
DisplayState *ds)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
qemu_pixman_image_unref(vd->guest.fb);
vd->guest.fb = pixman_image_ref(ds->surface->image);
vd->guest.format = ds->surface->format;
vnc_dpy_update(dcl, ds, 0, 0, ds_get_width(ds), ds_get_height(ds));
}
| null | null | null |
qemu/commit/21ef45d71221b4577330fe3aacfb06afad91ad46
|
console: kill DisplayState->opaque
It's broken by design. There can be multiple DisplayChangeListener
instances, so they simply can't store state in the (single) DisplayState
struct. Try 'qemu -display gtk -vnc :0', watch it crash & burn.
With DisplayChangeListenerOps having a more sane interface now we can
simply use the DisplayChangeListener pointer to get access to our
private data instead.
Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
|
./qemu/ui/vnc.c
|
c
|
2013-02-28T10:34:31Z
|
void SoftAACEncoder2::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (!mSentCodecSpecificData) {
if (outQueue.empty()) {
return;
}
if (AACENC_OK != aacEncEncode(mAACEncoder, NULL, NULL, NULL, NULL)) {
ALOGE("Unable to initialize encoder for profile / sample-rate / bit-rate / channels");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
OMX_U32 actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE);
if (mBitRate != actualBitRate) {
ALOGW("Requested bitrate %u unsupported, using %u", mBitRate, actualBitRate);
}
AACENC_InfoStruct encInfo;
if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) {
ALOGE("Failed to get AAC encoder info");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFilledLen = encInfo.confSize;
outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG;
uint8_t *out = outHeader->pBuffer + outHeader->nOffset;
memcpy(out, encInfo.confBuf, encInfo.confSize);
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mSentCodecSpecificData = true;
}
size_t numBytesPerInputFrame =
mNumChannels * kNumSamplesPerFrame * sizeof(int16_t);
if (mAACProfile == OMX_AUDIO_AACObjectELD && numBytesPerInputFrame > 512) {
numBytesPerInputFrame = 512;
}
for (;;) {
while (mInputSize < numBytesPerInputFrame) {
if (mSawInputEOS || inQueue.empty()) {
return;
}
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
const void *inData = inHeader->pBuffer + inHeader->nOffset;
size_t copy = numBytesPerInputFrame - mInputSize;
if (copy > inHeader->nFilledLen) {
copy = inHeader->nFilledLen;
}
if (mInputFrame == NULL) {
mInputFrame = new int16_t[numBytesPerInputFrame / sizeof(int16_t)];
}
if (mInputSize == 0) {
mInputTimeUs = inHeader->nTimeStamp;
}
memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy);
mInputSize += copy;
inHeader->nOffset += copy;
inHeader->nFilledLen -= copy;
inHeader->nTimeStamp +=
(copy * 1000000ll / mSampleRate)
/ (mNumChannels * sizeof(int16_t));
if (inHeader->nFilledLen == 0) {
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEOS = true;
memset((uint8_t *)mInputFrame + mInputSize,
0,
numBytesPerInputFrame - mInputSize);
mInputSize = numBytesPerInputFrame;
}
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
inData = NULL;
inHeader = NULL;
inInfo = NULL;
}
}
if (outQueue.empty()) {
return;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset;
size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset;
AACENC_InArgs inargs;
AACENC_OutArgs outargs;
memset(&inargs, 0, sizeof(inargs));
memset(&outargs, 0, sizeof(outargs));
inargs.numInSamples = numBytesPerInputFrame / sizeof(int16_t);
void* inBuffer[] = { (unsigned char *)mInputFrame };
INT inBufferIds[] = { IN_AUDIO_DATA };
INT inBufferSize[] = { (INT)numBytesPerInputFrame };
INT inBufferElSize[] = { sizeof(int16_t) };
AACENC_BufDesc inBufDesc;
inBufDesc.numBufs = sizeof(inBuffer) / sizeof(void*);
inBufDesc.bufs = (void**)&inBuffer;
inBufDesc.bufferIdentifiers = inBufferIds;
inBufDesc.bufSizes = inBufferSize;
inBufDesc.bufElSizes = inBufferElSize;
void* outBuffer[] = { outPtr };
INT outBufferIds[] = { OUT_BITSTREAM_DATA };
INT outBufferSize[] = { 0 };
INT outBufferElSize[] = { sizeof(UCHAR) };
AACENC_BufDesc outBufDesc;
outBufDesc.numBufs = sizeof(outBuffer) / sizeof(void*);
outBufDesc.bufs = (void**)&outBuffer;
outBufDesc.bufferIdentifiers = outBufferIds;
outBufDesc.bufSizes = outBufferSize;
outBufDesc.bufElSizes = outBufferElSize;
AACENC_ERROR encoderErr = AACENC_OK;
size_t nOutputBytes = 0;
do {
memset(&outargs, 0, sizeof(outargs));
outBuffer[0] = outPtr;
outBufferSize[0] = outAvailable - nOutputBytes;
encoderErr = aacEncEncode(mAACEncoder,
&inBufDesc,
&outBufDesc,
&inargs,
&outargs);
if (encoderErr == AACENC_OK) {
outPtr += outargs.numOutBytes;
nOutputBytes += outargs.numOutBytes;
if (outargs.numInSamples > 0) {
int numRemainingSamples = inargs.numInSamples - outargs.numInSamples;
if (numRemainingSamples > 0) {
memmove(mInputFrame,
&mInputFrame[outargs.numInSamples],
sizeof(int16_t) * numRemainingSamples);
}
inargs.numInSamples -= outargs.numInSamples;
}
}
} while (encoderErr == AACENC_OK && inargs.numInSamples > 0);
outHeader->nFilledLen = nOutputBytes;
outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
if (mSawInputEOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
}
outHeader->nTimeStamp = mInputTimeUs;
#if 0
ALOGI("sending %d bytes of data (time = %lld us, flags = 0x%08lx)",
nOutputBytes, mInputTimeUs, outHeader->nFlags);
hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen);
#endif
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
outHeader = NULL;
outInfo = NULL;
mInputSize = 0;
}
}
|
void SoftAACEncoder2::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (!mSentCodecSpecificData) {
if (outQueue.empty()) {
return;
}
if (AACENC_OK != aacEncEncode(mAACEncoder, NULL, NULL, NULL, NULL)) {
ALOGE("Unable to initialize encoder for profile / sample-rate / bit-rate / channels");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
OMX_U32 actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE);
if (mBitRate != actualBitRate) {
ALOGW("Requested bitrate %u unsupported, using %u", mBitRate, actualBitRate);
}
AACENC_InfoStruct encInfo;
if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) {
ALOGE("Failed to get AAC encoder info");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (outHeader->nOffset + encInfo.confSize > outHeader->nAllocLen) {
ALOGE("b/34617444");
android_errorWriteLog(0x534e4554,"34617444");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
outHeader->nFilledLen = encInfo.confSize;
outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG;
uint8_t *out = outHeader->pBuffer + outHeader->nOffset;
memcpy(out, encInfo.confBuf, encInfo.confSize);
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mSentCodecSpecificData = true;
}
size_t numBytesPerInputFrame =
mNumChannels * kNumSamplesPerFrame * sizeof(int16_t);
if (mAACProfile == OMX_AUDIO_AACObjectELD && numBytesPerInputFrame > 512) {
numBytesPerInputFrame = 512;
}
for (;;) {
while (mInputSize < numBytesPerInputFrame) {
if (mSawInputEOS || inQueue.empty()) {
return;
}
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
const void *inData = inHeader->pBuffer + inHeader->nOffset;
size_t copy = numBytesPerInputFrame - mInputSize;
if (copy > inHeader->nFilledLen) {
copy = inHeader->nFilledLen;
}
if (mInputFrame == NULL) {
mInputFrame = new int16_t[numBytesPerInputFrame / sizeof(int16_t)];
}
if (mInputSize == 0) {
mInputTimeUs = inHeader->nTimeStamp;
}
memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy);
mInputSize += copy;
inHeader->nOffset += copy;
inHeader->nFilledLen -= copy;
inHeader->nTimeStamp +=
(copy * 1000000ll / mSampleRate)
/ (mNumChannels * sizeof(int16_t));
if (inHeader->nFilledLen == 0) {
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEOS = true;
memset((uint8_t *)mInputFrame + mInputSize,
0,
numBytesPerInputFrame - mInputSize);
mInputSize = numBytesPerInputFrame;
}
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
inData = NULL;
inHeader = NULL;
inInfo = NULL;
}
}
if (outQueue.empty()) {
return;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset;
size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset;
AACENC_InArgs inargs;
AACENC_OutArgs outargs;
memset(&inargs, 0, sizeof(inargs));
memset(&outargs, 0, sizeof(outargs));
inargs.numInSamples = numBytesPerInputFrame / sizeof(int16_t);
void* inBuffer[] = { (unsigned char *)mInputFrame };
INT inBufferIds[] = { IN_AUDIO_DATA };
INT inBufferSize[] = { (INT)numBytesPerInputFrame };
INT inBufferElSize[] = { sizeof(int16_t) };
AACENC_BufDesc inBufDesc;
inBufDesc.numBufs = sizeof(inBuffer) / sizeof(void*);
inBufDesc.bufs = (void**)&inBuffer;
inBufDesc.bufferIdentifiers = inBufferIds;
inBufDesc.bufSizes = inBufferSize;
inBufDesc.bufElSizes = inBufferElSize;
void* outBuffer[] = { outPtr };
INT outBufferIds[] = { OUT_BITSTREAM_DATA };
INT outBufferSize[] = { 0 };
INT outBufferElSize[] = { sizeof(UCHAR) };
AACENC_BufDesc outBufDesc;
outBufDesc.numBufs = sizeof(outBuffer) / sizeof(void*);
outBufDesc.bufs = (void**)&outBuffer;
outBufDesc.bufferIdentifiers = outBufferIds;
outBufDesc.bufSizes = outBufferSize;
outBufDesc.bufElSizes = outBufferElSize;
AACENC_ERROR encoderErr = AACENC_OK;
size_t nOutputBytes = 0;
do {
memset(&outargs, 0, sizeof(outargs));
outBuffer[0] = outPtr;
outBufferSize[0] = outAvailable - nOutputBytes;
encoderErr = aacEncEncode(mAACEncoder,
&inBufDesc,
&outBufDesc,
&inargs,
&outargs);
if (encoderErr == AACENC_OK) {
outPtr += outargs.numOutBytes;
nOutputBytes += outargs.numOutBytes;
if (outargs.numInSamples > 0) {
int numRemainingSamples = inargs.numInSamples - outargs.numInSamples;
if (numRemainingSamples > 0) {
memmove(mInputFrame,
&mInputFrame[outargs.numInSamples],
sizeof(int16_t) * numRemainingSamples);
}
inargs.numInSamples -= outargs.numInSamples;
}
}
} while (encoderErr == AACENC_OK && inargs.numInSamples > 0);
outHeader->nFilledLen = nOutputBytes;
outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
if (mSawInputEOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
}
outHeader->nTimeStamp = mInputTimeUs;
#if 0
ALOGI("sending %d bytes of data (time = %lld us, flags = 0x%08lx)",
nOutputBytes, mInputTimeUs, outHeader->nFlags);
hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen);
#endif
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
outHeader = NULL;
outInfo = NULL;
mInputSize = 0;
}
}
|
CVE-2017-0594
|
CWE-120
|
An elevation of privilege vulnerability in codecs/aacenc/SoftAACEncoder2.cpp in libstagefright in Mediaserver could enable a local malicious application to execute arbitrary code within the context of a privileged process. This issue is rated as High because it could be used to gain local access to elevated capabilities, which are not normally accessible to a third-party application. Product: Android. Versions: 4.4.4, 5.0.2, 5.1.1, 6.0, 6.0.1, 7.0, 7.1.1, 7.1.2. Android ID: A-34617444.
|
https://android.googlesource.com/platform/frameworks/av/+/594bf934384920618d2b6ce0bcda1f60144cb3eb
|
Add bounds check in SoftAACEncoder2::onQueueFilled()
Original code blindly copied some header information into the
user-supplied buffer without checking for sufficient space.
The code does check when it gets to filling the data -- it's
just the header copies that weren't checked.
Bug: 34617444
Test: ran POC before/after
Change-Id: I6e80ec90616f6cd02bb8316cd2d6e309b7e4729d
(cherry picked from commit 6231243626b8b9c57593b1f0ee417f2c4af4c0aa)
|
media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp
|
cpp
| null |
static int iec61883_read_header(AVFormatContext *context)
{
struct iec61883_data *dv = context->priv_data;
struct raw1394_portinfo pinf[16];
rom1394_directory rom_dir;
char *endptr;
int inport;
int nb_ports;
int port = -1;
int response;
int i, j = 0;
uint64_t guid = 0;
dv->input_port = -1;
dv->output_port = -1;
dv->channel = -1;
dv->raw1394 = raw1394_new_handle();
if (!dv->raw1394) {
av_log(context, AV_LOG_ERROR, "Failed to open IEEE1394 interface.\n");
return AVERROR(EIO);
}
if ((nb_ports = raw1394_get_port_info(dv->raw1394, pinf, 16)) < 0) {
av_log(context, AV_LOG_ERROR, "Failed to get number of IEEE1394 ports.\n");
goto fail;
}
inport = strtol(context->filename, &endptr, 10);
if (endptr != context->filename && *endptr == '\0') {
av_log(context, AV_LOG_INFO, "Selecting IEEE1394 port: %d\n", inport);
j = inport;
nb_ports = inport + 1;
} else if (strcmp(context->filename, "auto")) {
av_log(context, AV_LOG_ERROR, "Invalid input \"%s\", you should specify "
"\"auto\" for auto-detection, or the port number.\n", context->filename);
goto fail;
}
if (dv->device_guid) {
if (sscanf(dv->device_guid, "%llx", (long long unsigned int *)&guid) != 1) {
av_log(context, AV_LOG_INFO, "Invalid dvguid parameter: %s\n",
dv->device_guid);
goto fail;
}
}
for (; j < nb_ports && port==-1; ++j) {
raw1394_destroy_handle(dv->raw1394);
if (!(dv->raw1394 = raw1394_new_handle_on_port(j))) {
av_log(context, AV_LOG_ERROR, "Failed setting IEEE1394 port.\n");
goto fail;
}
for (i=0; i<raw1394_get_nodecount(dv->raw1394); ++i) {
if (guid > 1) {
if (guid == rom1394_get_guid(dv->raw1394, i)) {
dv->node = i;
port = j;
break;
}
} else {
if (rom1394_get_directory(dv->raw1394, i, &rom_dir) < 0)
continue;
if (((rom1394_get_node_type(&rom_dir) == ROM1394_NODE_TYPE_AVC) &&
avc1394_check_subunit_type(dv->raw1394, i, AVC1394_SUBUNIT_TYPE_VCR)) ||
(rom_dir.unit_spec_id == MOTDCT_SPEC_ID)) {
rom1394_free_directory(&rom_dir);
dv->node = i;
port = j;
break;
}
rom1394_free_directory(&rom_dir);
}
}
}
if (port == -1) {
av_log(context, AV_LOG_ERROR, "No AV/C devices found.\n");
goto fail;
}
iec61883_cmp_normalize_output(dv->raw1394, 0xffc0 | dv->node);
if (dv->type == IEC61883_AUTO) {
response = avc1394_transaction(dv->raw1394, dv->node,
AVC1394_CTYPE_STATUS |
AVC1394_SUBUNIT_TYPE_TAPE_RECORDER |
AVC1394_SUBUNIT_ID_0 |
AVC1394_VCR_COMMAND_OUTPUT_SIGNAL_MODE |
0xFF, 2);
response = AVC1394_GET_OPERAND0(response);
dv->type = (response == 0x10 || response == 0x90 || response == 0x1A || response == 0x9A) ?
IEC61883_HDV : IEC61883_DV;
}
dv->channel = iec61883_cmp_connect(dv->raw1394, dv->node, &dv->output_port,
raw1394_get_local_id(dv->raw1394),
&dv->input_port, &dv->bandwidth);
if (dv->channel < 0)
dv->channel = 63;
if (!dv->max_packets)
dv->max_packets = 100;
if (CONFIG_MPEGTS_DEMUXER && dv->type == IEC61883_HDV) {
avformat_new_stream(context, NULL);
dv->mpeg_demux = avpriv_mpegts_parse_open(context);
if (!dv->mpeg_demux)
goto fail;
dv->parse_queue = iec61883_parse_queue_hdv;
dv->iec61883_mpeg2 = iec61883_mpeg2_recv_init(dv->raw1394,
(iec61883_mpeg2_recv_t)iec61883_callback,
dv);
dv->max_packets *= 766;
} else {
dv->dv_demux = avpriv_dv_init_demux(context);
if (!dv->dv_demux)
goto fail;
dv->parse_queue = iec61883_parse_queue_dv;
dv->iec61883_dv = iec61883_dv_fb_init(dv->raw1394, iec61883_callback, dv);
}
dv->raw1394_poll.fd = raw1394_get_fd(dv->raw1394);
dv->raw1394_poll.events = POLLIN | POLLERR | POLLHUP | POLLPRI;
if (dv->type == IEC61883_HDV)
iec61883_mpeg2_recv_start(dv->iec61883_mpeg2, dv->channel);
else
iec61883_dv_fb_start(dv->iec61883_dv, dv->channel);
#if THREADS
dv->thread_loop = 1;
pthread_mutex_init(&dv->mutex, NULL);
pthread_cond_init(&dv->cond, NULL);
pthread_create(&dv->receive_task_thread, NULL, iec61883_receive_task, dv);
#endif
return 0;
fail:
raw1394_destroy_handle(dv->raw1394);
return AVERROR(EIO);
}
|
static int iec61883_read_header(AVFormatContext *context)
{
struct iec61883_data *dv = context->priv_data;
struct raw1394_portinfo pinf[16];
rom1394_directory rom_dir;
char *endptr;
int inport;
int nb_ports;
int port = -1;
int response;
int i, j = 0;
uint64_t guid = 0;
dv->input_port = -1;
dv->output_port = -1;
dv->channel = -1;
dv->raw1394 = raw1394_new_handle();
if (!dv->raw1394) {
av_log(context, AV_LOG_ERROR, "Failed to open IEEE1394 interface.\n");
return AVERROR(EIO);
}
if ((nb_ports = raw1394_get_port_info(dv->raw1394, pinf, 16)) < 0) {
av_log(context, AV_LOG_ERROR, "Failed to get number of IEEE1394 ports.\n");
goto fail;
}
inport = strtol(context->filename, &endptr, 10);
if (endptr != context->filename && *endptr == '\0') {
av_log(context, AV_LOG_INFO, "Selecting IEEE1394 port: %d\n", inport);
j = inport;
nb_ports = inport + 1;
} else if (strcmp(context->filename, "auto")) {
av_log(context, AV_LOG_ERROR, "Invalid input \"%s\", you should specify "
"\"auto\" for auto-detection, or the port number.\n", context->filename);
goto fail;
}
if (dv->device_guid) {
if (sscanf(dv->device_guid, "%llx", (long long unsigned int *)&guid) != 1) {
av_log(context, AV_LOG_INFO, "Invalid dvguid parameter: %s\n",
dv->device_guid);
goto fail;
}
}
for (; j < nb_ports && port==-1; ++j) {
raw1394_destroy_handle(dv->raw1394);
if (!(dv->raw1394 = raw1394_new_handle_on_port(j))) {
av_log(context, AV_LOG_ERROR, "Failed setting IEEE1394 port.\n");
goto fail;
}
for (i=0; i<raw1394_get_nodecount(dv->raw1394); ++i) {
if (guid > 1) {
if (guid == rom1394_get_guid(dv->raw1394, i)) {
dv->node = i;
port = j;
break;
}
} else {
if (rom1394_get_directory(dv->raw1394, i, &rom_dir) < 0)
continue;
if (((rom1394_get_node_type(&rom_dir) == ROM1394_NODE_TYPE_AVC) &&
avc1394_check_subunit_type(dv->raw1394, i, AVC1394_SUBUNIT_TYPE_VCR)) ||
(rom_dir.unit_spec_id == MOTDCT_SPEC_ID)) {
rom1394_free_directory(&rom_dir);
dv->node = i;
port = j;
break;
}
rom1394_free_directory(&rom_dir);
}
}
}
if (port == -1) {
av_log(context, AV_LOG_ERROR, "No AV/C devices found.\n");
goto fail;
}
iec61883_cmp_normalize_output(dv->raw1394, 0xffc0 | dv->node);
if (dv->type == IEC61883_AUTO) {
response = avc1394_transaction(dv->raw1394, dv->node,
AVC1394_CTYPE_STATUS |
AVC1394_SUBUNIT_TYPE_TAPE_RECORDER |
AVC1394_SUBUNIT_ID_0 |
AVC1394_VCR_COMMAND_OUTPUT_SIGNAL_MODE |
0xFF, 2);
response = AVC1394_GET_OPERAND0(response);
dv->type = (response == 0x10 || response == 0x90 || response == 0x1A || response == 0x9A) ?
IEC61883_HDV : IEC61883_DV;
}
dv->channel = iec61883_cmp_connect(dv->raw1394, dv->node, &dv->output_port,
raw1394_get_local_id(dv->raw1394),
&dv->input_port, &dv->bandwidth);
if (dv->channel < 0)
dv->channel = 63;
if (!dv->max_packets)
dv->max_packets = 100;
if (CONFIG_MPEGTS_DEMUXER && dv->type == IEC61883_HDV) {
avformat_new_stream(context, NULL);
dv->mpeg_demux = avpriv_mpegts_parse_open(context);
if (!dv->mpeg_demux)
goto fail;
dv->parse_queue = iec61883_parse_queue_hdv;
dv->iec61883_mpeg2 = iec61883_mpeg2_recv_init(dv->raw1394,
(iec61883_mpeg2_recv_t)iec61883_callback,
dv);
dv->max_packets *= 766;
} else {
dv->dv_demux = avpriv_dv_init_demux(context);
if (!dv->dv_demux)
goto fail;
dv->parse_queue = iec61883_parse_queue_dv;
dv->iec61883_dv = iec61883_dv_fb_init(dv->raw1394, iec61883_callback, dv);
}
dv->raw1394_poll.fd = raw1394_get_fd(dv->raw1394);
dv->raw1394_poll.events = POLLIN | POLLERR | POLLHUP | POLLPRI;
if (dv->type == IEC61883_HDV)
iec61883_mpeg2_recv_start(dv->iec61883_mpeg2, dv->channel);
else
iec61883_dv_fb_start(dv->iec61883_dv, dv->channel);
#if THREADS
dv->thread_loop = 1;
if (pthread_mutex_init(&dv->mutex, NULL))
goto fail;
if (pthread_cond_init(&dv->cond, NULL))
goto fail;
if (pthread_create(&dv->receive_task_thread, NULL, iec61883_receive_task, dv))
goto fail;
#endif
return 0;
fail:
raw1394_destroy_handle(dv->raw1394);
return AVERROR(EIO);
}
| null | null | null |
FFmpeg/commit/7c453277a399bc81553c6110efd81a0957117138
|
avdevice/iec61883: Check pthread init for failures
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
|
./ffmpeg/libavdevice/iec61883.c
|
c
|
2015-06-07T16:57:55Z
|
dfaanalyze (struct dfa *d, int searchflag)
{
int *nullable; /* Nullable stack. */
int *nfirstpos; /* Element count stack for firstpos sets. */
position *firstpos; /* Array where firstpos elements are stored. */
int *nlastpos; /* Element count stack for lastpos sets. */
position *lastpos; /* Array where lastpos elements are stored. */
position_set tmp; /* Temporary set for merging sets. */
position_set merged; /* Result of merging sets. */
int separate_contexts; /* Context wanted by some position. */
int *o_nullable;
int *o_nfirst, *o_nlast;
position *o_firstpos, *o_lastpos;
int i, j;
position *pos;
#ifdef DEBUG
fprintf(stderr, "dfaanalyze:\n");
for (i = 0; i < d->tindex; ++i)
{
fprintf(stderr, " %d:", i);
prtok(d->tokens[i]);
}
putc('\n', stderr);
#endif
d->searchflag = searchflag;
MALLOC(nullable, d->depth);
o_nullable = nullable;
MALLOC(nfirstpos, d->depth);
o_nfirst = nfirstpos;
MALLOC(firstpos, d->nleaves);
o_firstpos = firstpos, firstpos += d->nleaves;
MALLOC(nlastpos, d->depth);
o_nlast = nlastpos;
MALLOC(lastpos, d->nleaves);
o_lastpos = lastpos, lastpos += d->nleaves;
alloc_position_set(&merged, d->nleaves);
CALLOC(d->follows, d->tindex);
for (i = 0; i < d->tindex; ++i)
{
switch (d->tokens[i])
{
case EMPTY:
/* The empty set is nullable. */
*nullable++ = 1;
/* The firstpos and lastpos of the empty leaf are both empty. */
*nfirstpos++ = *nlastpos++ = 0;
break;
case STAR:
case PLUS:
/* Every element in the firstpos of the argument is in the follow
of every element in the lastpos. */
tmp.nelem = nfirstpos[-1];
tmp.elems = firstpos;
pos = lastpos;
for (j = 0; j < nlastpos[-1]; ++j)
{
merge(&tmp, &d->follows[pos[j].index], &merged);
copy(&merged, &d->follows[pos[j].index]);
}
case QMARK:
/* A QMARK or STAR node is automatically nullable. */
if (d->tokens[i] != PLUS)
nullable[-1] = 1;
break;
case CAT:
/* Every element in the firstpos of the second argument is in the
follow of every element in the lastpos of the first argument. */
tmp.nelem = nfirstpos[-1];
tmp.elems = firstpos;
pos = lastpos + nlastpos[-1];
for (j = 0; j < nlastpos[-2]; ++j)
{
merge(&tmp, &d->follows[pos[j].index], &merged);
copy(&merged, &d->follows[pos[j].index]);
}
/* The firstpos of a CAT node is the firstpos of the first argument,
union that of the second argument if the first is nullable. */
if (nullable[-2])
nfirstpos[-2] += nfirstpos[-1];
else
firstpos += nfirstpos[-1];
--nfirstpos;
/* The lastpos of a CAT node is the lastpos of the second argument,
union that of the first argument if the second is nullable. */
if (nullable[-1])
nlastpos[-2] += nlastpos[-1];
else
{
pos = lastpos + nlastpos[-2];
for (j = nlastpos[-1] - 1; j >= 0; --j)
pos[j] = lastpos[j];
lastpos += nlastpos[-2];
nlastpos[-2] = nlastpos[-1];
}
--nlastpos;
/* A CAT node is nullable if both arguments are nullable. */
nullable[-2] = nullable[-1] && nullable[-2];
--nullable;
break;
case OR:
/* The firstpos is the union of the firstpos of each argument. */
nfirstpos[-2] += nfirstpos[-1];
--nfirstpos;
/* The lastpos is the union of the lastpos of each argument. */
nlastpos[-2] += nlastpos[-1];
--nlastpos;
/* An OR node is nullable if either argument is nullable. */
nullable[-2] = nullable[-1] || nullable[-2];
--nullable;
break;
default:
/* Anything else is a nonempty position. (Note that special
constructs like \< are treated as nonempty strings here;
an "epsilon closure" effectively makes them nullable later.
Backreferences have to get a real position so we can detect
transitions on them later. But they are nullable. */
*nullable++ = d->tokens[i] == BACKREF;
/* This position is in its own firstpos and lastpos. */
*nfirstpos++ = *nlastpos++ = 1;
--firstpos, --lastpos;
firstpos->index = lastpos->index = i;
firstpos->constraint = lastpos->constraint = NO_CONSTRAINT;
/* Allocate the follow set for this position. */
alloc_position_set(&d->follows[i], 1);
break;
}
#ifdef DEBUG
/* ... balance the above nonsyntactic #ifdef goo... */
fprintf(stderr, "node %d:", i);
prtok(d->tokens[i]);
putc('\n', stderr);
fprintf(stderr, nullable[-1] ? " nullable: yes\n" : " nullable: no\n");
fprintf(stderr, " firstpos:");
for (j = nfirstpos[-1] - 1; j >= 0; --j)
{
fprintf(stderr, " %d:", firstpos[j].index);
prtok(d->tokens[firstpos[j].index]);
}
fprintf(stderr, "\n lastpos:");
for (j = nlastpos[-1] - 1; j >= 0; --j)
{
fprintf(stderr, " %d:", lastpos[j].index);
prtok(d->tokens[lastpos[j].index]);
}
putc('\n', stderr);
#endif
}
/* For each follow set that is the follow set of a real position, replace
it with its epsilon closure. */
for (i = 0; i < d->tindex; ++i)
if (d->tokens[i] < NOTCHAR || d->tokens[i] == BACKREF
#if MBS_SUPPORT
|| d->tokens[i] == ANYCHAR
|| d->tokens[i] == MBCSET
#endif
|| d->tokens[i] >= CSET)
{
#ifdef DEBUG
fprintf(stderr, "follows(%d:", i);
prtok(d->tokens[i]);
fprintf(stderr, "):");
for (j = d->follows[i].nelem - 1; j >= 0; --j)
{
fprintf(stderr, " %d:", d->follows[i].elems[j].index);
prtok(d->tokens[d->follows[i].elems[j].index]);
}
putc('\n', stderr);
#endif
copy(&d->follows[i], &merged);
epsclosure(&merged, d);
copy(&merged, &d->follows[i]);
}
/* Get the epsilon closure of the firstpos of the regexp. The result will
be the set of positions of state 0. */
merged.nelem = 0;
for (i = 0; i < nfirstpos[-1]; ++i)
insert(firstpos[i], &merged);
epsclosure(&merged, d);
/* Build the initial state. */
d->salloc = 1;
d->sindex = 0;
MALLOC(d->states, d->salloc);
separate_contexts = state_separate_contexts (&merged);
state_index(d, &merged,
(separate_contexts & CTX_NEWLINE
? CTX_NEWLINE
: separate_contexts ^ CTX_ANY));
free(o_nullable);
free(o_nfirst);
free(o_firstpos);
free(o_nlast);
free(o_lastpos);
free(merged.elems);
}
|
dfaanalyze (struct dfa *d, int searchflag)
{
int *nullable; /* Nullable stack. */
size_t *nfirstpos; /* Element count stack for firstpos sets. */
position *firstpos; /* Array where firstpos elements are stored. */
size_t *nlastpos; /* Element count stack for lastpos sets. */
position *lastpos; /* Array where lastpos elements are stored. */
position_set tmp; /* Temporary set for merging sets. */
position_set merged; /* Result of merging sets. */
int separate_contexts; /* Context wanted by some position. */
int *o_nullable;
size_t *o_nfirst, *o_nlast;
position *o_firstpos, *o_lastpos;
size_t i, j;
position *pos;
#ifdef DEBUG
fprintf(stderr, "dfaanalyze:\n");
for (i = 0; i < d->tindex; ++i)
{
fprintf(stderr, " %zd:", i);
prtok(d->tokens[i]);
}
putc('\n', stderr);
#endif
d->searchflag = searchflag;
MALLOC(nullable, d->depth);
o_nullable = nullable;
MALLOC(nfirstpos, d->depth);
o_nfirst = nfirstpos;
MALLOC(firstpos, d->nleaves);
o_firstpos = firstpos, firstpos += d->nleaves;
MALLOC(nlastpos, d->depth);
o_nlast = nlastpos;
MALLOC(lastpos, d->nleaves);
o_lastpos = lastpos, lastpos += d->nleaves;
alloc_position_set(&merged, d->nleaves);
CALLOC(d->follows, d->tindex);
for (i = 0; i < d->tindex; ++i)
{
switch (d->tokens[i])
{
case EMPTY:
/* The empty set is nullable. */
*nullable++ = 1;
/* The firstpos and lastpos of the empty leaf are both empty. */
*nfirstpos++ = *nlastpos++ = 0;
break;
case STAR:
case PLUS:
/* Every element in the firstpos of the argument is in the follow
of every element in the lastpos. */
tmp.nelem = nfirstpos[-1];
tmp.elems = firstpos;
pos = lastpos;
for (j = 0; j < nlastpos[-1]; ++j)
{
merge(&tmp, &d->follows[pos[j].index], &merged);
copy(&merged, &d->follows[pos[j].index]);
}
case QMARK:
/* A QMARK or STAR node is automatically nullable. */
if (d->tokens[i] != PLUS)
nullable[-1] = 1;
break;
case CAT:
/* Every element in the firstpos of the second argument is in the
follow of every element in the lastpos of the first argument. */
tmp.nelem = nfirstpos[-1];
tmp.elems = firstpos;
pos = lastpos + nlastpos[-1];
for (j = 0; j < nlastpos[-2]; ++j)
{
merge(&tmp, &d->follows[pos[j].index], &merged);
copy(&merged, &d->follows[pos[j].index]);
}
/* The firstpos of a CAT node is the firstpos of the first argument,
union that of the second argument if the first is nullable. */
if (nullable[-2])
nfirstpos[-2] += nfirstpos[-1];
else
firstpos += nfirstpos[-1];
--nfirstpos;
/* The lastpos of a CAT node is the lastpos of the second argument,
union that of the first argument if the second is nullable. */
if (nullable[-1])
nlastpos[-2] += nlastpos[-1];
else
{
pos = lastpos + nlastpos[-2];
for (j = nlastpos[-1]; j-- > 0; )
pos[j] = lastpos[j];
lastpos += nlastpos[-2];
nlastpos[-2] = nlastpos[-1];
}
--nlastpos;
/* A CAT node is nullable if both arguments are nullable. */
nullable[-2] = nullable[-1] && nullable[-2];
--nullable;
break;
case OR:
/* The firstpos is the union of the firstpos of each argument. */
nfirstpos[-2] += nfirstpos[-1];
--nfirstpos;
/* The lastpos is the union of the lastpos of each argument. */
nlastpos[-2] += nlastpos[-1];
--nlastpos;
/* An OR node is nullable if either argument is nullable. */
nullable[-2] = nullable[-1] || nullable[-2];
--nullable;
break;
default:
/* Anything else is a nonempty position. (Note that special
constructs like \< are treated as nonempty strings here;
an "epsilon closure" effectively makes them nullable later.
Backreferences have to get a real position so we can detect
transitions on them later. But they are nullable. */
*nullable++ = d->tokens[i] == BACKREF;
/* This position is in its own firstpos and lastpos. */
*nfirstpos++ = *nlastpos++ = 1;
--firstpos, --lastpos;
firstpos->index = lastpos->index = i;
firstpos->constraint = lastpos->constraint = NO_CONSTRAINT;
/* Allocate the follow set for this position. */
alloc_position_set(&d->follows[i], 1);
break;
}
#ifdef DEBUG
/* ... balance the above nonsyntactic #ifdef goo... */
fprintf(stderr, "node %zd:", i);
prtok(d->tokens[i]);
putc('\n', stderr);
fprintf(stderr, nullable[-1] ? " nullable: yes\n" : " nullable: no\n");
fprintf(stderr, " firstpos:");
for (j = nfirstpos[-1]; j-- > 0; )
{
fprintf(stderr, " %zd:", firstpos[j].index);
prtok(d->tokens[firstpos[j].index]);
}
fprintf(stderr, "\n lastpos:");
for (j = nlastpos[-1]; j-- > 0; )
{
fprintf(stderr, " %zd:", lastpos[j].index);
prtok(d->tokens[lastpos[j].index]);
}
putc('\n', stderr);
#endif
}
/* For each follow set that is the follow set of a real position, replace
it with its epsilon closure. */
for (i = 0; i < d->tindex; ++i)
if (d->tokens[i] < NOTCHAR || d->tokens[i] == BACKREF
#if MBS_SUPPORT
|| d->tokens[i] == ANYCHAR
|| d->tokens[i] == MBCSET
#endif
|| d->tokens[i] >= CSET)
{
#ifdef DEBUG
fprintf(stderr, "follows(%zd:", i);
prtok(d->tokens[i]);
fprintf(stderr, "):");
for (j = d->follows[i].nelem; j-- > 0; )
{
fprintf(stderr, " %zd:", d->follows[i].elems[j].index);
prtok(d->tokens[d->follows[i].elems[j].index]);
}
putc('\n', stderr);
#endif
copy(&d->follows[i], &merged);
epsclosure(&merged, d);
copy(&merged, &d->follows[i]);
}
/* Get the epsilon closure of the firstpos of the regexp. The result will
be the set of positions of state 0. */
merged.nelem = 0;
for (i = 0; i < nfirstpos[-1]; ++i)
insert(firstpos[i], &merged);
epsclosure(&merged, d);
/* Build the initial state. */
d->salloc = 1;
d->sindex = 0;
MALLOC(d->states, d->salloc);
separate_contexts = state_separate_contexts (&merged);
state_index(d, &merged,
(separate_contexts & CTX_NEWLINE
? CTX_NEWLINE
: separate_contexts ^ CTX_ANY));
free(o_nullable);
free(o_nfirst);
free(o_firstpos);
free(o_nlast);
free(o_lastpos);
free(merged.elems);
}
|
CVE-2012-5667
|
CWE-189
|
Multiple integer overflows in GNU Grep before 2.11 might allow context-dependent attackers to execute arbitrary code via vectors involving a long input line that triggers a heap-based buffer overflow.
|
http://git.savannah.gnu.org/cgit/grep.git/commit/?id=cbbc1a45b9f843c811905c97c90a5d31f8e6c189
|
grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.
| null | null | null |
private static String getCurrentWorldOrServerName() {
IntegratedServer integratedServer = client.getServer();
if (integratedServer != null) {
return integratedServer.getSaveProperties().getLevelName();
}
ServerInfo serverInfo = client.getCurrentServerEntry();
if (serverInfo != null) {
return serverInfo.address;
}
if (client.isConnectedToRealms()) {
return "realms";
}
return "unknown";
}
|
private static String getCurrentWorldOrServerName() {
IntegratedServer integratedServer = client.getServer();
if (integratedServer != null) {
return integratedServer.getSaveProperties().getLevelName();
}
ServerInfo serverInfo = client.getCurrentServerEntry();
if (serverInfo != null) {
return serverInfo.address.replace(':', '_');
}
if (client.isConnectedToRealms()) {
return "realms";
}
return "unknown";
}
| null | null | null |
https://github.com/Johni0702/bobby/commit/08acba7fc0ab36bab7cf5f3f18e36c17ccee35f7
|
Fix crash when connecting to server with port on Windows (fixes #5)
Turns out `:` is an invalid character for file names on Windows. Easy fix is to
just replace it with an underscore.
|
src/main/java/de/johni0702/minecraft/bobby/FakeChunkManager.java
|
java
|
2021-03-06T19:20:42Z
|
int ff_rv34_decode_init_thread_copy(AVCodecContext *avctx)
{
int err;
RV34DecContext *r = avctx->priv_data;
r->s.avctx = avctx;
if (avctx->internal->is_copy) {
r->tmp_b_block_base = NULL;
if ((err = ff_MPV_common_init(&r->s)) < 0)
return err;
if ((err = rv34_decoder_alloc(r)) < 0)
return err;
}
return 0;
}
|
int ff_rv34_decode_init_thread_copy(AVCodecContext *avctx)
{
int err;
RV34DecContext *r = avctx->priv_data;
r->s.avctx = avctx;
if (avctx->internal->is_copy) {
r->tmp_b_block_base = NULL;
if ((err = ff_MPV_common_init(&r->s)) < 0)
return err;
if ((err = rv34_decoder_alloc(r)) < 0) {
ff_MPV_common_end(&r->s);
return err;
}
}
return 0;
}
| null | null | null |
FFmpeg/commit/fdbd924b84e85ac5c80f01ee059ed5c81d3cc205
|
rv34: Fix a memory leak on errors
Signed-off-by: Martin Storsjö <martin@martin.st>
|
./ffmpeg/libavcodec/rv34.c
|
c
|
2013-09-16T13:05:18Z
|
error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM(
uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) {
GLuint count = c.count;
uint32 pnames_size;
if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) {
return error::kOutOfBounds;
}
const GLenum* pnames = GetSharedMemoryAs<const GLenum*>(
c.pnames_shm_id, c.pnames_shm_offset, pnames_size);
if (pnames == NULL) {
return error::kOutOfBounds;
}
scoped_array<GLenum> enums(new GLenum[count]);
memcpy(enums.get(), pnames, pnames_size);
uint32 num_results = 0;
for (GLuint ii = 0; ii < count; ++ii) {
uint32 num = util_.GLGetNumValuesReturned(enums[ii]);
if (num == 0) {
SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname");
return error::kNoError;
}
DCHECK_LE(num, 4u);
if (!SafeAdd(num_results, num, &num_results)) {
return error::kOutOfBounds;
}
}
uint32 result_size = 0;
if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) {
return error::kOutOfBounds;
}
if (result_size != static_cast<uint32>(c.size)) {
SetGLError(GL_INVALID_VALUE,
"glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE");
return error::kNoError;
}
GLint* results = GetSharedMemoryAs<GLint*>(
c.results_shm_id, c.results_shm_offset, result_size);
if (results == NULL) {
return error::kOutOfBounds;
}
for (uint32 ii = 0; ii < num_results; ++ii) {
if (results[ii]) {
return error::kInvalidArguments;
}
}
GLint* start = results;
for (GLuint ii = 0; ii < count; ++ii) {
GLsizei num_written = 0;
if (!GetHelper(enums[ii], results, &num_written)) {
glGetIntegerv(enums[ii], results);
}
results += num_written;
}
if (static_cast<uint32>(results - start) != num_results) {
return error::kOutOfBounds;
}
return error::kNoError;
}
|
error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM(
uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) {
GLuint count = c.count;
uint32 pnames_size;
if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) {
return error::kOutOfBounds;
}
const GLenum* pnames = GetSharedMemoryAs<const GLenum*>(
c.pnames_shm_id, c.pnames_shm_offset, pnames_size);
if (pnames == NULL) {
return error::kOutOfBounds;
}
scoped_array<GLenum> enums(new GLenum[count]);
memcpy(enums.get(), pnames, pnames_size);
uint32 num_results = 0;
for (GLuint ii = 0; ii < count; ++ii) {
uint32 num = util_.GLGetNumValuesReturned(enums[ii]);
if (num == 0) {
SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname");
return error::kNoError;
}
DCHECK_LE(num, 4u);
if (!SafeAddUint32(num_results, num, &num_results)) {
return error::kOutOfBounds;
}
}
uint32 result_size = 0;
if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) {
return error::kOutOfBounds;
}
if (result_size != static_cast<uint32>(c.size)) {
SetGLError(GL_INVALID_VALUE,
"glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE");
return error::kNoError;
}
GLint* results = GetSharedMemoryAs<GLint*>(
c.results_shm_id, c.results_shm_offset, result_size);
if (results == NULL) {
return error::kOutOfBounds;
}
for (uint32 ii = 0; ii < num_results; ++ii) {
if (results[ii]) {
return error::kInvalidArguments;
}
}
GLint* start = results;
for (GLuint ii = 0; ii < count; ++ii) {
GLsizei num_written = 0;
if (!GetHelper(enums[ii], results, &num_written)) {
glGetIntegerv(enums[ii], results);
}
results += num_written;
}
if (static_cast<uint32>(results - start) != num_results) {
return error::kOutOfBounds;
}
return error::kNoError;
}
|
CVE-2012-2896
|
CWE-189
|
Integer overflow in the WebGL implementation in Google Chrome before 22.0.1229.79 on Mac OS X allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.
|
https://github.com/chromium/chromium/commit/3aad1a37affb1ab70d1897f2b03eb8c077264984
|
Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
|
gpu/command_buffer/service/gles2_cmd_decoder.cc
|
cc
|
2012-09-07T20:54:47Z
|
static SDL_Surface* Create_Surface_Shaded(int width, int height, SDL_Color fg, SDL_Color bg, Uint32 *color)
{
const int alignment = Get_Alignement() - 1;
SDL_Surface *textbuf;
Sint64 size;
Uint8 bg_alpha = bg.a;
/* Create a surface with memory:
* - pitch is rounded to alignment
* - adress is aligned
*/
void *pixels, *ptr;
/* Worse case at the end of line pulling 'alignment' extra blank pixels */
Sint64 pitch = width + alignment;
pitch += alignment;
pitch &= ~alignment;
size = height * pitch + sizeof (void *) + alignment;
if (size < 0 || size > SDL_MAX_SINT32) {
/* Overflow... */
return NULL;
}
ptr = SDL_malloc((size_t)size);
if (ptr == NULL) {
return NULL;
}
/* address is aligned */
pixels = (void *)(((uintptr_t)ptr + sizeof(void *) + alignment) & ~alignment);
((void **)pixels)[-1] = ptr;
textbuf = SDL_CreateRGBSurfaceWithFormatFrom(pixels, width, height, 0, pitch, SDL_PIXELFORMAT_INDEX8);
if (textbuf == NULL) {
SDL_free(ptr);
return NULL;
}
/* Let SDL handle the memory allocation */
textbuf->flags &= ~SDL_PREALLOC;
textbuf->flags |= SDL_SIMD_ALIGNED;
/* Initialize with background to 0 */
SDL_memset(pixels, 0, height * pitch);
/* Underline/Strikethrough color style */
*color = NUM_GRAYS - 1;
/* Support alpha blending */
if (fg.a != SDL_ALPHA_OPAQUE || bg.a != SDL_ALPHA_OPAQUE) {
SDL_SetSurfaceBlendMode(textbuf, SDL_BLENDMODE_BLEND);
/* Would disturb alpha palette */
if (bg.a == SDL_ALPHA_OPAQUE) {
bg.a = 0;
}
}
/* Fill the palette with NUM_GRAYS levels of shading from bg to fg */
{
SDL_Palette *palette = textbuf->format->palette;
int rdiff = fg.r - bg.r;
int gdiff = fg.g - bg.g;
int bdiff = fg.b - bg.b;
int adiff = fg.a - bg.a;
int sign_r = (rdiff >= 0) ? 1 : 255;
int sign_g = (gdiff >= 0) ? 1 : 255;
int sign_b = (bdiff >= 0) ? 1 : 255;
int sign_a = (adiff >= 0) ? 1 : 255;
int i;
for (i = 0; i < NUM_GRAYS; ++i) {
/* Compute color[i] = (i * color_diff / 255) */
int tmp_r = i * rdiff;
int tmp_g = i * gdiff;
int tmp_b = i * bdiff;
int tmp_a = i * adiff;
palette->colors[i].r = (Uint8)(bg.r + DIVIDE_BY_255_SIGNED(tmp_r, sign_r));
palette->colors[i].g = (Uint8)(bg.g + DIVIDE_BY_255_SIGNED(tmp_g, sign_g));
palette->colors[i].b = (Uint8)(bg.b + DIVIDE_BY_255_SIGNED(tmp_b, sign_b));
palette->colors[i].a = (Uint8)(bg.a + DIVIDE_BY_255_SIGNED(tmp_a, sign_a));
}
/* Make sure background has the correct alpha value */
palette->colors[0].a = bg_alpha;
}
return textbuf;
|
static SDL_Surface* Create_Surface_Shaded(int width, int height, SDL_Color fg, SDL_Color bg, Uint32 *color)
{
const int alignment = Get_Alignement() - 1;
SDL_Surface *textbuf;
Sint64 size;
Uint8 bg_alpha = bg.a;
/* Create a surface with memory:
* - pitch is rounded to alignment
* - adress is aligned
*/
void *pixels, *ptr;
/* Worse case at the end of line pulling 'alignment' extra blank pixels */
Sint64 pitch = (Sint64)width + (Sint64)alignment;
pitch += alignment;
pitch &= ~alignment;
size = height * pitch + sizeof (void *) + alignment;
if (size < 0 || size > SDL_MAX_SINT32) {
/* Overflow... */
return NULL;
}
ptr = SDL_malloc((size_t)size);
if (ptr == NULL) {
return NULL;
}
/* address is aligned */
pixels = (void *)(((uintptr_t)ptr + sizeof(void *) + alignment) & ~alignment);
((void **)pixels)[-1] = ptr;
textbuf = SDL_CreateRGBSurfaceWithFormatFrom(pixels, width, height, 0, pitch, SDL_PIXELFORMAT_INDEX8);
if (textbuf == NULL) {
SDL_free(ptr);
return NULL;
}
/* Let SDL handle the memory allocation */
textbuf->flags &= ~SDL_PREALLOC;
textbuf->flags |= SDL_SIMD_ALIGNED;
/* Initialize with background to 0 */
SDL_memset(pixels, 0, height * pitch);
/* Underline/Strikethrough color style */
*color = NUM_GRAYS - 1;
/* Support alpha blending */
if (fg.a != SDL_ALPHA_OPAQUE || bg.a != SDL_ALPHA_OPAQUE) {
SDL_SetSurfaceBlendMode(textbuf, SDL_BLENDMODE_BLEND);
/* Would disturb alpha palette */
if (bg.a == SDL_ALPHA_OPAQUE) {
bg.a = 0;
}
}
/* Fill the palette with NUM_GRAYS levels of shading from bg to fg */
{
SDL_Palette *palette = textbuf->format->palette;
int rdiff = fg.r - bg.r;
int gdiff = fg.g - bg.g;
int bdiff = fg.b - bg.b;
int adiff = fg.a - bg.a;
int sign_r = (rdiff >= 0) ? 1 : 255;
int sign_g = (gdiff >= 0) ? 1 : 255;
int sign_b = (bdiff >= 0) ? 1 : 255;
int sign_a = (adiff >= 0) ? 1 : 255;
int i;
for (i = 0; i < NUM_GRAYS; ++i) {
/* Compute color[i] = (i * color_diff / 255) */
int tmp_r = i * rdiff;
int tmp_g = i * gdiff;
int tmp_b = i * bdiff;
int tmp_a = i * adiff;
palette->colors[i].r = (Uint8)(bg.r + DIVIDE_BY_255_SIGNED(tmp_r, sign_r));
palette->colors[i].g = (Uint8)(bg.g + DIVIDE_BY_255_SIGNED(tmp_g, sign_g));
palette->colors[i].b = (Uint8)(bg.b + DIVIDE_BY_255_SIGNED(tmp_b, sign_b));
palette->colors[i].a = (Uint8)(bg.a + DIVIDE_BY_255_SIGNED(tmp_a, sign_a));
}
/* Make sure background has the correct alpha value */
palette->colors[0].a = bg_alpha;
}
return textbuf;
|
CVE-2022-27470
|
CWE-787
|
SDL_ttf v2.0.18 and below was discovered to contain an arbitrary memory write via the function TTF_RenderText_Solid(). This vulnerability is triggered via a crafted TTF file.
|
https://github.com/libsdl-org/SDL_ttf/commit/db1b41ab8bde6723c24b866e466cad78c2fa0448
|
More integer overflow (see bug #187)
Make sure that 'width + alignment' doesn't overflow, otherwise
it could create a SDL_Surface of 'width' but with wrong 'pitch'
|
SDL_ttf.c
|
c
|
2022-05-04T03:15:00Z
|
private void playerLeftParty(PlayerLeftPartyTeamEvent event) {
if (event.getTeamDeleted()) {
// last player leaving the party; transfer any claims the party had back to that player, if possible
FTBChunksTeamData ownerData = FTBChunksAPI.getManager().getData(event.getPlayer());
FTBChunksTeamData deletedData = FTBChunksAPI.getManager().getData(event.getTeam());
transferClaims(deletedData, ownerData);
FTBChunksAPI.getManager().deleteTeam(event.getTeam());
}
}
|
private void playerLeftParty(PlayerLeftPartyTeamEvent event) {
FTBChunksTeamData partyData = FTBChunksAPI.getManager().getData(event.getTeam());
FTBChunksTeamData playerData = FTBChunksAPI.getManager().getData(event.getPlayer());
if (event.getTeamDeleted()) {
// last player leaving the party; transfer any remaining claims the party had back to that player, if possible
transferClaims(partyData, playerData, partyData.getClaimedChunks());
// and purge party team data from manager & disk
FTBChunksAPI.getManager().deleteTeam(event.getTeam());
} else {
// return the departing player's original claims to them, if possible
transferClaims(partyData, playerData, partyData.getOriginalClaims(event.getPlayerId()));
partyData.originalClaims.remove(playerData.getTeamId());
}
}
| null | null | null |
https://github.com/FTBTeam/FTB-Chunks/commit/ad275524ddb57eb2ada6349b039cc905462b589d
|
fix: remember player's original claims when they join a party
Transfer those claims back to the player when they leave the party;
prevents claim stealing by maliciously inviting and kicking a player
https://github.com/FTBTeam/FTB-Mods-Issues/issues/4
|
common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunks.java
|
java
|
2022-11-14T11:39:01Z
|
public function delete()
{
return $this->filesystem->deleteDir($this->path);
}
|
public static function delete($id)
{
$id = sprintf('%d', $id);
$parent = self::getParent($id);
$sql = array(
'table' => 'cat',
'where' => array(
'id' => $id,
),
);
$cat = Db::delete($sql);
if ($cat) {
return true;
} else {
return false;
}
// check all posts with this category and move to parent categories
$post = Db::result("SELECT `id` FROM `posts`
WHERE `cat` = '{$id}'");
$npost = Db::$num_rows;
//print_r($parent);
if ($npost > 0) {
$sql = "UPDATE `posts`
SET `cat` = '{$parent[0]->parent}'
WHERE `cat` = '{$id}'";
Db::query($sql);
}
}
|
CVE-2016-10096
|
CWE-89
|
SQL injection vulnerability in register.php in GeniXCMS before 1.0.0 allows remote attackers to execute arbitrary SQL commands via the activation parameter.
|
https://github.com/semplon/GeniXCMS/commit/d885eb20006099262c0278932b9f8aca3c1ac97f
|
Major Update for Version 1.0.0 release
|
viewbutton.js
|
js
|
2017-01-01T19:59:00Z
|
static void ffserver_apply_stream_config(AVCodecContext *enc, const AVDictionary *conf, AVDictionary **opts)
{
AVDictionaryEntry *e;
if ((e = av_dict_get(conf, "VideoBitRateRangeMin", NULL, 0)))
ffserver_set_int_param(&enc->rc_min_rate, e->value, 1000, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoBitRateRangeMax", NULL, 0)))
ffserver_set_int_param(&enc->rc_max_rate, e->value, 1000, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "Debug", NULL, 0)))
ffserver_set_int_param(&enc->debug, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "Strict", NULL, 0)))
ffserver_set_int_param(&enc->strict_std_compliance, e->value, 0,
INT_MIN, INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoBufferSize", NULL, 0)))
ffserver_set_int_param(&enc->rc_buffer_size, e->value, 8*1024,
INT_MIN, INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoBitRateTolerance", NULL, 0)))
ffserver_set_int_param(&enc->bit_rate_tolerance, e->value, 1000,
INT_MIN, INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoBitRate", NULL, 0)))
ffserver_set_int_param(&enc->bit_rate, e->value, 1000, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoSizeWidth", NULL, 0)))
ffserver_set_int_param(&enc->width, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoSizeHeight", NULL, 0)))
ffserver_set_int_param(&enc->height, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "PixelFormat", NULL, 0))) {
int val;
ffserver_set_int_param(&val, e->value, 0, INT_MIN, INT_MAX, NULL, 0,
NULL);
enc->pix_fmt = val;
}
if ((e = av_dict_get(conf, "VideoGopSize", NULL, 0)))
ffserver_set_int_param(&enc->gop_size, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoFrameRateNum", NULL, 0)))
ffserver_set_int_param(&enc->time_base.num, e->value, 0, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoFrameRateDen", NULL, 0)))
ffserver_set_int_param(&enc->time_base.den, e->value, 0, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoQDiff", NULL, 0)))
ffserver_set_int_param(&enc->max_qdiff, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoQMax", NULL, 0)))
ffserver_set_int_param(&enc->qmax, e->value, 0, INT_MIN, INT_MAX, NULL,
0, NULL);
if ((e = av_dict_get(conf, "VideoQMin", NULL, 0)))
ffserver_set_int_param(&enc->qmin, e->value, 0, INT_MIN, INT_MAX, NULL,
0, NULL);
if ((e = av_dict_get(conf, "LumiMask", NULL, 0)))
ffserver_set_float_param(&enc->lumi_masking, e->value, 0, -FLT_MAX,
FLT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "DarkMask", NULL, 0)))
ffserver_set_float_param(&enc->dark_masking, e->value, 0, -FLT_MAX,
FLT_MAX, NULL, 0, NULL);
if (av_dict_get(conf, "BitExact", NULL, 0))
enc->flags |= CODEC_FLAG_BITEXACT;
if (av_dict_get(conf, "DctFastint", NULL, 0))
enc->dct_algo = FF_DCT_FASTINT;
if (av_dict_get(conf, "IdctSimple", NULL, 0))
enc->idct_algo = FF_IDCT_SIMPLE;
if (av_dict_get(conf, "VideoHighQuality", NULL, 0))
enc->mb_decision = FF_MB_DECISION_BITS;
if ((e = av_dict_get(conf, "VideoTag", NULL, 0)))
enc->codec_tag = MKTAG(e->value[0], e->value[1], e->value[2], e->value[3]);
if (av_dict_get(conf, "Qscale", NULL, 0)) {
enc->flags |= CODEC_FLAG_QSCALE;
ffserver_set_int_param(&enc->global_quality, e->value, FF_QP2LAMBDA,
INT_MIN, INT_MAX, NULL, 0, NULL);
}
if (av_dict_get(conf, "Video4MotionVector", NULL, 0)) {
enc->mb_decision = FF_MB_DECISION_BITS;
enc->flags |= CODEC_FLAG_4MV;
}
if ((e = av_dict_get(conf, "AudioChannels", NULL, 0)))
ffserver_set_int_param(&enc->channels, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "AudioSampleRate", NULL, 0)))
ffserver_set_int_param(&enc->sample_rate, e->value, 0, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "AudioBitRate", NULL, 0)))
ffserver_set_int_param(&enc->bit_rate, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
av_opt_set_dict2(enc->priv_data, opts, AV_OPT_SEARCH_CHILDREN);
av_opt_set_dict2(enc, opts, AV_OPT_SEARCH_CHILDREN);
if (av_dict_count(*opts))
av_log(NULL, AV_LOG_ERROR, "Something went wrong, %d options not set!!!\n", av_dict_count(*opts));
}
|
static void ffserver_apply_stream_config(AVCodecContext *enc, const AVDictionary *conf, AVDictionary **opts)
{
AVDictionaryEntry *e;
if ((e = av_dict_get(conf, "VideoBitRateRangeMin", NULL, 0)))
ffserver_set_int_param(&enc->rc_min_rate, e->value, 1000, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoBitRateRangeMax", NULL, 0)))
ffserver_set_int_param(&enc->rc_max_rate, e->value, 1000, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "Debug", NULL, 0)))
ffserver_set_int_param(&enc->debug, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "Strict", NULL, 0)))
ffserver_set_int_param(&enc->strict_std_compliance, e->value, 0,
INT_MIN, INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoBufferSize", NULL, 0)))
ffserver_set_int_param(&enc->rc_buffer_size, e->value, 8*1024,
INT_MIN, INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoBitRateTolerance", NULL, 0)))
ffserver_set_int_param(&enc->bit_rate_tolerance, e->value, 1000,
INT_MIN, INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoBitRate", NULL, 0)))
ffserver_set_int_param(&enc->bit_rate, e->value, 1000, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoSizeWidth", NULL, 0)))
ffserver_set_int_param(&enc->width, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoSizeHeight", NULL, 0)))
ffserver_set_int_param(&enc->height, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "PixelFormat", NULL, 0))) {
int val;
ffserver_set_int_param(&val, e->value, 0, INT_MIN, INT_MAX, NULL, 0,
NULL);
enc->pix_fmt = val;
}
if ((e = av_dict_get(conf, "VideoGopSize", NULL, 0)))
ffserver_set_int_param(&enc->gop_size, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoFrameRateNum", NULL, 0)))
ffserver_set_int_param(&enc->time_base.num, e->value, 0, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoFrameRateDen", NULL, 0)))
ffserver_set_int_param(&enc->time_base.den, e->value, 0, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoQDiff", NULL, 0)))
ffserver_set_int_param(&enc->max_qdiff, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "VideoQMax", NULL, 0)))
ffserver_set_int_param(&enc->qmax, e->value, 0, INT_MIN, INT_MAX, NULL,
0, NULL);
if ((e = av_dict_get(conf, "VideoQMin", NULL, 0)))
ffserver_set_int_param(&enc->qmin, e->value, 0, INT_MIN, INT_MAX, NULL,
0, NULL);
if ((e = av_dict_get(conf, "LumiMask", NULL, 0)))
ffserver_set_float_param(&enc->lumi_masking, e->value, 0, -FLT_MAX,
FLT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "DarkMask", NULL, 0)))
ffserver_set_float_param(&enc->dark_masking, e->value, 0, -FLT_MAX,
FLT_MAX, NULL, 0, NULL);
if (av_dict_get(conf, "BitExact", NULL, 0))
enc->flags |= CODEC_FLAG_BITEXACT;
if (av_dict_get(conf, "DctFastint", NULL, 0))
enc->dct_algo = FF_DCT_FASTINT;
if (av_dict_get(conf, "IdctSimple", NULL, 0))
enc->idct_algo = FF_IDCT_SIMPLE;
if (av_dict_get(conf, "VideoHighQuality", NULL, 0))
enc->mb_decision = FF_MB_DECISION_BITS;
if ((e = av_dict_get(conf, "VideoTag", NULL, 0)))
enc->codec_tag = MKTAG(e->value[0], e->value[1], e->value[2], e->value[3]);
if ((e = av_dict_get(conf, "Qscale", NULL, 0))) {
enc->flags |= CODEC_FLAG_QSCALE;
ffserver_set_int_param(&enc->global_quality, e->value, FF_QP2LAMBDA,
INT_MIN, INT_MAX, NULL, 0, NULL);
}
if (av_dict_get(conf, "Video4MotionVector", NULL, 0)) {
enc->mb_decision = FF_MB_DECISION_BITS;
enc->flags |= CODEC_FLAG_4MV;
}
if ((e = av_dict_get(conf, "AudioChannels", NULL, 0)))
ffserver_set_int_param(&enc->channels, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
if ((e = av_dict_get(conf, "AudioSampleRate", NULL, 0)))
ffserver_set_int_param(&enc->sample_rate, e->value, 0, INT_MIN,
INT_MAX, NULL, 0, NULL);
if ((e = av_dict_get(conf, "AudioBitRate", NULL, 0)))
ffserver_set_int_param(&enc->bit_rate, e->value, 0, INT_MIN, INT_MAX,
NULL, 0, NULL);
av_opt_set_dict2(enc->priv_data, opts, AV_OPT_SEARCH_CHILDREN);
av_opt_set_dict2(enc, opts, AV_OPT_SEARCH_CHILDREN);
if (av_dict_count(*opts))
av_log(NULL, AV_LOG_ERROR, "Something went wrong, %d options not set!!!\n", av_dict_count(*opts));
}
| null | null | null |
FFmpeg/commit/3f07dd6e392bf35a478203dc60fcbd36dfdd42aa
|
ffserver_config: fix possible crash
Fixes CID #1254662
Signed-off-by: Lukasz Marek <lukasz.m.luki2@gmail.com>
|
./ffmpeg/ffserver_config.c
|
c
|
2014-11-16T01:15:58Z
|
static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
KmvcContext *const ctx = avctx->priv_data;
uint8_t *out, *src;
int i;
int header;
int blocksize;
const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
if (ctx->pic.data[0])
avctx->release_buffer(avctx, &ctx->pic);
ctx->pic.reference = 1;
ctx->pic.buffer_hints = FF_BUFFER_HINTS_VALID;
if (avctx->get_buffer(avctx, &ctx->pic) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return -1;
}
header = *buf++;
if (buf[0] == 127) {
buf += 3;
for (i = 0; i < 127; i++) {
ctx->pal[i + (header & 0x81)] = AV_RB24(buf);
buf += 4;
}
buf -= 127 * 4 + 3;
}
if (header & KMVC_KEYFRAME) {
ctx->pic.key_frame = 1;
ctx->pic.pict_type = AV_PICTURE_TYPE_I;
} else {
ctx->pic.key_frame = 0;
ctx->pic.pict_type = AV_PICTURE_TYPE_P;
}
if (header & KMVC_PALETTE) {
ctx->pic.palette_has_changed = 1;
for (i = 1; i <= ctx->palsize; i++) {
ctx->pal[i] = bytestream_get_be24(&buf);
}
}
if (pal) {
ctx->pic.palette_has_changed = 1;
memcpy(ctx->pal, pal, AVPALETTE_SIZE);
}
if (ctx->setpal) {
ctx->setpal = 0;
ctx->pic.palette_has_changed = 1;
}
memcpy(ctx->pic.data[1], ctx->pal, 1024);
blocksize = *buf++;
if (blocksize != 8 && blocksize != 127) {
av_log(avctx, AV_LOG_ERROR, "Block size = %i\n", blocksize);
return -1;
}
memset(ctx->cur, 0, 320 * 200);
switch (header & KMVC_METHOD) {
case 0:
case 1:
memcpy(ctx->cur, ctx->prev, 320 * 200);
break;
case 3:
kmvc_decode_intra_8x8(ctx, buf, buf_size, avctx->width, avctx->height);
break;
case 4:
kmvc_decode_inter_8x8(ctx, buf, buf_size, avctx->width, avctx->height);
break;
default:
av_log(avctx, AV_LOG_ERROR, "Unknown compression method %i\n", header & KMVC_METHOD);
return -1;
}
out = ctx->pic.data[0];
src = ctx->cur;
for (i = 0; i < avctx->height; i++) {
memcpy(out, src, avctx->width);
src += 320;
out += ctx->pic.linesize[0];
}
if (ctx->cur == ctx->frm0) {
ctx->cur = ctx->frm1;
ctx->prev = ctx->frm0;
} else {
ctx->cur = ctx->frm0;
ctx->prev = ctx->frm1;
}
*data_size = sizeof(AVFrame);
*(AVFrame *) data = ctx->pic;
return buf_size;
}
|
static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPacket *avpkt)
{
KmvcContext *const ctx = avctx->priv_data;
uint8_t *out, *src;
int i;
int header;
int blocksize;
const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
bytestream2_init(&ctx->g, avpkt->data, avpkt->size);
if (ctx->pic.data[0])
avctx->release_buffer(avctx, &ctx->pic);
ctx->pic.reference = 1;
ctx->pic.buffer_hints = FF_BUFFER_HINTS_VALID;
if (avctx->get_buffer(avctx, &ctx->pic) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return -1;
}
header = bytestream2_get_byte(&ctx->g);
if (bytestream2_peek_byte(&ctx->g) == 127) {
bytestream2_skip(&ctx->g, 3);
for (i = 0; i < 127; i++) {
ctx->pal[i + (header & 0x81)] = bytestream2_get_be24(&ctx->g);
bytestream2_skip(&ctx->g, 1);
}
bytestream2_seek(&ctx->g, -127 * 4 - 3, SEEK_CUR);
}
if (header & KMVC_KEYFRAME) {
ctx->pic.key_frame = 1;
ctx->pic.pict_type = AV_PICTURE_TYPE_I;
} else {
ctx->pic.key_frame = 0;
ctx->pic.pict_type = AV_PICTURE_TYPE_P;
}
if (header & KMVC_PALETTE) {
ctx->pic.palette_has_changed = 1;
for (i = 1; i <= ctx->palsize; i++) {
ctx->pal[i] = bytestream2_get_be24(&ctx->g);
}
}
if (pal) {
ctx->pic.palette_has_changed = 1;
memcpy(ctx->pal, pal, AVPALETTE_SIZE);
}
if (ctx->setpal) {
ctx->setpal = 0;
ctx->pic.palette_has_changed = 1;
}
memcpy(ctx->pic.data[1], ctx->pal, 1024);
blocksize = bytestream2_get_byte(&ctx->g);
if (blocksize != 8 && blocksize != 127) {
av_log(avctx, AV_LOG_ERROR, "Block size = %i\n", blocksize);
return -1;
}
memset(ctx->cur, 0, 320 * 200);
switch (header & KMVC_METHOD) {
case 0:
case 1:
memcpy(ctx->cur, ctx->prev, 320 * 200);
break;
case 3:
kmvc_decode_intra_8x8(ctx, avctx->width, avctx->height);
break;
case 4:
kmvc_decode_inter_8x8(ctx, avctx->width, avctx->height);
break;
default:
av_log(avctx, AV_LOG_ERROR, "Unknown compression method %i\n", header & KMVC_METHOD);
return -1;
}
out = ctx->pic.data[0];
src = ctx->cur;
for (i = 0; i < avctx->height; i++) {
memcpy(out, src, avctx->width);
src += 320;
out += ctx->pic.linesize[0];
}
if (ctx->cur == ctx->frm0) {
ctx->cur = ctx->frm1;
ctx->prev = ctx->frm0;
} else {
ctx->cur = ctx->frm0;
ctx->prev = ctx->frm1;
}
*data_size = sizeof(AVFrame);
*(AVFrame *) data = ctx->pic;
return avpkt->size;
}
| null | null | null |
FFmpeg/commit/da2e774fd6841da7cede8c8ef30337449329727c
|
kmvc: Use bytestream2 functions to prevent buffer overreads.
Signed-off-by: Ronald S. Bultje <rsbultje@gmail.com>
|
./ffmpeg/libavcodec/kmvc.c
|
c
|
2012-01-10T01:21:17Z
|
static int
ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
ext4_lblk_t iblock, unsigned int max_blocks,
struct ext4_ext_path *path, int flags,
unsigned int allocated, struct buffer_head *bh_result,
ext4_fsblk_t newblock)
{
int ret = 0;
int err = 0;
ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
"block %llu, max_blocks %u, flags %d, allocated %u",
inode->i_ino, (unsigned long long)iblock, max_blocks,
flags, allocated);
ext4_ext_show_leaf(inode, path);
/* get_block() before submit the IO, split the extent */
if (flags == EXT4_GET_BLOCKS_PRE_IO) {
ret = ext4_split_unwritten_extents(handle,
inode, path, iblock,
max_blocks, flags);
/*
* Flag the inode(non aio case) or end_io struct (aio case)
* that this IO needs to convertion to written when IO is
* completed
*/
if (io)
io->flag = EXT4_IO_UNWRITTEN;
else
ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if (flags == EXT4_GET_BLOCKS_CONVERT) {
ret = ext4_convert_unwritten_extents_endio(handle, inode,
path);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
goto out2;
}
/* buffered IO case */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
goto map_out;
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
set_buffer_unwritten(bh_result);
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode,
path, iblock,
max_blocks);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
set_buffer_new(bh_result);
/*
* if we allocated more blocks than requested
* we need to make sure we unmap the extra block
* allocated. The actual needed block will get
* unmapped later when we find the buffer_head marked
* new.
*/
if (allocated > max_blocks) {
unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
newblock + max_blocks,
allocated - max_blocks);
allocated = max_blocks;
}
/*
* If we have done fallocate with the offset that is already
* delayed allocated, we would have block reservation
* and quota reservation done in the delayed write path.
* But fallocate would have already updated quota and block
* count for this offset. So cancel these reservation
*/
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ext4_da_update_reserve_space(inode, allocated, 0);
map_out:
set_buffer_mapped(bh_result);
out1:
if (allocated > max_blocks)
allocated = max_blocks;
ext4_ext_show_leaf(inode, path);
bh_result->b_bdev = inode->i_sb->s_bdev;
bh_result->b_blocknr = newblock;
out2:
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err ? err : allocated;
}
|
static int
ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
ext4_lblk_t iblock, unsigned int max_blocks,
struct ext4_ext_path *path, int flags,
unsigned int allocated, struct buffer_head *bh_result,
ext4_fsblk_t newblock)
{
int ret = 0;
int err = 0;
ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
"block %llu, max_blocks %u, flags %d, allocated %u",
inode->i_ino, (unsigned long long)iblock, max_blocks,
flags, allocated);
ext4_ext_show_leaf(inode, path);
/* get_block() before submit the IO, split the extent */
if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
ret = ext4_split_unwritten_extents(handle,
inode, path, iblock,
max_blocks, flags);
/*
* Flag the inode(non aio case) or end_io struct (aio case)
* that this IO needs to convertion to written when IO is
* completed
*/
if (io)
io->flag = EXT4_IO_UNWRITTEN;
else
ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
if (ext4_should_dioread_nolock(inode))
set_buffer_uninit(bh_result);
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
ret = ext4_convert_unwritten_extents_endio(handle, inode,
path);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
goto out2;
}
/* buffered IO case */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
goto map_out;
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
set_buffer_unwritten(bh_result);
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode,
path, iblock,
max_blocks);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
set_buffer_new(bh_result);
/*
* if we allocated more blocks than requested
* we need to make sure we unmap the extra block
* allocated. The actual needed block will get
* unmapped later when we find the buffer_head marked
* new.
*/
if (allocated > max_blocks) {
unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
newblock + max_blocks,
allocated - max_blocks);
allocated = max_blocks;
}
/*
* If we have done fallocate with the offset that is already
* delayed allocated, we would have block reservation
* and quota reservation done in the delayed write path.
* But fallocate would have already updated quota and block
* count for this offset. So cancel these reservation
*/
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ext4_da_update_reserve_space(inode, allocated, 0);
map_out:
set_buffer_mapped(bh_result);
out1:
if (allocated > max_blocks)
allocated = max_blocks;
ext4_ext_show_leaf(inode, path);
bh_result->b_bdev = inode->i_sb->s_bdev;
bh_result->b_blocknr = newblock;
out2:
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err ? err : allocated;
}
| null | null | null |
https://github.com/torvalds/linux/commit/744692dc059845b2a3022119871846e74d4f6e11
|
ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
|
fs/ext4/extents.c
|
c
|
2010-03-04T21:14:02Z
|
static BCPos debug_framepc(lua_State *L, GCfunc *fn, cTValue *nextframe)
{
const BCIns *ins;
GCproto *pt;
BCPos pos;
lua_assert(fn->c.gct == ~LJ_TFUNC || fn->c.gct == ~LJ_TTHREAD);
if (!isluafunc(fn)) { /* Cannot derive a PC for non-Lua functions. */
return NO_BCPOS;
} else if (nextframe == NULL) { /* Lua function on top. */
void *cf = cframe_raw(L->cframe);
if (cf == NULL || (char *)cframe_pc(cf) == (char *)cframe_L(cf))
return NO_BCPOS;
ins = cframe_pc(cf); /* Only happens during error/hook handling. */
} else {
if (frame_islua(nextframe)) {
ins = frame_pc(nextframe);
} else if (frame_iscont(nextframe)) {
ins = frame_contpc(nextframe);
} else {
/* Lua function below errfunc/gc/hook: find cframe to get the PC. */
void *cf = cframe_raw(L->cframe);
TValue *f = L->base-1;
for (;;) {
if (cf == NULL)
return NO_BCPOS;
while (cframe_nres(cf) < 0) {
if (f >= restorestack(L, -cframe_nres(cf)))
break;
cf = cframe_raw(cframe_prev(cf));
if (cf == NULL)
return NO_BCPOS;
}
if (f < nextframe)
break;
if (frame_islua(f)) {
f = frame_prevl(f);
} else {
if (frame_isc(f) || (LJ_HASFFI && frame_iscont(f) &&
(f-1)->u32.lo == LJ_CONT_FFI_CALLBACK))
cf = cframe_raw(cframe_prev(cf));
f = frame_prevd(f);
}
}
ins = cframe_pc(cf);
}
}
pt = funcproto(fn);
pos = proto_bcpos(pt, ins) - 1;
#if LJ_HASJIT
if (pos > pt->sizebc) { /* Undo the effects of lj_trace_exit for JLOOP. */
GCtrace *T = (GCtrace *)((char *)(ins-1) - offsetof(GCtrace, startins));
lua_assert(bc_isret(bc_op(ins[-1])));
pos = proto_bcpos(pt, mref(T->startpc, const BCIns));
}
#endif
return pos;
}
|
static BCPos debug_framepc(lua_State *L, GCfunc *fn, cTValue *nextframe)
{
const BCIns *ins;
GCproto *pt;
BCPos pos;
lua_assert(fn->c.gct == ~LJ_TFUNC || fn->c.gct == ~LJ_TTHREAD);
if (!isluafunc(fn)) { /* Cannot derive a PC for non-Lua functions. */
return NO_BCPOS;
} else if (nextframe == NULL) { /* Lua function on top. */
void *cf = cframe_raw(L->cframe);
if (cf == NULL || (char *)cframe_pc(cf) == (char *)cframe_L(cf))
return NO_BCPOS;
ins = cframe_pc(cf); /* Only happens during error/hook handling. */
} else {
if (frame_islua(nextframe)) {
ins = frame_pc(nextframe);
} else if (frame_iscont(nextframe)) {
ins = frame_contpc(nextframe);
} else {
/* Lua function below errfunc/gc/hook: find cframe to get the PC. */
void *cf = cframe_raw(L->cframe);
TValue *f = L->base-1;
for (;;) {
if (cf == NULL)
return NO_BCPOS;
while (cframe_nres(cf) < 0) {
if (f >= restorestack(L, -cframe_nres(cf)))
break;
cf = cframe_raw(cframe_prev(cf));
if (cf == NULL)
return NO_BCPOS;
}
if (f < nextframe)
break;
if (frame_islua(f)) {
f = frame_prevl(f);
} else {
if (frame_isc(f) || (LJ_HASFFI && frame_iscont(f) &&
(f-1)->u32.lo == LJ_CONT_FFI_CALLBACK))
cf = cframe_raw(cframe_prev(cf));
f = frame_prevd(f);
}
}
ins = cframe_pc(cf);
if (!ins) return NO_BCPOS;
}
}
pt = funcproto(fn);
pos = proto_bcpos(pt, ins) - 1;
#if LJ_HASJIT
if (pos > pt->sizebc) { /* Undo the effects of lj_trace_exit for JLOOP. */
GCtrace *T = (GCtrace *)((char *)(ins-1) - offsetof(GCtrace, startins));
lua_assert(bc_isret(bc_op(ins[-1])));
pos = proto_bcpos(pt, mref(T->startpc, const BCIns));
}
#endif
return pos;
}
|
CVE-2020-24372
|
CWE-125
|
LuaJIT through 2.1.0-beta3 has an out-of-bounds read in lj_err_run in lj_err.c.
|
https://github.com/LuaJIT/LuaJIT/commit/e296f56b825c688c3530a981dc6b495d972f3d01
|
Call error function on rethrow after trace exit.
| null | null |
2020-08-09T20:50:31Z
|
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ip6t_entry *)e);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ipv6, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
|
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ip6t_entry *)e);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ipv6, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
|
CVE-2016-4998
|
CWE-119
|
The IPT_SO_SET_REPLACE setsockopt implementation in the netfilter subsystem in the Linux kernel before 4.6 allows local users to cause a denial of service (out-of-bounds read) or possibly obtain sensitive information from kernel heap memory by leveraging in-container root access to provide a crafted offset value that leads to crossing a ruleset blob boundary.
|
https://github.com/torvalds/linux/commit/6e94e0cfb0887e4013b3b930fa6ab1fe6bb6ba91
|
netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
|
ip6_tables.c
|
c
|
2016-03-22T17:02:50Z
|
@site.route('/lost_found', methods=['GET', 'POST'])
def PropertyPage():
if request.method == "POST":
formtype = request.form['form-name']
if formtype == "LostSomething":
lostdesc = request.form['LostSomethingDescription']
lostlocation = request.form['LostSomethingPossibleLocation']
lostdate = request.form['LostSomethingDate']
lostowner = request.form['LostSomethingOwnerName']
lostmail = request.form['LostSomethingOwnerMail']
lostphone = request.form['LostSomethingOwnerPhone']
with dbapi2.connect(current_app.config['dsn']) as connection:
cursor = connection.cursor()
query = """INSERT INTO LOSTSTUFF(STUFFDESC, POSSIBLELOC, POSSIBLEDATE, OWNERNAME, OWNERMAIL, OWNERPHONE) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')""" % (lostdesc, lostlocation, lostdate, lostowner, lostmail, lostphone)
cursor.execute(query)
connection.commit()
else:
founddesc = request.form['FoundSomethingDescription']
foundlocation = request.form['FoundSomethingCurrentLocation']
founddate = request.form['FoundSomethingDate']
foundname = request.form['FoundSomethingFinderName']
foundmail = request.form['FoundSomethingFinderMail']
foundphone = request.form['FoundSomethingFinderPhone']
with dbapi2.connect(current_app.config['dsn']) as connection:
cursor = connection.cursor()
query = """INSERT INTO FOUNDSTUFF(STUFFDESC, CURRENTLOC, FINDINGDATE, FOUNDERNAME, FOUNDERMAIL, FOUNDERPHONE) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')""" % (founddesc, foundlocation, founddate, foundname, foundmail, foundphone)
cursor.execute(query)
connection.commit()
return render_template('lost_found.html')
else:
return render_template('lost_found.html')
|
@site.route('/lost_found', methods=['GET', 'POST'])
def PropertyPage():
if request.method == "POST":
formtype = request.form['form-name']
if formtype == "LostSomething":
lostdesc = request.form['LostSomethingDescription']
lostlocation = request.form['LostSomethingPossibleLocation']
lostdate = request.form['LostSomethingDate']
lostowner = request.form['LostSomethingOwnerName']
lostmail = request.form['LostSomethingOwnerMail']
lostphone = request.form['LostSomethingOwnerPhone']
with dbapi2.connect(current_app.config['dsn']) as connection:
cursor = connection.cursor()#prevented sql injection
query = """INSERT INTO LOSTSTUFF(STUFFDESC, POSSIBLELOC, POSSIBLEDATE, OWNERNAME, OWNERMAIL, OWNERPHONE) VALUES (%s, %s, %s, %s, %s, %s)"""
cursor.execute(query, (lostdesc, lostlocation, lostdate, lostowner, lostmail, lostphone))
connection.commit()
else:
founddesc = request.form['FoundSomethingDescription']
foundlocation = request.form['FoundSomethingCurrentLocation']
founddate = request.form['FoundSomethingDate']
foundname = request.form['FoundSomethingFinderName']
foundmail = request.form['FoundSomethingFinderMail']
foundphone = request.form['FoundSomethingFinderPhone']
with dbapi2.connect(current_app.config['dsn']) as connection:
cursor = connection.cursor()#prevented sql injection
query = """INSERT INTO FOUNDSTUFF(STUFFDESC, CURRENTLOC, FINDINGDATE, FOUNDERNAME, FOUNDERMAIL, FOUNDERPHONE) VALUES (%s, %s, %s, %s, %s, %s)"""
cursor.execute(query, (founddesc, foundlocation, founddate, foundname, foundmail, foundphone))
connection.commit()
return render_template('lost_found.html')
else:
return render_template('lost_found.html')
| null |
cwe-089
| null |
github.com/itucsdb1705/itucsdb1705/commit/311d8c9a66d365be94a1d906bc68f3d4ad29ea4b
|
prevented sql injection
edited handlers.py to prevent sql injection
|
handlers.py
|
py
|
2017-10-18T10:49:10Z
|
private static void printNodeAST(LineWriter writer, NodeInterface node, String fieldName, int level) {
if (node == null) {
return;
}
writer.writeLineFormat("%s%s = %s", " ".repeat(level), fieldName, node);
for (Class<?> c = node.getClass(); c != Object.class; c = c.getSuperclass()) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
if (NodeInterface.class.isAssignableFrom(field.getType())) {
try {
field.setAccessible(true);
NodeInterface value = (NodeInterface) field.get(node);
if (value != null) {
printNodeAST(writer, value, field.getName(), level + 1);
}
} catch (IllegalAccessException | RuntimeException e) {
// ignore
}
} else if (NodeInterface[].class.isAssignableFrom(field.getType())) {
try {
field.setAccessible(true);
NodeInterface[] value = (NodeInterface[]) field.get(node);
if (value != null) {
for (int i = 0; i < value.length; i++) {
printNodeAST(writer, value[i], field.getName() + "[" + i + "]", level + 1);
}
}
} catch (IllegalAccessException | RuntimeException e) {
// ignore
}
}
}
}
}
|
private static void printNodeAST(LineWriter writer, NodeInterface node, String fieldName, int level) {
if (node == null) {
return;
}
writer.writeLineFormat("%s%s = %s", " ".repeat(level), fieldName, node);
for (Class<?> c = node.getClass(); c != Object.class; c = c.getSuperclass()) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers()) || "parent".equals(field.getName())) {
continue;
}
if (NodeInterface.class.isAssignableFrom(field.getType())) {
try {
field.setAccessible(true);
NodeInterface value = (NodeInterface) field.get(node);
if (value != null) {
printNodeAST(writer, value, field.getName(), level + 1);
}
} catch (IllegalAccessException | RuntimeException e) {
// ignore
}
} else if (NodeInterface[].class.isAssignableFrom(field.getType())) {
try {
field.setAccessible(true);
NodeInterface[] value = (NodeInterface[]) field.get(node);
if (value != null) {
for (int i = 0; i < value.length; i++) {
printNodeAST(writer, value[i], field.getName() + "[" + i + "]", level + 1);
}
}
} catch (IllegalAccessException | RuntimeException e) {
// ignore
}
}
}
}
}
| null | null | null |
https://github.com/oracle/graal/commit/47b483e1a85b00600e0b9a2c2e6c0caf0b1ec366
|
Fix stack overflow in LLVM node utils
|
sulong/projects/com.oracle.truffle.llvm.runtime/src/com/oracle/truffle/llvm/runtime/LLVMNodeUtils.java
|
java
|
2022-10-13T07:52:31Z
|
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 开启 Xss 过滤状态
XssStateHolder.open();
try {
filterChain.doFilter(new XssRequestWrapper(request), response);
}
finally {
// 必须删除 ThreadLocal 存储的状态
XssStateHolder.remove();
}
}
|
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 开启 Xss 过滤状态
XssStateHolder.open();
try {
filterChain.doFilter(new XssRequestWrapper(request, xssCleaner), response);
}
finally {
// 必须删除 ThreadLocal 存储的状态
XssStateHolder.remove();
}
}
| null | null | null |
https://github.com/ballcat-projects/ballcat/commit/2519b52a6e4a70b9d85ae2017e42b738ef5cce85
|
:zap: 抽象出 XssCleaner 角色,用于控制 Xss 文本的清除行为
|
ballcat-starters/ballcat-spring-boot-starter-xss/src/main/java/com/hccake/ballcat/common/xss/core/XssFilter.java
|
java
|
2021-08-27T13:30:56Z
|
ssize_t __weak cpu_show_l1tf(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "Not affected\n");
}
|
ssize_t __weak cpu_show_l1tf(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sysfs_emit(buf, "Not affected\n");
}
| null |
CWE-787
| null |
https://github.com/torvalds/linux/commit/aa838896d87af561a33ecefea1caa4c15a68bc47
|
drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions
Convert the various sprintf fmaily calls in sysfs device show functions
to sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.
Done with:
$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .
And cocci script:
$ cat sysfs_emit_dev.cocci
@@
identifier d_show;
identifier dev, attr, buf;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
return
- sprintf(buf,
+ sysfs_emit(buf,
...);
...>
}
@@
identifier d_show;
identifier dev, attr, buf;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
return
- snprintf(buf, PAGE_SIZE,
+ sysfs_emit(buf,
...);
...>
}
@@
identifier d_show;
identifier dev, attr, buf;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
return
- scnprintf(buf, PAGE_SIZE,
+ sysfs_emit(buf,
...);
...>
}
@@
identifier d_show;
identifier dev, attr, buf;
expression chr;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
return
- strcpy(buf, chr);
+ sysfs_emit(buf, chr);
...>
}
@@
identifier d_show;
identifier dev, attr, buf;
identifier len;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
len =
- sprintf(buf,
+ sysfs_emit(buf,
...);
...>
return len;
}
@@
identifier d_show;
identifier dev, attr, buf;
identifier len;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
len =
- snprintf(buf, PAGE_SIZE,
+ sysfs_emit(buf,
...);
...>
return len;
}
@@
identifier d_show;
identifier dev, attr, buf;
identifier len;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
len =
- scnprintf(buf, PAGE_SIZE,
+ sysfs_emit(buf,
...);
...>
return len;
}
@@
identifier d_show;
identifier dev, attr, buf;
identifier len;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
- len += scnprintf(buf + len, PAGE_SIZE - len,
+ len += sysfs_emit_at(buf, len,
...);
...>
return len;
}
@@
identifier d_show;
identifier dev, attr, buf;
expression chr;
@@
ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)
{
...
- strcpy(buf, chr);
- return strlen(buf);
+ return sysfs_emit(buf, chr);
}
Signed-off-by: Joe Perches <joe@perches.com>
Link: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
| null | null |
2020-09-16T20:40:39Z
|
function form_confirm_buttons($action_url, $cancel_url) {
global $config;
?>
<tr>
<td align='right'>
<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $cancel_url);?>")' value='<?php print __esc('Cancel');?>'>
<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $action_url . '&confirm=true');?>")' value='<?php print __esc('Delete');?>'>
</td>
</tr>
<?php }
|
function form_confirm_buttons($action_url, $cancel_url) {
global $config;
?>
<tr>
<td align='right'>
<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $cancel_url, ENT_QUOTES);?>")' value='<?php print __esc('Cancel');?>'>
<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $action_url . '&confirm=true', ENT_QUOTES);?>")' value='<?php print __esc('Delete');?>'>
</td>
</tr>
<?php }
|
CVE-2017-12065
|
NVD-CWE-noinfo
|
spikekill.php in Cacti before 1.1.16 might allow remote attackers to execute arbitrary code via the avgnan, outlier-start, or outlier-end parameter.
|
https://github.com/Cacti/cacti/commit/bd0e586f6f46d814930226f1516a194e7e72293e
|
Resolving Issue #877
Improving resolution to #847 and one additional vulnerability.
|
html_form.php
|
php
|
2017-08-01T05:29:00Z
|
int udhcpd_main(int argc UNUSED_PARAM, char **argv)
{
int server_socket = -1, retval;
uint8_t *state;
unsigned timeout_end;
unsigned num_ips;
unsigned opt;
struct option_set *option;
char *str_I = str_I;
const char *str_a = "2000";
unsigned arpping_ms;
IF_FEATURE_UDHCP_PORT(char *str_P;)
setup_common_bufsiz();
IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
opt = getopt32(argv, "^"
"fSI:va:"IF_FEATURE_UDHCP_PORT("P:")
"\0"
#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
"vv"
#endif
, &str_I
, &str_a
IF_FEATURE_UDHCP_PORT(, &str_P)
IF_UDHCP_VERBOSE(, &dhcp_verbose)
);
if (!(opt & 1)) { /* no -f */
bb_daemonize_or_rexec(0, argv);
logmode = LOGMODE_NONE;
}
/* update argv after the possible vfork+exec in daemonize */
argv += optind;
if (opt & 2) { /* -S */
openlog(applet_name, LOG_PID, LOG_DAEMON);
logmode |= LOGMODE_SYSLOG;
}
if (opt & 4) { /* -I */
len_and_sockaddr *lsa = xhost_and_af2sockaddr(str_I, 0, AF_INET);
server_config.server_nip = lsa->u.sin.sin_addr.s_addr;
free(lsa);
}
#if ENABLE_FEATURE_UDHCP_PORT
if (opt & 32) { /* -P */
SERVER_PORT = xatou16(str_P);
CLIENT_PORT = SERVER_PORT + 1;
}
#endif
arpping_ms = xatou(str_a);
/* Would rather not do read_config before daemonization -
* otherwise NOMMU machines will parse config twice */
read_config(argv[0] ? argv[0] : DHCPD_CONF_FILE);
/* prevent poll timeout overflow */
if (server_config.auto_time > INT_MAX / 1000)
server_config.auto_time = INT_MAX / 1000;
/* Make sure fd 0,1,2 are open */
bb_sanitize_stdio();
/* Create pidfile */
write_pidfile(server_config.pidfile);
/* if (!..) bb_perror_msg("can't create pidfile %s", pidfile); */
bb_error_msg("started, v"BB_VER);
option = udhcp_find_option(server_config.options, DHCP_LEASE_TIME);
server_config.max_lease_sec = DEFAULT_LEASE_TIME;
if (option) {
move_from_unaligned32(server_config.max_lease_sec, option->data + OPT_DATA);
server_config.max_lease_sec = ntohl(server_config.max_lease_sec);
}
/* Sanity check */
num_ips = server_config.end_ip - server_config.start_ip + 1;
if (server_config.max_leases > num_ips) {
bb_error_msg("max_leases=%u is too big, setting to %u",
(unsigned)server_config.max_leases, num_ips);
server_config.max_leases = num_ips;
}
/* this sets g_leases */
SET_PTR_TO_GLOBALS(xzalloc(server_config.max_leases * sizeof(g_leases[0])));
read_leases(server_config.lease_file);
if (udhcp_read_interface(server_config.interface,
&server_config.ifindex,
(server_config.server_nip == 0 ? &server_config.server_nip : NULL),
server_config.server_mac)
) {
retval = 1;
goto ret;
}
/* Setup the signal pipe */
udhcp_sp_setup();
continue_with_autotime:
timeout_end = monotonic_sec() + server_config.auto_time;
while (1) { /* loop until universe collapses */
struct pollfd pfds[2];
struct dhcp_packet packet;
int bytes;
int tv;
uint8_t *server_id_opt;
uint8_t *requested_ip_opt;
uint32_t requested_nip = requested_nip; /* for compiler */
uint32_t static_lease_nip;
struct dyn_lease *lease, fake_lease;
if (server_socket < 0) {
server_socket = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT,
server_config.interface);
}
udhcp_sp_fd_set(pfds, server_socket);
new_tv:
tv = -1;
if (server_config.auto_time) {
tv = timeout_end - monotonic_sec();
if (tv <= 0) {
write_leases:
write_leases();
goto continue_with_autotime;
}
tv *= 1000;
}
/* Block here waiting for either signal or packet */
retval = poll(pfds, 2, tv);
if (retval <= 0) {
if (retval == 0)
goto write_leases;
if (errno == EINTR)
goto new_tv;
/* < 0 and not EINTR: should not happen */
bb_perror_msg_and_die("poll");
}
if (pfds[0].revents) switch (udhcp_sp_read()) {
case SIGUSR1:
bb_error_msg("received %s", "SIGUSR1");
write_leases();
/* why not just reset the timeout, eh */
goto continue_with_autotime;
case SIGTERM:
bb_error_msg("received %s", "SIGTERM");
write_leases();
goto ret0;
}
/* Is it a packet? */
if (!pfds[1].revents)
continue; /* no */
/* Note: we do not block here, we block on poll() instead.
* Blocking here would prevent SIGTERM from working:
* socket read inside this call is restarted on caught signals.
*/
bytes = udhcp_recv_kernel_packet(&packet, server_socket);
if (bytes < 0) {
/* bytes can also be -2 ("bad packet data") */
if (bytes == -1 && errno != EINTR) {
log1("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
close(server_socket);
server_socket = -1;
}
continue;
}
if (packet.hlen != 6) {
bb_error_msg("MAC length != 6, ignoring packet");
continue;
}
if (packet.op != BOOTREQUEST) {
bb_error_msg("not a REQUEST, ignoring packet");
continue;
}
state = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (state == NULL || state[0] < DHCP_MINTYPE || state[0] > DHCP_MAXTYPE) {
bb_error_msg("no or bad message type option, ignoring packet");
continue;
}
/* Get SERVER_ID if present */
server_id_opt = udhcp_get_option(&packet, DHCP_SERVER_ID);
if (server_id_opt) {
uint32_t server_id_network_order;
move_from_unaligned32(server_id_network_order, server_id_opt);
if (server_id_network_order != server_config.server_nip) {
/* client talks to somebody else */
log1("server ID doesn't match, ignoring");
continue;
}
}
/* Look for a static/dynamic lease */
static_lease_nip = get_static_nip_by_mac(server_config.static_leases, &packet.chaddr);
if (static_lease_nip) {
bb_error_msg("found static lease: %x", static_lease_nip);
memcpy(&fake_lease.lease_mac, &packet.chaddr, 6);
fake_lease.lease_nip = static_lease_nip;
fake_lease.expires = 0;
lease = &fake_lease;
} else {
lease = find_lease_by_mac(packet.chaddr);
}
/* Get REQUESTED_IP if present */
requested_ip_opt = udhcp_get_option(&packet, DHCP_REQUESTED_IP);
if (requested_ip_opt) {
move_from_unaligned32(requested_nip, requested_ip_opt);
}
switch (state[0]) {
case DHCPDISCOVER:
log1("received %s", "DISCOVER");
send_offer(&packet, static_lease_nip, lease, requested_ip_opt, arpping_ms);
break;
case DHCPREQUEST:
log1("received %s", "REQUEST");
/* RFC 2131:
o DHCPREQUEST generated during SELECTING state:
Client inserts the address of the selected server in 'server
identifier', 'ciaddr' MUST be zero, 'requested IP address' MUST be
filled in with the yiaddr value from the chosen DHCPOFFER.
Note that the client may choose to collect several DHCPOFFER
messages and select the "best" offer. The client indicates its
selection by identifying the offering server in the DHCPREQUEST
message. If the client receives no acceptable offers, the client
may choose to try another DHCPDISCOVER message. Therefore, the
servers may not receive a specific DHCPREQUEST from which they can
decide whether or not the client has accepted the offer.
o DHCPREQUEST generated during INIT-REBOOT state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST be filled in with client's notion of its previously
assigned address. 'ciaddr' MUST be zero. The client is seeking to
verify a previously allocated, cached configuration. Server SHOULD
send a DHCPNAK message to the client if the 'requested IP address'
is incorrect, or is on the wrong network.
Determining whether a client in the INIT-REBOOT state is on the
correct network is done by examining the contents of 'giaddr', the
'requested IP address' option, and a database lookup. If the DHCP
server detects that the client is on the wrong net (i.e., the
result of applying the local subnet mask or remote subnet mask (if
'giaddr' is not zero) to 'requested IP address' option value
doesn't match reality), then the server SHOULD send a DHCPNAK
message to the client.
If the network is correct, then the DHCP server should check if
the client's notion of its IP address is correct. If not, then the
server SHOULD send a DHCPNAK message to the client. If the DHCP
server has no record of this client, then it MUST remain silent,
and MAY output a warning to the network administrator. This
behavior is necessary for peaceful coexistence of non-
communicating DHCP servers on the same wire.
If 'giaddr' is 0x0 in the DHCPREQUEST message, the client is on
the same subnet as the server. The server MUST broadcast the
DHCPNAK message to the 0xffffffff broadcast address because the
client may not have a correct network address or subnet mask, and
the client may not be answering ARP requests.
If 'giaddr' is set in the DHCPREQUEST message, the client is on a
different subnet. The server MUST set the broadcast bit in the
DHCPNAK, so that the relay agent will broadcast the DHCPNAK to the
client, because the client may not have a correct network address
or subnet mask, and the client may not be answering ARP requests.
o DHCPREQUEST generated during RENEWING state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST NOT be filled in, 'ciaddr' MUST be filled in with
client's IP address. In this situation, the client is completely
configured, and is trying to extend its lease. This message will
be unicast, so no relay agents will be involved in its
transmission. Because 'giaddr' is therefore not filled in, the
DHCP server will trust the value in 'ciaddr', and use it when
replying to the client.
A client MAY choose to renew or extend its lease prior to T1. The
server may choose not to extend the lease (as a policy decision by
the network administrator), but should return a DHCPACK message
regardless.
o DHCPREQUEST generated during REBINDING state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST NOT be filled in, 'ciaddr' MUST be filled in with
client's IP address. In this situation, the client is completely
configured, and is trying to extend its lease. This message MUST
be broadcast to the 0xffffffff IP broadcast address. The DHCP
server SHOULD check 'ciaddr' for correctness before replying to
the DHCPREQUEST.
The DHCPREQUEST from a REBINDING client is intended to accommodate
sites that have multiple DHCP servers and a mechanism for
maintaining consistency among leases managed by multiple servers.
A DHCP server MAY extend a client's lease only if it has local
administrative authority to do so.
*/
if (!requested_ip_opt) {
requested_nip = packet.ciaddr;
if (requested_nip == 0) {
log1("no requested IP and no ciaddr, ignoring");
break;
}
}
if (lease && requested_nip == lease->lease_nip) {
/* client requested or configured IP matches the lease.
* ACK it, and bump lease expiration time. */
send_ACK(&packet, lease->lease_nip);
break;
}
/* No lease for this MAC, or lease IP != requested IP */
if (server_id_opt /* client is in SELECTING state */
|| requested_ip_opt /* client is in INIT-REBOOT state */
) {
/* "No, we don't have this IP for you" */
send_NAK(&packet);
} /* else: client is in RENEWING or REBINDING, do not answer */
break;
case DHCPDECLINE:
/* RFC 2131:
* "If the server receives a DHCPDECLINE message,
* the client has discovered through some other means
* that the suggested network address is already
* in use. The server MUST mark the network address
* as not available and SHOULD notify the local
* sysadmin of a possible configuration problem."
*
* SERVER_ID must be present,
* REQUESTED_IP must be present,
* chaddr must be filled in,
* ciaddr must be 0 (we do not check this)
*/
log1("received %s", "DECLINE");
if (server_id_opt
&& requested_ip_opt
&& lease /* chaddr matches this lease */
&& requested_nip == lease->lease_nip
) {
memset(lease->lease_mac, 0, sizeof(lease->lease_mac));
lease->expires = time(NULL) + server_config.decline_time;
}
break;
case DHCPRELEASE:
/* "Upon receipt of a DHCPRELEASE message, the server
* marks the network address as not allocated."
*
* SERVER_ID must be present,
* REQUESTED_IP must not be present (we do not check this),
* chaddr must be filled in,
* ciaddr must be filled in
*/
log1("received %s", "RELEASE");
if (server_id_opt
&& lease /* chaddr matches this lease */
&& packet.ciaddr == lease->lease_nip
) {
lease->expires = time(NULL);
}
break;
case DHCPINFORM:
log1("received %s", "INFORM");
send_inform(&packet);
break;
}
}
ret0:
retval = 0;
ret:
/*if (server_config.pidfile) - server_config.pidfile is never NULL */
remove_pidfile(server_config.pidfile);
return retval;
}
|
int udhcpd_main(int argc UNUSED_PARAM, char **argv)
{
int server_socket = -1, retval;
uint8_t *state;
unsigned timeout_end;
unsigned num_ips;
unsigned opt;
struct option_set *option;
char *str_I = str_I;
const char *str_a = "2000";
unsigned arpping_ms;
IF_FEATURE_UDHCP_PORT(char *str_P;)
setup_common_bufsiz();
IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
opt = getopt32(argv, "^"
"fSI:va:"IF_FEATURE_UDHCP_PORT("P:")
"\0"
#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
"vv"
#endif
, &str_I
, &str_a
IF_FEATURE_UDHCP_PORT(, &str_P)
IF_UDHCP_VERBOSE(, &dhcp_verbose)
);
if (!(opt & 1)) { /* no -f */
bb_daemonize_or_rexec(0, argv);
logmode = LOGMODE_NONE;
}
/* update argv after the possible vfork+exec in daemonize */
argv += optind;
if (opt & 2) { /* -S */
openlog(applet_name, LOG_PID, LOG_DAEMON);
logmode |= LOGMODE_SYSLOG;
}
if (opt & 4) { /* -I */
len_and_sockaddr *lsa = xhost_and_af2sockaddr(str_I, 0, AF_INET);
server_config.server_nip = lsa->u.sin.sin_addr.s_addr;
free(lsa);
}
#if ENABLE_FEATURE_UDHCP_PORT
if (opt & 32) { /* -P */
SERVER_PORT = xatou16(str_P);
CLIENT_PORT = SERVER_PORT + 1;
}
#endif
arpping_ms = xatou(str_a);
/* Would rather not do read_config before daemonization -
* otherwise NOMMU machines will parse config twice */
read_config(argv[0] ? argv[0] : DHCPD_CONF_FILE);
/* prevent poll timeout overflow */
if (server_config.auto_time > INT_MAX / 1000)
server_config.auto_time = INT_MAX / 1000;
/* Make sure fd 0,1,2 are open */
bb_sanitize_stdio();
/* Create pidfile */
write_pidfile(server_config.pidfile);
/* if (!..) bb_perror_msg("can't create pidfile %s", pidfile); */
bb_error_msg("started, v"BB_VER);
option = udhcp_find_option(server_config.options, DHCP_LEASE_TIME);
server_config.max_lease_sec = DEFAULT_LEASE_TIME;
if (option) {
move_from_unaligned32(server_config.max_lease_sec, option->data + OPT_DATA);
server_config.max_lease_sec = ntohl(server_config.max_lease_sec);
}
/* Sanity check */
num_ips = server_config.end_ip - server_config.start_ip + 1;
if (server_config.max_leases > num_ips) {
bb_error_msg("max_leases=%u is too big, setting to %u",
(unsigned)server_config.max_leases, num_ips);
server_config.max_leases = num_ips;
}
/* this sets g_leases */
SET_PTR_TO_GLOBALS(xzalloc(server_config.max_leases * sizeof(g_leases[0])));
read_leases(server_config.lease_file);
if (udhcp_read_interface(server_config.interface,
&server_config.ifindex,
(server_config.server_nip == 0 ? &server_config.server_nip : NULL),
server_config.server_mac)
) {
retval = 1;
goto ret;
}
/* Setup the signal pipe */
udhcp_sp_setup();
continue_with_autotime:
timeout_end = monotonic_sec() + server_config.auto_time;
while (1) { /* loop until universe collapses */
struct pollfd pfds[2];
struct dhcp_packet packet;
int bytes;
int tv;
uint8_t *server_id_opt;
uint8_t *requested_ip_opt;
uint32_t requested_nip = requested_nip; /* for compiler */
uint32_t static_lease_nip;
struct dyn_lease *lease, fake_lease;
if (server_socket < 0) {
server_socket = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT,
server_config.interface);
}
udhcp_sp_fd_set(pfds, server_socket);
new_tv:
tv = -1;
if (server_config.auto_time) {
tv = timeout_end - monotonic_sec();
if (tv <= 0) {
write_leases:
write_leases();
goto continue_with_autotime;
}
tv *= 1000;
}
/* Block here waiting for either signal or packet */
retval = poll(pfds, 2, tv);
if (retval <= 0) {
if (retval == 0)
goto write_leases;
if (errno == EINTR)
goto new_tv;
/* < 0 and not EINTR: should not happen */
bb_perror_msg_and_die("poll");
}
if (pfds[0].revents) switch (udhcp_sp_read()) {
case SIGUSR1:
bb_error_msg("received %s", "SIGUSR1");
write_leases();
/* why not just reset the timeout, eh */
goto continue_with_autotime;
case SIGTERM:
bb_error_msg("received %s", "SIGTERM");
write_leases();
goto ret0;
}
/* Is it a packet? */
if (!pfds[1].revents)
continue; /* no */
/* Note: we do not block here, we block on poll() instead.
* Blocking here would prevent SIGTERM from working:
* socket read inside this call is restarted on caught signals.
*/
bytes = udhcp_recv_kernel_packet(&packet, server_socket);
if (bytes < 0) {
/* bytes can also be -2 ("bad packet data") */
if (bytes == -1 && errno != EINTR) {
log1("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
close(server_socket);
server_socket = -1;
}
continue;
}
if (packet.hlen != 6) {
bb_error_msg("MAC length != 6, ignoring packet");
continue;
}
if (packet.op != BOOTREQUEST) {
bb_error_msg("not a REQUEST, ignoring packet");
continue;
}
state = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (state == NULL || state[0] < DHCP_MINTYPE || state[0] > DHCP_MAXTYPE) {
bb_error_msg("no or bad message type option, ignoring packet");
continue;
}
/* Get SERVER_ID if present */
server_id_opt = udhcp_get_option32(&packet, DHCP_SERVER_ID);
if (server_id_opt) {
uint32_t server_id_network_order;
move_from_unaligned32(server_id_network_order, server_id_opt);
if (server_id_network_order != server_config.server_nip) {
/* client talks to somebody else */
log1("server ID doesn't match, ignoring");
continue;
}
}
/* Look for a static/dynamic lease */
static_lease_nip = get_static_nip_by_mac(server_config.static_leases, &packet.chaddr);
if (static_lease_nip) {
bb_error_msg("found static lease: %x", static_lease_nip);
memcpy(&fake_lease.lease_mac, &packet.chaddr, 6);
fake_lease.lease_nip = static_lease_nip;
fake_lease.expires = 0;
lease = &fake_lease;
} else {
lease = find_lease_by_mac(packet.chaddr);
}
/* Get REQUESTED_IP if present */
requested_ip_opt = udhcp_get_option32(&packet, DHCP_REQUESTED_IP);
if (requested_ip_opt) {
move_from_unaligned32(requested_nip, requested_ip_opt);
}
switch (state[0]) {
case DHCPDISCOVER:
log1("received %s", "DISCOVER");
send_offer(&packet, static_lease_nip, lease, requested_ip_opt, arpping_ms);
break;
case DHCPREQUEST:
log1("received %s", "REQUEST");
/* RFC 2131:
o DHCPREQUEST generated during SELECTING state:
Client inserts the address of the selected server in 'server
identifier', 'ciaddr' MUST be zero, 'requested IP address' MUST be
filled in with the yiaddr value from the chosen DHCPOFFER.
Note that the client may choose to collect several DHCPOFFER
messages and select the "best" offer. The client indicates its
selection by identifying the offering server in the DHCPREQUEST
message. If the client receives no acceptable offers, the client
may choose to try another DHCPDISCOVER message. Therefore, the
servers may not receive a specific DHCPREQUEST from which they can
decide whether or not the client has accepted the offer.
o DHCPREQUEST generated during INIT-REBOOT state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST be filled in with client's notion of its previously
assigned address. 'ciaddr' MUST be zero. The client is seeking to
verify a previously allocated, cached configuration. Server SHOULD
send a DHCPNAK message to the client if the 'requested IP address'
is incorrect, or is on the wrong network.
Determining whether a client in the INIT-REBOOT state is on the
correct network is done by examining the contents of 'giaddr', the
'requested IP address' option, and a database lookup. If the DHCP
server detects that the client is on the wrong net (i.e., the
result of applying the local subnet mask or remote subnet mask (if
'giaddr' is not zero) to 'requested IP address' option value
doesn't match reality), then the server SHOULD send a DHCPNAK
message to the client.
If the network is correct, then the DHCP server should check if
the client's notion of its IP address is correct. If not, then the
server SHOULD send a DHCPNAK message to the client. If the DHCP
server has no record of this client, then it MUST remain silent,
and MAY output a warning to the network administrator. This
behavior is necessary for peaceful coexistence of non-
communicating DHCP servers on the same wire.
If 'giaddr' is 0x0 in the DHCPREQUEST message, the client is on
the same subnet as the server. The server MUST broadcast the
DHCPNAK message to the 0xffffffff broadcast address because the
client may not have a correct network address or subnet mask, and
the client may not be answering ARP requests.
If 'giaddr' is set in the DHCPREQUEST message, the client is on a
different subnet. The server MUST set the broadcast bit in the
DHCPNAK, so that the relay agent will broadcast the DHCPNAK to the
client, because the client may not have a correct network address
or subnet mask, and the client may not be answering ARP requests.
o DHCPREQUEST generated during RENEWING state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST NOT be filled in, 'ciaddr' MUST be filled in with
client's IP address. In this situation, the client is completely
configured, and is trying to extend its lease. This message will
be unicast, so no relay agents will be involved in its
transmission. Because 'giaddr' is therefore not filled in, the
DHCP server will trust the value in 'ciaddr', and use it when
replying to the client.
A client MAY choose to renew or extend its lease prior to T1. The
server may choose not to extend the lease (as a policy decision by
the network administrator), but should return a DHCPACK message
regardless.
o DHCPREQUEST generated during REBINDING state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST NOT be filled in, 'ciaddr' MUST be filled in with
client's IP address. In this situation, the client is completely
configured, and is trying to extend its lease. This message MUST
be broadcast to the 0xffffffff IP broadcast address. The DHCP
server SHOULD check 'ciaddr' for correctness before replying to
the DHCPREQUEST.
The DHCPREQUEST from a REBINDING client is intended to accommodate
sites that have multiple DHCP servers and a mechanism for
maintaining consistency among leases managed by multiple servers.
A DHCP server MAY extend a client's lease only if it has local
administrative authority to do so.
*/
if (!requested_ip_opt) {
requested_nip = packet.ciaddr;
if (requested_nip == 0) {
log1("no requested IP and no ciaddr, ignoring");
break;
}
}
if (lease && requested_nip == lease->lease_nip) {
/* client requested or configured IP matches the lease.
* ACK it, and bump lease expiration time. */
send_ACK(&packet, lease->lease_nip);
break;
}
/* No lease for this MAC, or lease IP != requested IP */
if (server_id_opt /* client is in SELECTING state */
|| requested_ip_opt /* client is in INIT-REBOOT state */
) {
/* "No, we don't have this IP for you" */
send_NAK(&packet);
} /* else: client is in RENEWING or REBINDING, do not answer */
break;
case DHCPDECLINE:
/* RFC 2131:
* "If the server receives a DHCPDECLINE message,
* the client has discovered through some other means
* that the suggested network address is already
* in use. The server MUST mark the network address
* as not available and SHOULD notify the local
* sysadmin of a possible configuration problem."
*
* SERVER_ID must be present,
* REQUESTED_IP must be present,
* chaddr must be filled in,
* ciaddr must be 0 (we do not check this)
*/
log1("received %s", "DECLINE");
if (server_id_opt
&& requested_ip_opt
&& lease /* chaddr matches this lease */
&& requested_nip == lease->lease_nip
) {
memset(lease->lease_mac, 0, sizeof(lease->lease_mac));
lease->expires = time(NULL) + server_config.decline_time;
}
break;
case DHCPRELEASE:
/* "Upon receipt of a DHCPRELEASE message, the server
* marks the network address as not allocated."
*
* SERVER_ID must be present,
* REQUESTED_IP must not be present (we do not check this),
* chaddr must be filled in,
* ciaddr must be filled in
*/
log1("received %s", "RELEASE");
if (server_id_opt
&& lease /* chaddr matches this lease */
&& packet.ciaddr == lease->lease_nip
) {
lease->expires = time(NULL);
}
break;
case DHCPINFORM:
log1("received %s", "INFORM");
send_inform(&packet);
break;
}
}
ret0:
retval = 0;
ret:
/*if (server_config.pidfile) - server_config.pidfile is never NULL */
remove_pidfile(server_config.pidfile);
return retval;
}
|
CVE-2018-20679
|
CWE-125
|
An issue was discovered in BusyBox before 1.30.0. An out of bounds read in udhcp components (consumed by the DHCP server, client, and relay) allows a remote attacker to leak sensitive information from the stack by sending a crafted DHCP message. This is related to verification in udhcp_get_option() in networking/udhcp/common.c that 4-byte options are indeed 4 bytes.
|
https://git.busybox.net/busybox/commit/?id=6d3b4bb24da9a07c263f3c1acf8df85382ff562c
|
udhcpc: check that 4-byte options are indeed 4-byte, closes 11506
function old new delta
udhcp_get_option32 - 27 +27
udhcp_get_option 231 248 +17
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 44/0) Total: 44 bytes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
| null | null | null |
static int decode_rle(AVCodecContext *avctx, AVFrame *p, GetByteContext *gbc,
int step)
{
int i, j;
int offset = avctx->width * step;
uint8_t *outdata = p->data[0];
for (i = 0; i < avctx->height; i++) {
int size, left, code, pix;
uint8_t *out = outdata;
int pos = 0;
size = left = bytestream2_get_be16(gbc);
if (bytestream2_get_bytes_left(gbc) < size)
while (left > 0) {
code = bytestream2_get_byte(gbc);
if (code & 0x80 ) {
pix = bytestream2_get_byte(gbc);
for (j = 0; j < 257 - code; j++) {
out[pos] = pix;
pos += step;
if (pos >= offset) {
pos -= offset;
pos++;
}
}
left -= 2;
} else {
for (j = 0; j < code + 1; j++) {
out[pos] = bytestream2_get_byte(gbc);
pos += step;
if (pos >= offset) {
pos -= offset;
pos++;
}
}
left -= 2 + code;
}
}
outdata += p->linesize[0];
}
return 0;
}
|
static int decode_rle(AVCodecContext *avctx, AVFrame *p, GetByteContext *gbc,
int step)
{
int i, j;
int offset = avctx->width * step;
uint8_t *outdata = p->data[0];
for (i = 0; i < avctx->height; i++) {
int size, left, code, pix;
uint8_t *out = outdata;
int pos = 0;
size = left = bytestream2_get_be16(gbc);
if (bytestream2_get_bytes_left(gbc) < size)
return AVERROR_INVALIDDATA;
while (left > 0) {
code = bytestream2_get_byte(gbc);
if (code & 0x80 ) {
pix = bytestream2_get_byte(gbc);
for (j = 0; j < 257 - code; j++) {
out[pos] = pix;
pos += step;
if (pos >= offset) {
pos -= offset;
pos++;
}
if (pos >= offset)
return AVERROR_INVALIDDATA;
}
left -= 2;
} else {
for (j = 0; j < code + 1; j++) {
out[pos] = bytestream2_get_byte(gbc);
pos += step;
if (pos >= offset) {
pos -= offset;
pos++;
}
if (pos >= offset)
return AVERROR_INVALIDDATA;
}
left -= 2 + code;
}
}
outdata += p->linesize[0];
}
return 0;
}
| null | null | null |
FFmpeg/commit/1eda55510ae5d15ce3df9f496002508580899045
|
lavc/qdrw: Fix overwrite when reading invalid Quickdraw images.
|
./ffmpeg/libavcodec/qdrw.c
|
c
|
2015-05-16T20:51:16Z
|
public static void handleRecipe(IRecipeHandler recipe, int index, List<Object[]> inputs, List<Object[]> outputs) {
// raw inputs
recipe.getIngredientStacks(index)
.stream()
.map((positionedStack) -> (Object[]) positionedStack.items)
.forEach(inputs::add);
// raw outputs
PositionedStack resultStack = recipe.getResultStack(index);
if (resultStack != null)
outputs.add(resultStack.items);
for (IAdapter adapter : adapters) {
adapter.handleRecipe(recipe, index, inputs, outputs);
}
}
|
public static void handleRecipe(IRecipeHandler recipe, int index, List<Object[]> inputs, List<Object[]> outputs) {
// raw inputs
recipe.getIngredientStacks(index)
.stream()
.map((positionedStack) -> (Object[]) positionedStack.items)
.forEach(inputs::add);
// raw outputs
PositionedStack resultStack = recipe.getResultStack(index);
if (resultStack != null)
outputs.add(resultStack.items);
try {
for (IAdapter adapter : adapters) {
adapter.handleRecipe(recipe, index, inputs, outputs);
}
} catch (Exception e) {
Utilities.addChatMessage(Utilities.ChatMessage.RECIPE_TRANSFER_ERROR);
JustEnoughCalculation.logger.error("Exception when handling recipe: " + recipe.getClass().getName());
e.printStackTrace();
}
}
| null | null | null |
https://github.com/Towdium/JustEnoughCalculation/commit/903743d0a3e350ddc45732851b4c9ecabe5d1e36
|
Fix crash when transferring recipe
|
src/main/java/me/towdium/jecalculation/nei/Adapter.java
|
java
|
2022-11-18T09:04:41Z
|
exo_open_launch_desktop_file (const gchar *arg)
{
#ifdef HAVE_GIO_UNIX
GFile *gfile;
gchar *contents;
gsize length;
gboolean result;
GKeyFile *key_file;
GDesktopAppInfo *appinfo;
/* try to open a file from the arguments */
gfile = g_file_new_for_commandline_arg (arg);
if (G_UNLIKELY (gfile == NULL))
return FALSE;
/* load the contents of the file */
result = g_file_load_contents (gfile, NULL, &contents, &length, NULL, NULL);
g_object_unref (G_OBJECT (gfile));
if (G_UNLIKELY (!result || length == 0))
return FALSE;
/* create the key file */
key_file = g_key_file_new ();
result = g_key_file_load_from_data (key_file, contents, length, G_KEY_FILE_NONE, NULL);
g_free (contents);
if (G_UNLIKELY (!result))
{
g_key_file_free (key_file);
return FALSE;
}
/* create the appinfo */
appinfo = g_desktop_app_info_new_from_keyfile (key_file);
g_key_file_free (key_file);
if (G_UNLIKELY (appinfo == NULL))
return FALSE;
/* try to launch a (non-hidden) desktop file */
if (G_LIKELY (!g_desktop_app_info_get_is_hidden (appinfo)))
result = g_app_info_launch (G_APP_INFO (appinfo), NULL, NULL, NULL);
else
result = FALSE;
g_object_unref (G_OBJECT (appinfo));
#ifndef NDEBUG
g_debug ("launching desktop file %s", result ? "succeeded" : "failed");
#endif
return result;
#else /* !HAVE_GIO_UNIX */
g_critical (_("Launching desktop files is not supported when %s is compiled "
"without GIO-Unix features."), g_get_prgname ());
return FALSE;
#endif
}
|
exo_open_launch_desktop_file (const gchar *arg)
{
#ifdef HAVE_GIO_UNIX
GFile *gfile;
gchar *contents;
gsize length;
gboolean result;
GKeyFile *key_file;
GDesktopAppInfo *appinfo;
/* try to open a file from the arguments */
gfile = g_file_new_for_commandline_arg (arg);
if (G_UNLIKELY (gfile == NULL))
return FALSE;
/* Only execute local .desktop files to prevent execution of malicious launchers from foreign locations */
if (g_file_has_uri_scheme (gfile, "file") == FALSE)
{
char *uri = g_file_get_uri (gfile);
g_warning ("Execution of remote .desktop file '%s' was skipped due to security concerns.", uri);
g_object_unref (gfile);
g_free (uri);
return FALSE;
}
/* load the contents of the file */
result = g_file_load_contents (gfile, NULL, &contents, &length, NULL, NULL);
g_object_unref (G_OBJECT (gfile));
if (G_UNLIKELY (!result || length == 0))
return FALSE;
/* create the key file */
key_file = g_key_file_new ();
result = g_key_file_load_from_data (key_file, contents, length, G_KEY_FILE_NONE, NULL);
g_free (contents);
if (G_UNLIKELY (!result))
{
g_key_file_free (key_file);
return FALSE;
}
/* create the appinfo */
appinfo = g_desktop_app_info_new_from_keyfile (key_file);
g_key_file_free (key_file);
if (G_UNLIKELY (appinfo == NULL))
return FALSE;
/* try to launch a (non-hidden) desktop file */
if (G_LIKELY (!g_desktop_app_info_get_is_hidden (appinfo)))
result = g_app_info_launch (G_APP_INFO (appinfo), NULL, NULL, NULL);
else
result = FALSE;
g_object_unref (G_OBJECT (appinfo));
#ifndef NDEBUG
g_debug ("launching desktop file %s", result ? "succeeded" : "failed");
#endif
return result;
#else /* !HAVE_GIO_UNIX */
g_critical (_("Launching desktop files is not supported when %s is compiled "
"without GIO-Unix features."), g_get_prgname ());
return FALSE;
#endif
}
| null |
CWE-94
| null |
https://github.com/xfce-mirror/exo/commit/c71c04ff5882b2866a0d8506fb460d4ef796de9f
|
exo-open : Only execute local .desktop files
Issue #85 (Backported cc047717)
CVE-2022-32278
This patch prevents executing possibly malicious .desktop files
from online sources (ftp://, http:// etc.).
Original patch authored by Alexander Schwinn <alexxcons@xfce.org>
| null | null |
2022-06-06T14:57:03Z
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.