instruction
stringclasses 1
value | input
stringlengths 90
114k
| output
stringlengths 16
114k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: ext4_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19 | ext4_xattr_put_super(struct super_block *sb)
| 169,995 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void fe_netjoin_deinit(void)
{
while (joinservers != NULL)
netjoin_server_remove(joinservers->data);
if (join_tag != -1) {
g_source_remove(join_tag);
signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting);
}
signal_remove("setup changed", (SIGNAL_FUNC) read_settings);
signal_remove("message quit", (SIGNAL_FUNC) msg_quit);
signal_remove("message join", (SIGNAL_FUNC) msg_join);
signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode);
}
Commit Message: Merge branch 'netjoin-timeout' into 'master'
fe-netjoin: remove irc servers on "server disconnected" signal
Closes #7
See merge request !10
CWE ID: CWE-416 | void fe_netjoin_deinit(void)
{
while (joinservers != NULL)
netjoin_server_remove(joinservers->data);
if (join_tag != -1) {
g_source_remove(join_tag);
signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting);
}
signal_remove("setup changed", (SIGNAL_FUNC) read_settings);
signal_remove("server disconnected", (SIGNAL_FUNC) sig_server_disconnected);
signal_remove("message quit", (SIGNAL_FUNC) msg_quit);
signal_remove("message join", (SIGNAL_FUNC) msg_join);
signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode);
}
| 168,290 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: WORD32 ih264d_create(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
ih264d_create_op_t *ps_create_op;
WORD32 ret;
ps_create_op = (ih264d_create_op_t *)pv_api_op;
ps_create_op->s_ivd_create_op_t.u4_error_code = 0;
ret = ih264d_allocate_static_bufs(&dec_hdl, pv_api_ip, pv_api_op);
/* If allocation of some buffer fails, then free buffers allocated till then */
if((IV_FAIL == ret) && (NULL != dec_hdl))
{
ih264d_free_static_bufs(dec_hdl);
ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED;
ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR;
return IV_FAIL;
}
return IV_SUCCESS;
}
Commit Message: Decoder: Handle dec_hdl memory allocation failure gracefully
If memory allocation for dec_hdl fails, return gracefully
with an error code. All other allocation failures are
handled correctly.
Bug: 68300072
Test: ran poc before/after
Change-Id: I118ae71f4aded658441f1932bd4ede3536f5028b
(cherry picked from commit 7720b3fe3de04523da3a9ecec2b42a3748529bbd)
CWE ID: CWE-770 | WORD32 ih264d_create(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
ih264d_create_ip_t *ps_create_ip;
ih264d_create_op_t *ps_create_op;
WORD32 ret;
ps_create_ip = (ih264d_create_ip_t *)pv_api_ip;
ps_create_op = (ih264d_create_op_t *)pv_api_op;
ps_create_op->s_ivd_create_op_t.u4_error_code = 0;
dec_hdl = NULL;
ret = ih264d_allocate_static_bufs(&dec_hdl, pv_api_ip, pv_api_op);
/* If allocation of some buffer fails, then free buffers allocated till then */
if(IV_FAIL == ret)
{
if(dec_hdl)
{
if(dec_hdl->pv_codec_handle)
{
ih264d_free_static_bufs(dec_hdl);
}
else
{
void (*pf_aligned_free)(void *pv_mem_ctxt, void *pv_buf);
void *pv_mem_ctxt;
pf_aligned_free = ps_create_ip->s_ivd_create_ip_t.pf_aligned_free;
pv_mem_ctxt = ps_create_ip->s_ivd_create_ip_t.pv_mem_ctxt;
pf_aligned_free(pv_mem_ctxt, dec_hdl);
}
}
ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED;
ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR;
return IV_FAIL;
}
return IV_SUCCESS;
}
| 174,112 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: main( int argc,
char* argv[] )
{
int old_ptsize, orig_ptsize, file;
int first_glyph = 0;
int XisSetup = 0;
char* execname;
int option;
int file_loaded;
grEvent event;
execname = ft_basename( argv[0] );
while ( 1 )
{
option = getopt( argc, argv, "d:e:f:r:" );
if ( option == -1 )
break;
switch ( option )
{
case 'd':
parse_design_coords( optarg );
break;
case 'e':
encoding = (FT_Encoding)make_tag( optarg );
break;
case 'f':
first_glyph = atoi( optarg );
break;
case 'r':
res = atoi( optarg );
if ( res < 1 )
usage( execname );
break;
default:
usage( execname );
break;
}
}
argc -= optind;
argv += optind;
if ( argc <= 1 )
usage( execname );
if ( sscanf( argv[0], "%d", &orig_ptsize ) != 1 )
orig_ptsize = 64;
file = 1;
/* Initialize engine */
error = FT_Init_FreeType( &library );
if ( error )
PanicZ( "Could not initialize FreeType library" );
NewFile:
ptsize = orig_ptsize;
hinted = 1;
file_loaded = 0;
/* Load face */
error = FT_New_Face( library, argv[file], 0, &face );
if ( error )
goto Display_Font;
if ( encoding != FT_ENCODING_NONE )
{
error = FT_Select_Charmap( face, encoding );
if ( error )
goto Display_Font;
}
/* retrieve multiple master information */
error = FT_Get_MM_Var( face, &multimaster );
if ( error )
goto Display_Font;
/* if the user specified a position, use it, otherwise */
/* set the current position to the median of each axis */
{
int n;
for ( n = 0; n < (int)multimaster->num_axis; n++ )
{
design_pos[n] = n < requested_cnt ? requested_pos[n]
: multimaster->axis[n].def;
if ( design_pos[n] < multimaster->axis[n].minimum )
design_pos[n] = multimaster->axis[n].minimum;
else if ( design_pos[n] > multimaster->axis[n].maximum )
design_pos[n] = multimaster->axis[n].maximum;
}
}
error = FT_Set_Var_Design_Coordinates( face,
multimaster->num_axis,
design_pos );
if ( error )
goto Display_Font;
file_loaded++;
Reset_Scale( ptsize );
num_glyphs = face->num_glyphs;
glyph = face->glyph;
size = face->size;
Display_Font:
/* initialize graphics if needed */
if ( !XisSetup )
{
XisSetup = 1;
Init_Display();
}
grSetTitle( surface, "FreeType Glyph Viewer - press F1 for help" );
old_ptsize = ptsize;
if ( file_loaded >= 1 )
{
Fail = 0;
Num = first_glyph;
if ( Num >= num_glyphs )
Num = num_glyphs - 1;
if ( Num < 0 )
Num = 0;
}
for ( ;; )
{
int key;
Clear_Display();
if ( file_loaded >= 1 )
{
switch ( render_mode )
{
case 0:
Render_Text( Num );
break;
default:
Render_All( Num, ptsize );
}
sprintf( Header, "%s %s (file %s)",
face->family_name,
face->style_name,
ft_basename( argv[file] ) );
if ( !new_header )
new_header = Header;
grWriteCellString( &bit, 0, 0, new_header, fore_color );
new_header = 0;
sprintf( Header, "axis: " );
{
int n;
for ( n = 0; n < (int)multimaster->num_axis; n++ )
{
char temp[32];
sprintf( temp, " %s:%g",
multimaster->axis[n].name,
design_pos[n]/65536. );
strcat( Header, temp );
}
}
grWriteCellString( &bit, 0, 16, Header, fore_color );
sprintf( Header, "at %d points, first glyph = %d",
ptsize,
Num );
}
else
{
sprintf( Header, "%s: not an MM font file, or could not be opened",
ft_basename( argv[file] ) );
}
grWriteCellString( &bit, 0, 8, Header, fore_color );
grRefreshSurface( surface );
grListenSurface( surface, 0, &event );
if ( !( key = Process_Event( &event ) ) )
goto End;
if ( key == 'n' )
{
if ( file_loaded >= 1 )
FT_Done_Face( face );
if ( file < argc - 1 )
file++;
goto NewFile;
}
if ( key == 'p' )
{
if ( file_loaded >= 1 )
FT_Done_Face( face );
if ( file > 1 )
file--;
goto NewFile;
}
if ( ptsize != old_ptsize )
{
Reset_Scale( ptsize );
old_ptsize = ptsize;
}
}
End:
grDoneSurface( surface );
grDoneDevices();
free ( multimaster );
FT_Done_Face ( face );
FT_Done_FreeType( library );
printf( "Execution completed successfully.\n" );
printf( "Fails = %d\n", Fail );
exit( 0 ); /* for safety reasons */
return 0; /* never reached */
}
Commit Message:
CWE ID: CWE-119 | main( int argc,
char* argv[] )
{
int old_ptsize, orig_ptsize, file;
int first_glyph = 0;
int XisSetup = 0;
char* execname;
int option;
int file_loaded;
grEvent event;
execname = ft_basename( argv[0] );
while ( 1 )
{
option = getopt( argc, argv, "d:e:f:r:" );
if ( option == -1 )
break;
switch ( option )
{
case 'd':
parse_design_coords( optarg );
break;
case 'e':
encoding = (FT_Encoding)make_tag( optarg );
break;
case 'f':
first_glyph = atoi( optarg );
break;
case 'r':
res = atoi( optarg );
if ( res < 1 )
usage( execname );
break;
default:
usage( execname );
break;
}
}
argc -= optind;
argv += optind;
if ( argc <= 1 )
usage( execname );
if ( sscanf( argv[0], "%d", &orig_ptsize ) != 1 )
orig_ptsize = 64;
file = 1;
/* Initialize engine */
error = FT_Init_FreeType( &library );
if ( error )
PanicZ( "Could not initialize FreeType library" );
NewFile:
ptsize = orig_ptsize;
hinted = 1;
file_loaded = 0;
/* Load face */
error = FT_New_Face( library, argv[file], 0, &face );
if ( error )
goto Display_Font;
if ( encoding != FT_ENCODING_NONE )
{
error = FT_Select_Charmap( face, encoding );
if ( error )
goto Display_Font;
}
/* retrieve multiple master information */
error = FT_Get_MM_Var( face, &multimaster );
if ( error )
goto Display_Font;
/* if the user specified a position, use it, otherwise */
/* set the current position to the median of each axis */
{
int n;
for ( n = 0; n < (int)multimaster->num_axis; n++ )
{
design_pos[n] = n < requested_cnt ? requested_pos[n]
: multimaster->axis[n].def;
if ( design_pos[n] < multimaster->axis[n].minimum )
design_pos[n] = multimaster->axis[n].minimum;
else if ( design_pos[n] > multimaster->axis[n].maximum )
design_pos[n] = multimaster->axis[n].maximum;
}
}
error = FT_Set_Var_Design_Coordinates( face,
multimaster->num_axis,
design_pos );
if ( error )
goto Display_Font;
file_loaded++;
Reset_Scale( ptsize );
num_glyphs = face->num_glyphs;
glyph = face->glyph;
size = face->size;
Display_Font:
/* initialize graphics if needed */
if ( !XisSetup )
{
XisSetup = 1;
Init_Display();
}
grSetTitle( surface, "FreeType Glyph Viewer - press F1 for help" );
old_ptsize = ptsize;
if ( file_loaded >= 1 )
{
Fail = 0;
Num = first_glyph;
if ( Num >= num_glyphs )
Num = num_glyphs - 1;
if ( Num < 0 )
Num = 0;
}
for ( ;; )
{
int key;
Clear_Display();
if ( file_loaded >= 1 )
{
switch ( render_mode )
{
case 0:
Render_Text( Num );
break;
default:
Render_All( Num, ptsize );
}
sprintf( Header, "%.50s %.50s (file %.100s)",
face->family_name,
face->style_name,
ft_basename( argv[file] ) );
if ( !new_header )
new_header = Header;
grWriteCellString( &bit, 0, 0, new_header, fore_color );
new_header = 0;
sprintf( Header, "axis: " );
{
int n;
for ( n = 0; n < (int)multimaster->num_axis; n++ )
{
char temp[32];
sprintf( temp, " %s:%g",
multimaster->axis[n].name,
design_pos[n]/65536. );
strcat( Header, temp );
}
}
grWriteCellString( &bit, 0, 16, Header, fore_color );
sprintf( Header, "at %d points, first glyph = %d",
ptsize,
Num );
}
else
{
sprintf( Header, "%.100s: not an MM font file, or could not be opened",
ft_basename( argv[file] ) );
}
grWriteCellString( &bit, 0, 8, Header, fore_color );
grRefreshSurface( surface );
grListenSurface( surface, 0, &event );
if ( !( key = Process_Event( &event ) ) )
goto End;
if ( key == 'n' )
{
if ( file_loaded >= 1 )
FT_Done_Face( face );
if ( file < argc - 1 )
file++;
goto NewFile;
}
if ( key == 'p' )
{
if ( file_loaded >= 1 )
FT_Done_Face( face );
if ( file > 1 )
file--;
goto NewFile;
}
if ( ptsize != old_ptsize )
{
Reset_Scale( ptsize );
old_ptsize = ptsize;
}
}
End:
grDoneSurface( surface );
grDoneDevices();
free ( multimaster );
FT_Done_Face ( face );
FT_Done_FreeType( library );
printf( "Execution completed successfully.\n" );
printf( "Fails = %d\n", Fail );
exit( 0 ); /* for safety reasons */
return 0; /* never reached */
}
| 164,999 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
int do_rf64 = 0, write_junk = 1;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_riff_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so rf64", total_data_bytes);
write_junk = 0;
do_rf64 = 1;
}
else if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so riff", total_data_bytes);
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1);
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk);
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk))) ||
(write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
return TRUE;
}
Commit Message: issue #27, do not overwrite stack on corrupt RF64 file
CWE ID: CWE-119 | int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
int do_rf64 = 0, write_junk = 1, table_length = 0;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
CS64Chunk cs64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_riff_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so rf64", total_data_bytes);
write_junk = 0;
do_rf64 = 1;
}
else if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so riff", total_data_bytes);
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1);
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
total_riff_bytes += table_length * sizeof (CS64Chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk));
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
ds64_chunk.tableLength = table_length;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
// this "table" is just a dummy placeholder for testing (normally not written)
if (table_length) {
strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID));
cs64_chunk.chunkSize64 = 12345678;
WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat);
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
// again, this is normally not written except for testing
while (table_length--)
if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
return TRUE;
}
| 169,335 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits)
{
stream_t *ps_stream = (stream_t *)pv_ctxt;
if (ps_stream->u4_offset < ps_stream->u4_max_offset)
{
FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned)
}
return;
}
Commit Message: Fixed out of bound read in flush_bits
Bug: 28168413
Change-Id: I3db5432a08daf665e160c0dab2d1928a576418b4
CWE ID: CWE-200 | INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits)
{
stream_t *ps_stream = (stream_t *)pv_ctxt;
if ((ps_stream->u4_offset + 64) < ps_stream->u4_max_offset)
{
FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned)
}
else
{
UWORD32 u4_temp;
if (((ps_stream->u4_offset & 0x1f) + u4_no_of_bits) >= 32)
{
ps_stream->u4_buf = ps_stream->u4_buf_nxt;
ps_stream->u4_buf_nxt = 0;
}
ps_stream->u4_offset += u4_no_of_bits;
}
return;
}
| 173,549 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: log2vis_encoded_string (PyObject * string, const char *encoding,
FriBidiParType base_direction, int clean, int reordernsm)
{
PyObject *logical = NULL; /* logical unicode object */
PyObject *result = NULL; /* output string object */
/* Always needed for the string length */
logical = PyUnicode_Decode (PyString_AS_STRING (string),
PyString_GET_SIZE (string),
encoding, "strict");
if (logical == NULL)
return NULL;
if (strcmp (encoding, "utf-8") == 0)
/* Shortcut for utf8 strings (little faster) */
result = log2vis_utf8 (string,
PyUnicode_GET_SIZE (logical),
base_direction, clean, reordernsm);
else
{
/* Invoke log2vis_unicode and encode back to encoding */
PyObject *visual = log2vis_unicode (logical, base_direction, clean, reordernsm);
if (visual)
{
result = PyUnicode_Encode (PyUnicode_AS_UNICODE
(visual),
PyUnicode_GET_SIZE (visual),
encoding, "strict");
Py_DECREF (visual);
}
}
Py_DECREF (logical);
return result;
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119 | log2vis_encoded_string (PyObject * string, const char *encoding,
| 165,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: ossl_cipher_set_key(VALUE self, VALUE key)
{
EVP_CIPHER_CTX *ctx;
int key_len;
StringValue(key);
GetCipher(self, ctx);
key_len = EVP_CIPHER_CTX_key_length(ctx);
if (RSTRING_LEN(key) != key_len)
ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
return key;
}
Commit Message: cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49
CWE ID: CWE-310 | ossl_cipher_set_key(VALUE self, VALUE key)
{
EVP_CIPHER_CTX *ctx;
int key_len;
StringValue(key);
GetCipher(self, ctx);
key_len = EVP_CIPHER_CTX_key_length(ctx);
if (RSTRING_LEN(key) != key_len)
ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
rb_ivar_set(self, id_key_set, Qtrue);
return key;
}
| 168,782 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void traverse_commit_list(struct rev_info *revs,
show_commit_fn show_commit,
show_object_fn show_object,
void *data)
{
int i;
struct commit *commit;
struct strbuf base;
strbuf_init(&base, PATH_MAX);
while ((commit = get_revision(revs)) != NULL) {
/*
* an uninteresting boundary commit may not have its tree
* parsed yet, but we are not going to show them anyway
*/
if (commit->tree)
add_pending_tree(revs, commit->tree);
show_commit(commit, data);
}
for (i = 0; i < revs->pending.nr; i++) {
struct object_array_entry *pending = revs->pending.objects + i;
struct object *obj = pending->item;
const char *name = pending->name;
const char *path = pending->path;
if (obj->flags & (UNINTERESTING | SEEN))
continue;
if (obj->type == OBJ_TAG) {
obj->flags |= SEEN;
show_object(obj, NULL, name, data);
continue;
}
if (!path)
path = "";
if (obj->type == OBJ_TREE) {
process_tree(revs, (struct tree *)obj, show_object,
&base, path, data);
continue;
}
if (obj->type == OBJ_BLOB) {
process_blob(revs, (struct blob *)obj, show_object,
NULL, path, data);
continue;
}
die("unknown pending object %s (%s)",
oid_to_hex(&obj->oid), name);
}
object_array_clear(&revs->pending);
strbuf_release(&base);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
CWE ID: CWE-119 | void traverse_commit_list(struct rev_info *revs,
show_commit_fn show_commit,
show_object_fn show_object,
void *data)
{
int i;
struct commit *commit;
struct strbuf base;
strbuf_init(&base, PATH_MAX);
while ((commit = get_revision(revs)) != NULL) {
/*
* an uninteresting boundary commit may not have its tree
* parsed yet, but we are not going to show them anyway
*/
if (commit->tree)
add_pending_tree(revs, commit->tree);
show_commit(commit, data);
}
for (i = 0; i < revs->pending.nr; i++) {
struct object_array_entry *pending = revs->pending.objects + i;
struct object *obj = pending->item;
const char *name = pending->name;
const char *path = pending->path;
if (obj->flags & (UNINTERESTING | SEEN))
continue;
if (obj->type == OBJ_TAG) {
obj->flags |= SEEN;
show_object(obj, name, data);
continue;
}
if (!path)
path = "";
if (obj->type == OBJ_TREE) {
process_tree(revs, (struct tree *)obj, show_object,
&base, path, data);
continue;
}
if (obj->type == OBJ_BLOB) {
process_blob(revs, (struct blob *)obj, show_object,
&base, path, data);
continue;
}
die("unknown pending object %s (%s)",
oid_to_hex(&obj->oid), name);
}
object_array_clear(&revs->pending);
strbuf_release(&base);
}
| 167,420 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: StyleResolver::StyleResolver(Document& document)
: m_document(document)
, m_fontSelector(CSSFontSelector::create(&document))
, m_viewportStyleResolver(ViewportStyleResolver::create(&document))
, m_styleResourceLoader(document.fetcher())
, m_styleResolverStatsSequence(0)
, m_accessCount(0)
{
Element* root = document.documentElement();
m_fontSelector->registerForInvalidationCallbacks(this);
CSSDefaultStyleSheets::initDefaultStyle(root);
FrameView* view = document.view();
if (view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
else
m_medium = adoptPtr(new MediaQueryEvaluator("all"));
if (root)
m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
if (m_rootDefaultStyle && view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get()));
m_styleTree.clear();
initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors());
#if ENABLE(SVG_FONTS)
if (document.svgExtensions()) {
const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements();
HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
fontSelector()->addFontFaceRule((*it)->fontFaceRule());
}
#endif
document.styleEngine()->appendActiveAuthorStyleSheets(this);
}
Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun.
We've been bitten by the Simple Default Stylesheet being out
of sync with the real html.css twice this week.
The Simple Default Stylesheet was invented years ago for Mac:
http://trac.webkit.org/changeset/36135
It nicely handles the case where you just want to create
a single WebView and parse some simple HTML either without
styling said HTML, or only to display a small string, etc.
Note that this optimization/complexity *only* helps for the
very first document, since the default stylesheets are
all static (process-global) variables. Since any real page
on the internet uses a tag not covered by the simple default
stylesheet, not real load benefits from this optimization.
Only uses of WebView which were just rendering small bits
of text might have benefited from this. about:blank would
also have used this sheet.
This was a common application for some uses of WebView back
in those days. These days, even with WebView on Android,
there are likely much larger overheads than parsing the
html.css stylesheet, so making it required seems like the
right tradeoff of code-simplicity for this case.
BUG=319556
Review URL: https://codereview.chromium.org/73723005
git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | StyleResolver::StyleResolver(Document& document)
: m_document(document)
, m_fontSelector(CSSFontSelector::create(&document))
, m_viewportStyleResolver(ViewportStyleResolver::create(&document))
, m_styleResourceLoader(document.fetcher())
, m_styleResolverStatsSequence(0)
, m_accessCount(0)
{
m_fontSelector->registerForInvalidationCallbacks(this);
// FIXME: Why do this here instead of as part of resolving style on the root?
CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary();
// Construct document root element default style. This is needed
// This is here instead of constructor because when constructor is run,
// Document doesn't have documentElement.
// NOTE: This assumes that element that gets passed to the styleForElement call
// is always from the document that owns the StyleResolver.
FrameView* view = document.view();
if (view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
else
m_medium = adoptPtr(new MediaQueryEvaluator("all"));
Element* root = document.documentElement();
if (root)
m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
if (m_rootDefaultStyle && view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get()));
m_styleTree.clear();
initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors());
#if ENABLE(SVG_FONTS)
if (document.svgExtensions()) {
const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements();
HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
fontSelector()->addFontFaceRule((*it)->fontFaceRule());
}
#endif
document.styleEngine()->appendActiveAuthorStyleSheets(this);
}
| 171,584 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) {
const xmlChar *in;
int nbchar = 0;
int line = ctxt->input->line;
int col = ctxt->input->col;
int ccol;
SHRINK;
GROW;
/*
* Accelerated common case where input don't need to be
* modified before passing it to the handler.
*/
if (!cdata) {
in = ctxt->input->cur;
do {
get_more_space:
while (*in == 0x20) { in++; ctxt->input->col++; }
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more_space;
}
if (*in == '<') {
nbchar = in - ctxt->input->cur;
if (nbchar > 0) {
const xmlChar *tmp = ctxt->input->cur;
ctxt->input->cur = in;
if ((ctxt->sax != NULL) &&
(ctxt->sax->ignorableWhitespace !=
ctxt->sax->characters)) {
if (areBlanks(ctxt, tmp, nbchar, 1)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData,
tmp, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
if (*ctxt->space == -1)
*ctxt->space = -2;
}
} else if ((ctxt->sax != NULL) &&
(ctxt->sax->characters != NULL)) {
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
}
}
return;
}
get_more:
ccol = ctxt->input->col;
while (test_char_data[*in]) {
in++;
ccol++;
}
ctxt->input->col = ccol;
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more;
}
if (*in == ']') {
if ((in[1] == ']') && (in[2] == '>')) {
xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
ctxt->input->cur = in;
return;
}
in++;
ctxt->input->col++;
goto get_more;
}
nbchar = in - ctxt->input->cur;
if (nbchar > 0) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->ignorableWhitespace !=
ctxt->sax->characters) &&
(IS_BLANK_CH(*ctxt->input->cur))) {
const xmlChar *tmp = ctxt->input->cur;
ctxt->input->cur = in;
if (areBlanks(ctxt, tmp, nbchar, 0)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData,
tmp, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
if (*ctxt->space == -1)
*ctxt->space = -2;
}
line = ctxt->input->line;
col = ctxt->input->col;
} else if (ctxt->sax != NULL) {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, nbchar);
line = ctxt->input->line;
col = ctxt->input->col;
}
/* something really bad happened in the SAX callback */
if (ctxt->instate != XML_PARSER_CONTENT)
return;
}
ctxt->input->cur = in;
if (*in == 0xD) {
in++;
if (*in == 0xA) {
ctxt->input->cur = in;
in++;
ctxt->input->line++; ctxt->input->col = 1;
continue; /* while */
}
in--;
}
if (*in == '<') {
return;
}
if (*in == '&') {
return;
}
SHRINK;
GROW;
in = ctxt->input->cur;
} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
nbchar = 0;
}
ctxt->input->line = line;
ctxt->input->col = col;
xmlParseCharDataComplex(ctxt, cdata);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) {
const xmlChar *in;
int nbchar = 0;
int line = ctxt->input->line;
int col = ctxt->input->col;
int ccol;
SHRINK;
GROW;
/*
* Accelerated common case where input don't need to be
* modified before passing it to the handler.
*/
if (!cdata) {
in = ctxt->input->cur;
do {
get_more_space:
while (*in == 0x20) { in++; ctxt->input->col++; }
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more_space;
}
if (*in == '<') {
nbchar = in - ctxt->input->cur;
if (nbchar > 0) {
const xmlChar *tmp = ctxt->input->cur;
ctxt->input->cur = in;
if ((ctxt->sax != NULL) &&
(ctxt->sax->ignorableWhitespace !=
ctxt->sax->characters)) {
if (areBlanks(ctxt, tmp, nbchar, 1)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData,
tmp, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
if (*ctxt->space == -1)
*ctxt->space = -2;
}
} else if ((ctxt->sax != NULL) &&
(ctxt->sax->characters != NULL)) {
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
}
}
return;
}
get_more:
ccol = ctxt->input->col;
while (test_char_data[*in]) {
in++;
ccol++;
}
ctxt->input->col = ccol;
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more;
}
if (*in == ']') {
if ((in[1] == ']') && (in[2] == '>')) {
xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
ctxt->input->cur = in;
return;
}
in++;
ctxt->input->col++;
goto get_more;
}
nbchar = in - ctxt->input->cur;
if (nbchar > 0) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->ignorableWhitespace !=
ctxt->sax->characters) &&
(IS_BLANK_CH(*ctxt->input->cur))) {
const xmlChar *tmp = ctxt->input->cur;
ctxt->input->cur = in;
if (areBlanks(ctxt, tmp, nbchar, 0)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData,
tmp, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
if (*ctxt->space == -1)
*ctxt->space = -2;
}
line = ctxt->input->line;
col = ctxt->input->col;
} else if (ctxt->sax != NULL) {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, nbchar);
line = ctxt->input->line;
col = ctxt->input->col;
}
/* something really bad happened in the SAX callback */
if (ctxt->instate != XML_PARSER_CONTENT)
return;
}
ctxt->input->cur = in;
if (*in == 0xD) {
in++;
if (*in == 0xA) {
ctxt->input->cur = in;
in++;
ctxt->input->line++; ctxt->input->col = 1;
continue; /* while */
}
in--;
}
if (*in == '<') {
return;
}
if (*in == '&') {
return;
}
SHRINK;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return;
in = ctxt->input->cur;
} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
nbchar = 0;
}
ctxt->input->line = line;
ctxt->input->col = col;
xmlParseCharDataComplex(ctxt, cdata);
}
| 171,274 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: long ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
long len;
id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
return E_FILE_FORMAT_INVALID;
}
const unsigned long long rollover_check =
static_cast<unsigned long long>(pos) + len;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
Commit Message: Fix ParseElementHeader to support 0 payload elements
Cherry-pick'ing Change 5c83bbec9a5f6f00a349674ddad85b753d2ea219
from upstream. This fixes regression in some edge cases for mkv
playback.
BUG=26499283
Change-Id: I88de03219a3d941b6b2f251d384e29c36bdd4d9b
CWE ID: CWE-20 | long ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
long len;
id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
return E_FILE_FORMAT_INVALID;
}
const unsigned long long rollover_check =
static_cast<unsigned long long>(pos) + len;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if (stop >= 0 && pos > stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 174,229 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void AppControllerImpl::GetArcAndroidId(
mojom::AppController::GetArcAndroidIdCallback callback) {
arc::GetAndroidId(base::BindOnce(
[](mojom::AppController::GetArcAndroidIdCallback callback, bool success,
int64_t android_id) {
std::move(callback).Run(success, base::NumberToString(android_id));
},
std::move(callback)));
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <michaelpg@chromium.org>
Commit-Queue: Lucas Tenório <ltenorio@chromium.org>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | void AppControllerImpl::GetArcAndroidId(
void AppControllerService::GetArcAndroidId(
mojom::AppController::GetArcAndroidIdCallback callback) {
arc::GetAndroidId(base::BindOnce(
[](mojom::AppController::GetArcAndroidIdCallback callback, bool success,
int64_t android_id) {
std::move(callback).Run(success, base::NumberToString(android_id));
},
std::move(callback)));
}
| 172,083 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int key_reject_and_link(struct key *key,
unsigned timeout,
unsigned error,
struct key *keyring,
struct key *authkey)
{
struct assoc_array_edit *edit;
struct timespec now;
int ret, awaken, link_ret = 0;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
if (keyring) {
if (keyring->restrict_link)
return -EPERM;
link_ret = __key_link_begin(keyring, &key->index_key, &edit);
}
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* mark the key as being negatively instantiated */
atomic_inc(&key->user->nikeys);
key->reject_error = -error;
smp_wmb();
set_bit(KEY_FLAG_NEGATIVE, &key->flags);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
now = current_kernel_time();
key->expiry = now.tv_sec + timeout;
key_schedule_gc(key->expiry + key_gc_delay);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
ret = 0;
/* and link it into the destination keyring */
if (keyring && link_ret == 0)
__key_link(key, &edit);
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
}
mutex_unlock(&key_construction_mutex);
if (keyring)
__key_link_end(keyring, &key->index_key, edit);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret == 0 ? link_ret : ret;
}
Commit Message: KEYS: potential uninitialized variable
If __key_link_begin() failed then "edit" would be uninitialized. I've
added a check to fix that.
This allows a random user to crash the kernel, though it's quite
difficult to achieve. There are three ways it can be done as the user
would have to cause an error to occur in __key_link():
(1) Cause the kernel to run out of memory. In practice, this is difficult
to achieve without ENOMEM cropping up elsewhere and aborting the
attempt.
(2) Revoke the destination keyring between the keyring ID being looked up
and it being tested for revocation. In practice, this is difficult to
time correctly because the KEYCTL_REJECT function can only be used
from the request-key upcall process. Further, users can only make use
of what's in /sbin/request-key.conf, though this does including a
rejection debugging test - which means that the destination keyring
has to be the caller's session keyring in practice.
(3) Have just enough key quota available to create a key, a new session
keyring for the upcall and a link in the session keyring, but not then
sufficient quota to create a link in the nominated destination keyring
so that it fails with EDQUOT.
The bug can be triggered using option (3) above using something like the
following:
echo 80 >/proc/sys/kernel/keys/root_maxbytes
keyctl request2 user debug:fred negate @t
The above sets the quota to something much lower (80) to make the bug
easier to trigger, but this is dependent on the system. Note also that
the name of the keyring created contains a random number that may be
between 1 and 10 characters in size, so may throw the test off by
changing the amount of quota used.
Assuming the failure occurs, something like the following will be seen:
kfree_debugcheck: out of range ptr 6b6b6b6b6b6b6b68h
------------[ cut here ]------------
kernel BUG at ../mm/slab.c:2821!
...
RIP: 0010:[<ffffffff811600f9>] kfree_debugcheck+0x20/0x25
RSP: 0018:ffff8804014a7de8 EFLAGS: 00010092
RAX: 0000000000000034 RBX: 6b6b6b6b6b6b6b68 RCX: 0000000000000000
RDX: 0000000000040001 RSI: 00000000000000f6 RDI: 0000000000000300
RBP: ffff8804014a7df0 R08: 0000000000000001 R09: 0000000000000000
R10: ffff8804014a7e68 R11: 0000000000000054 R12: 0000000000000202
R13: ffffffff81318a66 R14: 0000000000000000 R15: 0000000000000001
...
Call Trace:
kfree+0xde/0x1bc
assoc_array_cancel_edit+0x1f/0x36
__key_link_end+0x55/0x63
key_reject_and_link+0x124/0x155
keyctl_reject_key+0xb6/0xe0
keyctl_negate_key+0x10/0x12
SyS_keyctl+0x9f/0xe7
do_syscall_64+0x63/0x13a
entry_SYSCALL64_slow_path+0x25/0x25
Fixes: f70e2e06196a ('KEYS: Do preallocation for __key_link()')
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: David Howells <dhowells@redhat.com>
cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: | int key_reject_and_link(struct key *key,
unsigned timeout,
unsigned error,
struct key *keyring,
struct key *authkey)
{
struct assoc_array_edit *edit;
struct timespec now;
int ret, awaken, link_ret = 0;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
if (keyring) {
if (keyring->restrict_link)
return -EPERM;
link_ret = __key_link_begin(keyring, &key->index_key, &edit);
}
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* mark the key as being negatively instantiated */
atomic_inc(&key->user->nikeys);
key->reject_error = -error;
smp_wmb();
set_bit(KEY_FLAG_NEGATIVE, &key->flags);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
now = current_kernel_time();
key->expiry = now.tv_sec + timeout;
key_schedule_gc(key->expiry + key_gc_delay);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
ret = 0;
/* and link it into the destination keyring */
if (keyring && link_ret == 0)
__key_link(key, &edit);
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
}
mutex_unlock(&key_construction_mutex);
if (keyring && link_ret == 0)
__key_link_end(keyring, &key->index_key, edit);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret == 0 ? link_ret : ret;
}
| 167,261 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: hstore_slice_to_hstore(PG_FUNCTION_ARGS)
{
HStore *hs = PG_GETARG_HS(0);
HEntry *entries = ARRPTR(hs);
char *ptr = STRPTR(hs);
ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(1);
HStore *out;
int nkeys;
Pairs *key_pairs = hstoreArrayToPairs(key_array, &nkeys);
Pairs *out_pairs;
int bufsiz;
int lastidx = 0;
int i;
int out_count = 0;
if (nkeys == 0)
{
out = hstorePairs(NULL, 0, 0);
PG_RETURN_POINTER(out);
}
out_pairs = palloc(sizeof(Pairs) * nkeys);
bufsiz = 0;
/*
* we exploit the fact that the pairs list is already sorted into strictly
* increasing order to narrow the hstoreFindKey search; each search can
* start one entry past the previous "found" entry, or at the lower bound
* of the last search.
*/
for (i = 0; i < nkeys; ++i)
{
int idx = hstoreFindKey(hs, &lastidx,
key_pairs[i].key, key_pairs[i].keylen);
if (idx >= 0)
{
out_pairs[out_count].key = key_pairs[i].key;
bufsiz += (out_pairs[out_count].keylen = key_pairs[i].keylen);
out_pairs[out_count].val = HS_VAL(entries, ptr, idx);
bufsiz += (out_pairs[out_count].vallen = HS_VALLEN(entries, idx));
out_pairs[out_count].isnull = HS_VALISNULL(entries, idx);
out_pairs[out_count].needfree = false;
++out_count;
}
}
/*
* we don't use uniquePairs here because we know that the pairs list is
* already sorted and uniq'ed.
*/
out = hstorePairs(out_pairs, out_count, bufsiz);
PG_RETURN_POINTER(out);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | hstore_slice_to_hstore(PG_FUNCTION_ARGS)
{
HStore *hs = PG_GETARG_HS(0);
HEntry *entries = ARRPTR(hs);
char *ptr = STRPTR(hs);
ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(1);
HStore *out;
int nkeys;
Pairs *key_pairs = hstoreArrayToPairs(key_array, &nkeys);
Pairs *out_pairs;
int bufsiz;
int lastidx = 0;
int i;
int out_count = 0;
if (nkeys == 0)
{
out = hstorePairs(NULL, 0, 0);
PG_RETURN_POINTER(out);
}
/* hstoreArrayToPairs() checked overflow */
out_pairs = palloc(sizeof(Pairs) * nkeys);
bufsiz = 0;
/*
* we exploit the fact that the pairs list is already sorted into strictly
* increasing order to narrow the hstoreFindKey search; each search can
* start one entry past the previous "found" entry, or at the lower bound
* of the last search.
*/
for (i = 0; i < nkeys; ++i)
{
int idx = hstoreFindKey(hs, &lastidx,
key_pairs[i].key, key_pairs[i].keylen);
if (idx >= 0)
{
out_pairs[out_count].key = key_pairs[i].key;
bufsiz += (out_pairs[out_count].keylen = key_pairs[i].keylen);
out_pairs[out_count].val = HS_VAL(entries, ptr, idx);
bufsiz += (out_pairs[out_count].vallen = HS_VALLEN(entries, idx));
out_pairs[out_count].isnull = HS_VALISNULL(entries, idx);
out_pairs[out_count].needfree = false;
++out_count;
}
}
/*
* we don't use uniquePairs here because we know that the pairs list is
* already sorted and uniq'ed.
*/
out = hstorePairs(out_pairs, out_count, bufsiz);
PG_RETURN_POINTER(out);
}
| 166,401 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: 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;
}
Commit Message: 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
CWE ID: CWE-119 | 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;
}
| 167,514 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name)
{
if (name.isEmpty())
return;
map.add(name.impl());
if (Frame* f = frame())
f->script()->namedItemAdded(this, name);
}
Commit Message: Fix tracking of the id attribute string if it is shared across elements.
The patch to remove AtomicStringImpl:
http://src.chromium.org/viewvc/blink?view=rev&rev=154790
Exposed a lifetime issue with strings for id attributes. We simply need to use
AtomicString.
BUG=290566
Review URL: https://codereview.chromium.org/33793004
git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name)
void HTMLDocument::addItemToMap(HashCountedSet<AtomicString>& map, const AtomicString& name)
{
if (name.isEmpty())
return;
map.add(name);
if (Frame* f = frame())
f->script()->namedItemAdded(this, name);
}
| 171,156 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int csum_len_for_type(int cst)
{
switch (cst) {
case CSUM_NONE:
return 1;
case CSUM_ARCHAIC:
return 2;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
return MD4_DIGEST_LEN;
case CSUM_MD5:
return MD5_DIGEST_LEN;
}
return 0;
}
Commit Message:
CWE ID: CWE-354 | int csum_len_for_type(int cst)
{
switch (cst) {
case CSUM_NONE:
return 1;
case CSUM_MD4_ARCHAIC:
return 2;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
return MD4_DIGEST_LEN;
case CSUM_MD5:
return MD5_DIGEST_LEN;
}
return 0;
}
| 164,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n)
{
cmsSEQ* Seq;
cmsUInt32Number i;
if (n == 0) return NULL;
if (n > 255) return NULL;
Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ));
if (Seq == NULL) return NULL;
Seq -> ContextID = ContextID;
Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC));
Seq -> n = n;
for (i=0; i < n; i++) {
Seq -> seq[i].Manufacturer = NULL;
Seq -> seq[i].Model = NULL;
Seq -> seq[i].Description = NULL;
}
return Seq;
}
Commit Message: Non happy-path fixes
CWE ID: | cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n)
{
cmsSEQ* Seq;
cmsUInt32Number i;
if (n == 0) return NULL;
if (n > 255) return NULL;
Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ));
if (Seq == NULL) return NULL;
Seq -> ContextID = ContextID;
Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC));
Seq -> n = n;
if (Seq -> seq == NULL) {
_cmsFree(ContextID, Seq);
return NULL;
}
for (i=0; i < n; i++) {
Seq -> seq[i].Manufacturer = NULL;
Seq -> seq[i].Model = NULL;
Seq -> seq[i].Description = NULL;
}
return Seq;
}
| 166,542 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: WebTransformationMatrix WebTransformOperations::blend(const WebTransformOperations& from, double progress) const
{
WebTransformationMatrix toReturn;
bool fromIdentity = from.isIdentity();
bool toIdentity = isIdentity();
if (fromIdentity && toIdentity)
return toReturn;
if (matchesTypes(from)) {
size_t numOperations = max(fromIdentity ? 0 : from.m_private->operations.size(),
toIdentity ? 0 : m_private->operations.size());
for (size_t i = 0; i < numOperations; ++i) {
WebTransformationMatrix blended = blendTransformOperations(
fromIdentity ? 0 : &from.m_private->operations[i],
toIdentity ? 0 : &m_private->operations[i],
progress);
toReturn.multiply(blended);
}
} else {
toReturn = apply();
WebTransformationMatrix fromTransform = from.apply();
toReturn.blend(fromTransform, progress);
}
return toReturn;
}
Commit Message: [chromium] We should accelerate all transformations, except when we must blend matrices that cannot be decomposed.
https://bugs.webkit.org/show_bug.cgi?id=95855
Reviewed by James Robinson.
Source/Platform:
WebTransformOperations are now able to report if they can successfully blend.
WebTransformationMatrix::blend now returns a bool if blending would fail.
* chromium/public/WebTransformOperations.h:
(WebTransformOperations):
* chromium/public/WebTransformationMatrix.h:
(WebTransformationMatrix):
Source/WebCore:
WebTransformOperations are now able to report if they can successfully blend.
WebTransformationMatrix::blend now returns a bool if blending would fail.
Unit tests:
AnimationTranslationUtilTest.createTransformAnimationWithNonDecomposableMatrix
AnimationTranslationUtilTest.createTransformAnimationWithNonInvertibleTransform
* platform/chromium/support/WebTransformOperations.cpp:
(WebKit::blendTransformOperations):
(WebKit::WebTransformOperations::blend):
(WebKit::WebTransformOperations::canBlendWith):
(WebKit):
(WebKit::WebTransformOperations::blendInternal):
* platform/chromium/support/WebTransformationMatrix.cpp:
(WebKit::WebTransformationMatrix::blend):
* platform/graphics/chromium/AnimationTranslationUtil.cpp:
(WebCore::WebTransformAnimationCurve):
Source/WebKit/chromium:
Added the following unit tests:
AnimationTranslationUtilTest.createTransformAnimationWithNonDecomposableMatrix
AnimationTranslationUtilTest.createTransformAnimationWithNonInvertibleTransform
* tests/AnimationTranslationUtilTest.cpp:
(WebKit::TEST):
(WebKit):
git-svn-id: svn://svn.chromium.org/blink/trunk@127868 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | WebTransformationMatrix WebTransformOperations::blend(const WebTransformOperations& from, double progress) const
{
WebTransformationMatrix toReturn;
blendInternal(from, progress, toReturn);
return toReturn;
}
| 171,002 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
{
unsigned char wire[DTLS1_HM_HEADER_LENGTH];
unsigned long len, frag_off, frag_len;
int i,al;
struct hm_header_st msg_hdr;
/* see if we have the required fragment already */
if ((frag_len = dtls1_retrieve_buffered_fragment(s,max,ok)) || *ok)
{
return frag_len;
}
/* read handshake message header */
i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,wire,
DTLS1_HM_HEADER_LENGTH, 0);
if (i <= 0) /* nbio, or an error */
{
s->rwstate=SSL_READING;
*ok = 0;
return i;
}
/* Handshake fails if message header is incomplete */
if (i != DTLS1_HM_HEADER_LENGTH)
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
/* parse the message fragment header */
dtls1_get_message_header(wire, &msg_hdr);
/*
* if this is a future (or stale) message it gets buffered
* (or dropped)--no further processing at this time
* While listening, we accept seq 1 (ClientHello with cookie)
* although we're still expecting seq 0 (ClientHello)
*/
if (msg_hdr.seq != s->d1->handshake_read_seq && !(s->d1->listen && msg_hdr.seq == 1))
return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
len = msg_hdr.msg_len;
frag_off = msg_hdr.frag_off;
frag_len = msg_hdr.frag_len;
if (frag_len && frag_len < len)
return dtls1_reassemble_fragment(s, &msg_hdr, ok);
if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
wire[0] == SSL3_MT_HELLO_REQUEST)
{
/* The server may always send 'Hello Request' messages --
* we are doing a handshake anyway now, so ignore them
* if their format is correct. Does not count for
* 'Finished' MAC. */
if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0)
{
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
wire, DTLS1_HM_HEADER_LENGTH, s,
s->msg_callback_arg);
s->msg_callback_arg);
s->init_num = 0;
return dtls1_get_message_fragment(s, st1, stn,
max, ok);
}
else /* Incorrectly formated Hello request */
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
}
if ((al=dtls1_preprocess_fragment(s,&msg_hdr,max)))
goto f_err;
/* XDTLS: ressurect this when restart is in place */
s->state=stn;
if ( frag_len > 0)
{
unsigned char *p=(unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH;
i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
&p[frag_off],frag_len,0);
/* XDTLS: fix this--message fragments cannot span multiple packets */
if (i <= 0)
{
s->rwstate=SSL_READING;
*ok = 0;
return i;
}
}
else
i = 0;
/* XDTLS: an incorrectly formatted fragment should cause the
* handshake to fail */
if (i != (int)frag_len)
{
al=SSL3_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL3_AD_ILLEGAL_PARAMETER);
goto f_err;
}
*ok = 1;
/* Note that s->init_num is *not* used as current offset in
* s->init_buf->data, but as a counter summing up fragments'
* lengths: as soon as they sum up to handshake packet
* length, we assume we have got all the fragments. */
s->init_num = frag_len;
return frag_len;
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
s->init_num = 0;
*ok=0;
return(-1);
}
Commit Message:
CWE ID: CWE-399 | dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
{
unsigned char wire[DTLS1_HM_HEADER_LENGTH];
unsigned long len, frag_off, frag_len;
int i,al;
struct hm_header_st msg_hdr;
redo:
/* see if we have the required fragment already */
if ((frag_len = dtls1_retrieve_buffered_fragment(s,max,ok)) || *ok)
{
return frag_len;
}
/* read handshake message header */
i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,wire,
DTLS1_HM_HEADER_LENGTH, 0);
if (i <= 0) /* nbio, or an error */
{
s->rwstate=SSL_READING;
*ok = 0;
return i;
}
/* Handshake fails if message header is incomplete */
if (i != DTLS1_HM_HEADER_LENGTH)
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
/* parse the message fragment header */
dtls1_get_message_header(wire, &msg_hdr);
/*
* if this is a future (or stale) message it gets buffered
* (or dropped)--no further processing at this time
* While listening, we accept seq 1 (ClientHello with cookie)
* although we're still expecting seq 0 (ClientHello)
*/
if (msg_hdr.seq != s->d1->handshake_read_seq && !(s->d1->listen && msg_hdr.seq == 1))
return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
len = msg_hdr.msg_len;
frag_off = msg_hdr.frag_off;
frag_len = msg_hdr.frag_len;
if (frag_len && frag_len < len)
return dtls1_reassemble_fragment(s, &msg_hdr, ok);
if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
wire[0] == SSL3_MT_HELLO_REQUEST)
{
/* The server may always send 'Hello Request' messages --
* we are doing a handshake anyway now, so ignore them
* if their format is correct. Does not count for
* 'Finished' MAC. */
if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0)
{
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
wire, DTLS1_HM_HEADER_LENGTH, s,
s->msg_callback_arg);
s->msg_callback_arg);
s->init_num = 0;
goto redo;
}
else /* Incorrectly formated Hello request */
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
}
if ((al=dtls1_preprocess_fragment(s,&msg_hdr,max)))
goto f_err;
/* XDTLS: ressurect this when restart is in place */
s->state=stn;
if ( frag_len > 0)
{
unsigned char *p=(unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH;
i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
&p[frag_off],frag_len,0);
/* XDTLS: fix this--message fragments cannot span multiple packets */
if (i <= 0)
{
s->rwstate=SSL_READING;
*ok = 0;
return i;
}
}
else
i = 0;
/* XDTLS: an incorrectly formatted fragment should cause the
* handshake to fail */
if (i != (int)frag_len)
{
al=SSL3_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL3_AD_ILLEGAL_PARAMETER);
goto f_err;
}
*ok = 1;
/* Note that s->init_num is *not* used as current offset in
* s->init_buf->data, but as a counter summing up fragments'
* lengths: as soon as they sum up to handshake packet
* length, we assume we have got all the fragments. */
s->init_num = frag_len;
return frag_len;
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
s->init_num = 0;
*ok=0;
return(-1);
}
| 165,282 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& result, Element* element, Namespaces* namespaces)
{
if (!element->isFrameOwnerElement())
return;
HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element);
Frame* frame = frameOwner->contentFrame();
if (!frame)
return;
KURL url = frame->document()->url();
if (url.isValid() && !url.isBlankURL())
return;
url = m_serializer->urlForBlankFrame(frame);
appendAttribute(result, element, Attribute(frameOwnerURLAttributeName(*frameOwner), url.string()), namespaces);
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> R=abarth@chromium.org
>
> Review URL: https://codereview.chromium.org/68613003
TBR=tiger@opera.com
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& result, Element* element, Namespaces* namespaces)
void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& out, Element* element, Namespaces* namespaces)
{
if (!element->isFrameOwnerElement())
return;
HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element);
Frame* frame = frameOwner->contentFrame();
if (!frame)
return;
KURL url = frame->document()->url();
if (url.isValid() && !url.isBlankURL())
return;
url = m_serializer->urlForBlankFrame(frame);
appendAttribute(out, element, Attribute(frameOwnerURLAttributeName(*frameOwner), url.string()), namespaces);
}
| 171,566 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int ssl3_client_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i;
unsigned long l;
int al = 0;
#ifndef OPENSSL_NO_COMP
int j;
SSL_COMP *comp;
#endif
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
SSL_SESSION *sess = s->session;
if ((sess == NULL) ||
(sess->ssl_version != s->version) ||
!sess->session_id_length || (sess->not_resumable)) {
if (!ssl_get_new_session(s, 0))
goto err;
}
if (s->method->version == DTLS_ANY_VERSION) {
/* Determine which DTLS version to use */
int options = s->options;
/* If DTLS 1.2 disabled correct the version number */
if (options & SSL_OP_NO_DTLSv1_2) {
if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
/*
* Disabling all versions is silly: return an error.
*/
if (options & SSL_OP_NO_DTLSv1) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION);
goto err;
}
/*
* Update method so we don't use any DTLS 1.2 features.
*/
s->method = DTLSv1_client_method();
s->version = DTLS1_VERSION;
} else {
/*
* We only support one version: update method
*/
if (options & SSL_OP_NO_DTLSv1)
s->method = DTLSv1_2_client_method();
s->version = DTLS1_2_VERSION;
}
s->client_version = s->version;
}
/* else use the pre-loaded session */
p = s->s3->client_random;
/*
* for DTLS if client_random is initialized, reuse it, we are
* required to use same upon reply to HelloVerify
*/
if (SSL_IS_DTLS(s)) {
size_t idx;
i = 1;
for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
if (p[idx]) {
i = 0;
break;
}
}
} else
i = 1;
if (i)
ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random));
/* Do the message type and length last */
d = p = ssl_handshake_start(s);
/*-
* version indicates the negotiated version: for example from
* an SSLv2/v3 compatible client hello). The client_version
* field is the maximum version we permit and it is also
* used in RSA encrypted premaster secrets. Some servers can
* choke if we initially report a higher version then
* renegotiate to a lower one in the premaster secret. This
* didn't happen with TLS 1.0 as most servers supported it
* but it can with TLS 1.1 or later if the server only supports
* 1.0.
*
* Possible scenario with previous logic:
* 1. Client hello indicates TLS 1.2
* 2. Server hello says TLS 1.0
* 3. RSA encrypted premaster secret uses 1.2.
* 4. Handhaked proceeds using TLS 1.0.
* 5. Server sends hello request to renegotiate.
* 6. Client hello indicates TLS v1.0 as we now
* know that is maximum server supports.
* 7. Server chokes on RSA encrypted premaster secret
* containing version 1.0.
*
* For interoperability it should be OK to always use the
* maximum version we support in client hello and then rely
* on the checking of version to ensure the servers isn't
* being inconsistent: for example initially negotiating with
* TLS 1.0 and renegotiating with TLS 1.2. We do this by using
* client_version in client hello and not resetting it to
* the negotiated version.
*/
*(p++) = s->client_version >> 8;
*(p++) = s->client_version & 0xff;
/* Random stuff */
memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* Session ID */
if (s->new_session)
i = 0;
else
i = s->session->session_id_length;
*(p++) = i;
if (i != 0) {
if (i > (int)sizeof(s->session->session_id)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
memcpy(p, s->session->session_id, i);
p += i;
}
/* cookie stuff for DTLS */
if (SSL_IS_DTLS(s)) {
if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
*(p++) = s->d1->cookie_len;
memcpy(p, s->d1->cookie, s->d1->cookie_len);
p += s->d1->cookie_len;
}
/* Ciphers supported */
i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
if (i == 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
goto err;
}
#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
/*
* Some servers hang if client hello > 256 bytes as hack workaround
* chop number of supported ciphers to keep it well below this if we
* use TLS v1.2
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION
&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
#endif
s2n(i, p);
p += i;
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
*(p++) = 1;
#else
if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
j = 0;
else
j = sk_SSL_COMP_num(s->ctx->comp_methods);
*(p++) = 1 + j;
for (i = 0; i < j; i++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
*(p++) = comp->id;
}
#endif
*(p++) = 0; /* Add the NULL method */
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (ssl_prepare_clienthello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
if ((p =
ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
&al)) == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
#endif
l = p - d;
ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
s->state = SSL3_ST_CW_CLNT_HELLO_B;
}
/* SSL3_ST_CW_CLNT_HELLO_B */
return ssl_do_write(s);
err:
return (-1);
}
Commit Message:
CWE ID: CWE-310 | int ssl3_client_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i;
unsigned long l;
int al = 0;
#ifndef OPENSSL_NO_COMP
int j;
SSL_COMP *comp;
#endif
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
SSL_SESSION *sess = s->session;
if ((sess == NULL) ||
(sess->ssl_version != s->version) ||
!sess->session_id_length || (sess->not_resumable)) {
if (!ssl_get_new_session(s, 0))
goto err;
}
if (s->method->version == DTLS_ANY_VERSION) {
/* Determine which DTLS version to use */
int options = s->options;
/* If DTLS 1.2 disabled correct the version number */
if (options & SSL_OP_NO_DTLSv1_2) {
if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
/*
* Disabling all versions is silly: return an error.
*/
if (options & SSL_OP_NO_DTLSv1) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION);
goto err;
}
/*
* Update method so we don't use any DTLS 1.2 features.
*/
s->method = DTLSv1_client_method();
s->version = DTLS1_VERSION;
} else {
/*
* We only support one version: update method
*/
if (options & SSL_OP_NO_DTLSv1)
s->method = DTLSv1_2_client_method();
s->version = DTLS1_2_VERSION;
}
s->client_version = s->version;
}
/* else use the pre-loaded session */
p = s->s3->client_random;
/*
* for DTLS if client_random is initialized, reuse it, we are
* required to use same upon reply to HelloVerify
*/
if (SSL_IS_DTLS(s)) {
size_t idx;
i = 1;
for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
if (p[idx]) {
i = 0;
break;
}
}
} else
i = 1;
if (i && ssl_fill_hello_random(s, 0, p,
sizeof(s->s3->client_random)) <= 0)
goto err;
/* Do the message type and length last */
d = p = ssl_handshake_start(s);
/*-
* version indicates the negotiated version: for example from
* an SSLv2/v3 compatible client hello). The client_version
* field is the maximum version we permit and it is also
* used in RSA encrypted premaster secrets. Some servers can
* choke if we initially report a higher version then
* renegotiate to a lower one in the premaster secret. This
* didn't happen with TLS 1.0 as most servers supported it
* but it can with TLS 1.1 or later if the server only supports
* 1.0.
*
* Possible scenario with previous logic:
* 1. Client hello indicates TLS 1.2
* 2. Server hello says TLS 1.0
* 3. RSA encrypted premaster secret uses 1.2.
* 4. Handhaked proceeds using TLS 1.0.
* 5. Server sends hello request to renegotiate.
* 6. Client hello indicates TLS v1.0 as we now
* know that is maximum server supports.
* 7. Server chokes on RSA encrypted premaster secret
* containing version 1.0.
*
* For interoperability it should be OK to always use the
* maximum version we support in client hello and then rely
* on the checking of version to ensure the servers isn't
* being inconsistent: for example initially negotiating with
* TLS 1.0 and renegotiating with TLS 1.2. We do this by using
* client_version in client hello and not resetting it to
* the negotiated version.
*/
*(p++) = s->client_version >> 8;
*(p++) = s->client_version & 0xff;
/* Random stuff */
memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* Session ID */
if (s->new_session)
i = 0;
else
i = s->session->session_id_length;
*(p++) = i;
if (i != 0) {
if (i > (int)sizeof(s->session->session_id)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
memcpy(p, s->session->session_id, i);
p += i;
}
/* cookie stuff for DTLS */
if (SSL_IS_DTLS(s)) {
if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
*(p++) = s->d1->cookie_len;
memcpy(p, s->d1->cookie, s->d1->cookie_len);
p += s->d1->cookie_len;
}
/* Ciphers supported */
i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
if (i == 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
goto err;
}
#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
/*
* Some servers hang if client hello > 256 bytes as hack workaround
* chop number of supported ciphers to keep it well below this if we
* use TLS v1.2
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION
&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
#endif
s2n(i, p);
p += i;
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
*(p++) = 1;
#else
if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
j = 0;
else
j = sk_SSL_COMP_num(s->ctx->comp_methods);
*(p++) = 1 + j;
for (i = 0; i < j; i++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
*(p++) = comp->id;
}
#endif
*(p++) = 0; /* Add the NULL method */
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (ssl_prepare_clienthello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
if ((p =
ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
&al)) == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
#endif
l = p - d;
ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
s->state = SSL3_ST_CW_CLNT_HELLO_B;
}
/* SSL3_ST_CW_CLNT_HELLO_B */
return ssl_do_write(s);
err:
return (-1);
}
| 164,812 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const
{
assert(pTrack);
const long long n = pTrack->GetNumber();
const TrackPosition* i = m_track_positions;
const TrackPosition* const j = i + m_track_positions_count;
while (i != j)
{
const TrackPosition& p = *i++;
if (p.m_track == n)
return &p;
}
return NULL; //no matching track number found
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const
const long long n = pTrack->GetNumber();
const TrackPosition* i = m_track_positions;
const TrackPosition* const j = i + m_track_positions_count;
while (i != j) {
const TrackPosition& p = *i++;
if (p.m_track == n)
return &p;
}
return NULL; // no matching track number found
}
| 174,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void Document::open(Document* entered_document,
ExceptionState& exception_state) {
if (ImportLoader()) {
exception_state.ThrowDOMException(
kInvalidStateError, "Imported document doesn't support open().");
return;
}
if (!IsHTMLDocument()) {
exception_state.ThrowDOMException(kInvalidStateError,
"Only HTML documents support open().");
return;
}
if (throw_on_dynamic_markup_insertion_count_) {
exception_state.ThrowDOMException(
kInvalidStateError,
"Custom Element constructor should not use open().");
return;
}
if (entered_document) {
if (!GetSecurityOrigin()->IsSameSchemeHostPortAndSuborigin(
entered_document->GetSecurityOrigin())) {
exception_state.ThrowSecurityError(
"Can only call open() on same-origin documents.");
return;
}
SetSecurityOrigin(entered_document->GetSecurityOrigin());
if (this != entered_document) {
KURL new_url = entered_document->Url();
new_url.SetFragmentIdentifier(String());
SetURL(new_url);
}
cookie_url_ = entered_document->CookieURL();
}
open();
}
Commit Message: Inherit referrer and policy when creating a nested browsing context
BUG=763194
R=estark@chromium.org
Change-Id: Ide3950269adf26ba221f573dfa088e95291ab676
Reviewed-on: https://chromium-review.googlesource.com/732652
Reviewed-by: Emily Stark <estark@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#511211}
CWE ID: CWE-20 | void Document::open(Document* entered_document,
ExceptionState& exception_state) {
if (ImportLoader()) {
exception_state.ThrowDOMException(
kInvalidStateError, "Imported document doesn't support open().");
return;
}
if (!IsHTMLDocument()) {
exception_state.ThrowDOMException(kInvalidStateError,
"Only HTML documents support open().");
return;
}
if (throw_on_dynamic_markup_insertion_count_) {
exception_state.ThrowDOMException(
kInvalidStateError,
"Custom Element constructor should not use open().");
return;
}
if (entered_document) {
if (!GetSecurityOrigin()->IsSameSchemeHostPortAndSuborigin(
entered_document->GetSecurityOrigin())) {
exception_state.ThrowSecurityError(
"Can only call open() on same-origin documents.");
return;
}
SetSecurityOrigin(entered_document->GetSecurityOrigin());
if (this != entered_document) {
KURL new_url = entered_document->Url();
new_url.SetFragmentIdentifier(String());
SetURL(new_url);
SetReferrerPolicy(entered_document->GetReferrerPolicy());
}
cookie_url_ = entered_document->CookieURL();
}
open();
}
| 172,691 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
{
static PNG_CONST char short_months[12][4] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
if (png_ptr == NULL)
return (NULL);
if (png_ptr->time_buffer == NULL)
{
png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
png_sizeof(char)));
}
#ifdef _WIN32_WCE
{
wchar_t time_buf[29];
wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer,
29, NULL, NULL);
}
#else
#ifdef USE_FAR_KEYWORD
{
char near_time_buf[29];
png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
png_memcpy(png_ptr->time_buffer, near_time_buf,
29*png_sizeof(char));
}
#else
png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
#endif
#endif /* _WIN32_WCE */
return ((png_charp)png_ptr->time_buffer);
}
Commit Message: third_party/libpng: update to 1.2.54
TBR=darin@chromium.org
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
{
static PNG_CONST char short_months[12][4] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
if (png_ptr == NULL)
return (NULL);
if (png_ptr->time_buffer == NULL)
{
png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
png_sizeof(char)));
}
#ifdef _WIN32_WCE
{
wchar_t time_buf[29];
wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
ptime->day % 32, short_months[(ptime->month - 1U) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer,
29, NULL, NULL);
}
#else
#ifdef USE_FAR_KEYWORD
{
char near_time_buf[29];
png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1U) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
png_memcpy(png_ptr->time_buffer, near_time_buf,
29*png_sizeof(char));
}
#else
png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1U) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
#endif
#endif /* _WIN32_WCE */
return ((png_charp)png_ptr->time_buffer);
}
| 172,161 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)
{
uint16_t type = 0;
uint64_t size = 0;
if (!object)
return NULL;
type = (**object) & BPLIST_MASK;
size = (**object) & BPLIST_FILL;
(*object)++;
if (size == BPLIST_FILL) {
switch (type) {
case BPLIST_DATA:
case BPLIST_STRING:
case BPLIST_UNICODE:
case BPLIST_ARRAY:
case BPLIST_SET:
case BPLIST_DICT:
{
uint16_t next_size = **object & BPLIST_FILL;
if ((**object & BPLIST_MASK) != BPLIST_UINT) {
PLIST_BIN_ERR("%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\n", __func__, type, **object & BPLIST_MASK, BPLIST_UINT);
return NULL;
}
(*object)++;
next_size = 1 << next_size;
if (*object + next_size > bplist->offset_table) {
PLIST_BIN_ERR("%s: size node data bytes for node type 0x%02x point outside of valid range\n", __func__, type);
return NULL;
}
size = UINT_TO_HOST(*object, next_size);
(*object) += next_size;
break;
}
default:
break;
}
}
switch (type)
{
case BPLIST_NULL:
switch (size)
{
case BPLIST_TRUE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = TRUE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_FALSE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = FALSE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_NULL:
default:
return NULL;
}
case BPLIST_UINT:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UINT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uint_node(object, size);
case BPLIST_REAL:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_real_node(object, size);
case BPLIST_DATE:
if (3 != size) {
PLIST_BIN_ERR("%s: invalid data size for BPLIST_DATE node\n", __func__);
return NULL;
}
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_date_node(object, size);
case BPLIST_DATA:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATA data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_data_node(object, size);
case BPLIST_STRING:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_STRING data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_string_node(object, size);
case BPLIST_UNICODE:
if (size*2 < size) {
PLIST_BIN_ERR("%s: Integer overflow when calculating BPLIST_UNICODE data size.\n", __func__);
return NULL;
}
if (*object + size*2 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UNICODE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_unicode_node(object, size);
case BPLIST_SET:
case BPLIST_ARRAY:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_ARRAY data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_array_node(bplist, object, size);
case BPLIST_UID:
if (*object + size+1 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UID data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uid_node(object, size);
case BPLIST_DICT:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_dict_node(bplist, object, size);
default:
PLIST_BIN_ERR("%s: unexpected node type 0x%02x\n", __func__, type);
return NULL;
}
return NULL;
}
Commit Message: bplist: Fix data range check for string/data/dict/array nodes
Passing a size of 0xFFFFFFFFFFFFFFFF to parse_string_node() might result
in a memcpy with a size of -1, leading to undefined behavior.
This commit makes sure that the actual node data (which depends on the size)
is in the range start_of_object..start_of_object+size.
Credit to OSS-Fuzz
CWE ID: CWE-787 | static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)
{
uint16_t type = 0;
uint64_t size = 0;
if (!object)
return NULL;
type = (**object) & BPLIST_MASK;
size = (**object) & BPLIST_FILL;
(*object)++;
if (size == BPLIST_FILL) {
switch (type) {
case BPLIST_DATA:
case BPLIST_STRING:
case BPLIST_UNICODE:
case BPLIST_ARRAY:
case BPLIST_SET:
case BPLIST_DICT:
{
uint16_t next_size = **object & BPLIST_FILL;
if ((**object & BPLIST_MASK) != BPLIST_UINT) {
PLIST_BIN_ERR("%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\n", __func__, type, **object & BPLIST_MASK, BPLIST_UINT);
return NULL;
}
(*object)++;
next_size = 1 << next_size;
if (*object + next_size > bplist->offset_table) {
PLIST_BIN_ERR("%s: size node data bytes for node type 0x%02x point outside of valid range\n", __func__, type);
return NULL;
}
size = UINT_TO_HOST(*object, next_size);
(*object) += next_size;
break;
}
default:
break;
}
}
switch (type)
{
case BPLIST_NULL:
switch (size)
{
case BPLIST_TRUE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = TRUE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_FALSE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = FALSE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_NULL:
default:
return NULL;
}
case BPLIST_UINT:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UINT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uint_node(object, size);
case BPLIST_REAL:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_real_node(object, size);
case BPLIST_DATE:
if (3 != size) {
PLIST_BIN_ERR("%s: invalid data size for BPLIST_DATE node\n", __func__);
return NULL;
}
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_date_node(object, size);
case BPLIST_DATA:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATA data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_data_node(object, size);
case BPLIST_STRING:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_STRING data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_string_node(object, size);
case BPLIST_UNICODE:
if (size*2 < size) {
PLIST_BIN_ERR("%s: Integer overflow when calculating BPLIST_UNICODE data size.\n", __func__);
return NULL;
}
if (*object + size*2 < *object || *object + size*2 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UNICODE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_unicode_node(object, size);
case BPLIST_SET:
case BPLIST_ARRAY:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_ARRAY data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_array_node(bplist, object, size);
case BPLIST_UID:
if (*object + size+1 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UID data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uid_node(object, size);
case BPLIST_DICT:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DICT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_dict_node(bplist, object, size);
default:
PLIST_BIN_ERR("%s: unexpected node type 0x%02x\n", __func__, type);
return NULL;
}
return NULL;
}
| 168,334 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void jas_matrix_asr(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
assert(n >= 0);
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = jas_seqent_asr(*data, n);
}
}
}
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | void jas_matrix_asr(jas_matrix_t *matrix, int n)
{
jas_matind_t i;
jas_matind_t j;
jas_seqent_t *rowstart;
jas_matind_t rowstep;
jas_seqent_t *data;
assert(n >= 0);
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = jas_seqent_asr(*data, n);
}
}
}
}
| 168,698 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: Status XvMCGetDRInfo(Display *dpy, XvPortID port,
char **name, char **busID,
int *major, int *minor,
int *patchLevel,
int *isLocal)
{
XExtDisplayInfo *info = xvmc_find_display(dpy);
xvmcGetDRInfoReply rep;
xvmcGetDRInfoReq *req;
CARD32 magic;
#ifdef HAVE_SHMAT
volatile CARD32 *shMem;
struct timezone here;
struct timeval now;
here.tz_minuteswest = 0;
here.tz_dsttime = 0;
#endif
*name = NULL;
*busID = NULL;
XvMCCheckExtension (dpy, info, BadImplementation);
LockDisplay (dpy);
XvMCGetReq (GetDRInfo, req);
req->port = port;
magic = 0;
req->magic = 0;
#ifdef HAVE_SHMAT
req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600);
/*
* We fill a shared memory page with a repetitive pattern. If the
* X server can read this pattern, we probably have a local connection.
* Note that we can trigger the remote X server to read any shared
* page on the remote machine, so we shouldn't be able to guess and verify
* any complicated data on those pages. Thats the explanation of this
* otherwise stupid-looking pattern algorithm.
*/
if (req->shmKey >= 0) {
shMem = (CARD32 *) shmat(req->shmKey, NULL, 0);
shmctl( req->shmKey, IPC_RMID, NULL);
if ( shMem ) {
register volatile CARD32 *shMemC = shMem;
register int i;
gettimeofday( &now, &here);
magic = now.tv_usec & 0x000FFFFF;
req->magic = magic;
i = 1024 / sizeof(CARD32);
while(i--) {
*shMemC++ = magic;
magic = ~magic;
}
} else {
req->shmKey = -1;
}
}
#else
req->shmKey = 0;
#endif
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay (dpy);
SyncHandle ();
#ifdef HAVE_SHMAT
if ( req->shmKey >= 0) {
shmdt( (const void *) shMem );
}
#endif
return -1;
}
#ifdef HAVE_SHMAT
shmdt( (const void *) shMem );
#endif
if (rep.length > 0) {
unsigned long realSize = 0;
char *tmpBuf = NULL;
if ((rep.length < (INT_MAX >> 2)) &&
/* protect against overflow in strncpy below */
(rep.nameLen + rep.busIDLen > rep.nameLen)) {
realSize = rep.length << 2;
if (realSize >= (rep.nameLen + rep.busIDLen)) {
tmpBuf = Xmalloc(realSize);
*name = Xmalloc(rep.nameLen);
*busID = Xmalloc(rep.busIDLen);
}
}
if (*name && *busID && tmpBuf) {
_XRead(dpy, tmpBuf, realSize);
strncpy(*name,tmpBuf,rep.nameLen);
(*name)[rep.nameLen - 1] = '\0';
strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
(*busID)[rep.busIDLen - 1] = '\0';
XFree(tmpBuf);
} else {
XFree(*name);
*name = NULL;
XFree(*busID);
*busID = NULL;
XFree(tmpBuf);
_XEatDataWords(dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return -1;
}
}
UnlockDisplay (dpy);
SyncHandle ();
*major = rep.major;
*minor = rep.minor;
*patchLevel = rep.patchLevel;
*isLocal = (req->shmKey > 0) ? rep.isLocal : 1;
return (rep.length > 0) ? Success : BadImplementation;
}
Commit Message:
CWE ID: CWE-119 | Status XvMCGetDRInfo(Display *dpy, XvPortID port,
char **name, char **busID,
int *major, int *minor,
int *patchLevel,
int *isLocal)
{
XExtDisplayInfo *info = xvmc_find_display(dpy);
xvmcGetDRInfoReply rep;
xvmcGetDRInfoReq *req;
CARD32 magic;
#ifdef HAVE_SHMAT
volatile CARD32 *shMem;
struct timezone here;
struct timeval now;
here.tz_minuteswest = 0;
here.tz_dsttime = 0;
#endif
*name = NULL;
*busID = NULL;
XvMCCheckExtension (dpy, info, BadImplementation);
LockDisplay (dpy);
XvMCGetReq (GetDRInfo, req);
req->port = port;
magic = 0;
req->magic = 0;
#ifdef HAVE_SHMAT
req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600);
/*
* We fill a shared memory page with a repetitive pattern. If the
* X server can read this pattern, we probably have a local connection.
* Note that we can trigger the remote X server to read any shared
* page on the remote machine, so we shouldn't be able to guess and verify
* any complicated data on those pages. Thats the explanation of this
* otherwise stupid-looking pattern algorithm.
*/
if (req->shmKey >= 0) {
shMem = (CARD32 *) shmat(req->shmKey, NULL, 0);
shmctl( req->shmKey, IPC_RMID, NULL);
if ( shMem ) {
register volatile CARD32 *shMemC = shMem;
register int i;
gettimeofday( &now, &here);
magic = now.tv_usec & 0x000FFFFF;
req->magic = magic;
i = 1024 / sizeof(CARD32);
while(i--) {
*shMemC++ = magic;
magic = ~magic;
}
} else {
req->shmKey = -1;
}
}
#else
req->shmKey = 0;
#endif
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay (dpy);
SyncHandle ();
#ifdef HAVE_SHMAT
if ( req->shmKey >= 0) {
shmdt( (const void *) shMem );
}
#endif
return -1;
}
#ifdef HAVE_SHMAT
shmdt( (const void *) shMem );
#endif
if (rep.length > 0) {
unsigned long realSize = 0;
char *tmpBuf = NULL;
if ((rep.length < (INT_MAX >> 2)) &&
/* protect against overflow in strncpy below */
(rep.nameLen + rep.busIDLen > rep.nameLen)) {
realSize = rep.length << 2;
if (realSize >= (rep.nameLen + rep.busIDLen)) {
tmpBuf = Xmalloc(realSize);
*name = Xmalloc(rep.nameLen);
*busID = Xmalloc(rep.busIDLen);
}
}
if (*name && *busID && tmpBuf) {
_XRead(dpy, tmpBuf, realSize);
strncpy(*name,tmpBuf,rep.nameLen);
(*name)[rep.nameLen == 0 ? 0 : rep.nameLen - 1] = '\0';
strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
(*busID)[rep.busIDLen == 0 ? 0 : rep.busIDLen - 1] = '\0';
XFree(tmpBuf);
} else {
XFree(*name);
*name = NULL;
XFree(*busID);
*busID = NULL;
XFree(tmpBuf);
_XEatDataWords(dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return -1;
}
}
UnlockDisplay (dpy);
SyncHandle ();
*major = rep.major;
*minor = rep.minor;
*patchLevel = rep.patchLevel;
*isLocal = (req->shmKey > 0) ? rep.isLocal : 1;
return (rep.length > 0) ? Success : BadImplementation;
}
| 164,913 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void BrowserTabStripController::TabDetachedAt(TabContents* contents,
int model_index) {
hover_tab_selector_.CancelTabTransition();
tabstrip_->RemoveTabAt(model_index);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void BrowserTabStripController::TabDetachedAt(TabContents* contents,
void BrowserTabStripController::TabDetachedAt(WebContents* contents,
int model_index) {
hover_tab_selector_.CancelTabTransition();
tabstrip_->RemoveTabAt(model_index);
}
| 171,523 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static inline int handle_dots(struct nameidata *nd, int type)
{
if (type == LAST_DOTDOT) {
if (nd->flags & LOOKUP_RCU) {
return follow_dotdot_rcu(nd);
} else
follow_dotdot(nd);
}
return 0;
}
Commit Message: vfs: Test for and handle paths that are unreachable from their mnt_root
In rare cases a directory can be renamed out from under a bind mount.
In those cases without special handling it becomes possible to walk up
the directory tree to the root dentry of the filesystem and down
from the root dentry to every other file or directory on the filesystem.
Like division by zero .. from an unconnected path can not be given
a useful semantic as there is no predicting at which path component
the code will realize it is unconnected. We certainly can not match
the current behavior as the current behavior is a security hole.
Therefore when encounting .. when following an unconnected path
return -ENOENT.
- Add a function path_connected to verify path->dentry is reachable
from path->mnt.mnt_root. AKA to validate that rename did not do
something nasty to the bind mount.
To avoid races path_connected must be called after following a path
component to it's next path component.
Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-254 | static inline int handle_dots(struct nameidata *nd, int type)
{
if (type == LAST_DOTDOT) {
if (nd->flags & LOOKUP_RCU) {
return follow_dotdot_rcu(nd);
} else
return follow_dotdot(nd);
}
return 0;
}
| 166,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
SessionService* session_service =
SessionServiceFactory::GetForProfile(profile_);
if (session_service)
session_service->TabClosing(old_contents->web_contents());
TabInsertedAt(new_contents->web_contents(), index, (index == active_index()));
int entry_count =
new_contents->web_contents()->GetController().GetEntryCount();
if (entry_count > 0) {
new_contents->web_contents()->GetController().NotifyEntryChanged(
new_contents->web_contents()->GetController().GetEntryAtIndex(
entry_count - 1),
entry_count - 1);
}
if (session_service) {
session_service->TabRestored(new_contents,
tab_strip_model_->IsTabPinned(index));
}
content::DevToolsManager::GetInstance()->ContentsReplaced(
old_contents->web_contents(), new_contents->web_contents());
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
TabDetachedAtImpl(old_contents->web_contents(), index, DETACH_TYPE_REPLACE);
SessionService* session_service =
SessionServiceFactory::GetForProfile(profile_);
if (session_service)
session_service->TabClosing(old_contents->web_contents());
TabInsertedAt(new_contents->web_contents(), index, (index == active_index()));
int entry_count =
new_contents->web_contents()->GetController().GetEntryCount();
if (entry_count > 0) {
new_contents->web_contents()->GetController().NotifyEntryChanged(
new_contents->web_contents()->GetController().GetEntryAtIndex(
entry_count - 1),
entry_count - 1);
}
if (session_service) {
session_service->TabRestored(new_contents,
tab_strip_model_->IsTabPinned(index));
}
content::DevToolsManager::GetInstance()->ContentsReplaced(
old_contents->web_contents(), new_contents->web_contents());
}
| 171,509 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: image_transform_png_set_scale_16_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth > 8;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_scale_16_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth > 8;
}
| 173,645 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void TouchEventHandler::handleTouchPoint(Platform::TouchPoint& point, unsigned modifiers)
{
m_webPage->m_inputHandler->setInputModeEnabled();
bool shiftActive = modifiers & KEYMOD_SHIFT;
bool altActive = modifiers & KEYMOD_ALT;
bool ctrlActive = modifiers & KEYMOD_CTRL;
switch (point.m_state) {
case Platform::TouchPoint::TouchPressed:
{
m_webPage->m_inputHandler->clearDidSpellCheckState();
if (!m_lastFatFingersResult.isValid())
doFatFingers(point);
Element* elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable();
if (m_lastFatFingersResult.isTextInput()) {
elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable(FatFingersResult::ShadowContentNotAllowed, true /* shouldUseRootEditableElement */);
m_shouldRequestSpellCheckOptions = m_webPage->m_inputHandler->shouldRequestSpellCheckingOptionsForPoint(point.m_pos, elementUnderFatFinger, m_spellCheckOptionRequest);
}
handleFatFingerPressed(shiftActive, altActive, ctrlActive);
break;
}
case Platform::TouchPoint::TouchReleased:
{
if (!m_shouldRequestSpellCheckOptions)
m_webPage->m_inputHandler->processPendingKeyboardVisibilityChange();
if (m_webPage->m_inputHandler->isInputMode())
m_webPage->m_inputHandler->notifyClientOfKeyboardVisibilityChange(true);
m_webPage->m_tapHighlight->hide();
IntPoint adjustedPoint = m_webPage->mapFromContentsToViewport(m_lastFatFingersResult.adjustedPosition());
PlatformMouseEvent mouseEvent(adjustedPoint, m_lastScreenPoint, PlatformEvent::MouseReleased, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen);
m_webPage->handleMouseEvent(mouseEvent);
if (m_shouldRequestSpellCheckOptions) {
IntPoint pixelPositionRelativeToViewport = m_webPage->mapToTransformed(adjustedPoint);
IntSize screenOffset(m_lastScreenPoint - pixelPositionRelativeToViewport);
m_webPage->m_inputHandler->requestSpellingCheckingOptions(m_spellCheckOptionRequest, screenOffset);
m_shouldRequestSpellCheckOptions = false;
}
m_lastFatFingersResult.reset(); // Reset the fat finger result as its no longer valid when a user's finger is not on the screen.
break;
}
case Platform::TouchPoint::TouchMoved:
{
m_webPage->m_inputHandler->clearDidSpellCheckState();
PlatformMouseEvent mouseEvent(point.m_pos, m_lastScreenPoint, PlatformEvent::MouseMoved, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen);
m_lastScreenPoint = point.m_screenPos;
m_webPage->handleMouseEvent(mouseEvent);
break;
}
default:
break;
}
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void TouchEventHandler::handleTouchPoint(Platform::TouchPoint& point, unsigned modifiers)
void TouchEventHandler::handleTouchPoint(const Platform::TouchPoint& point, unsigned modifiers)
{
m_webPage->m_inputHandler->setInputModeEnabled();
bool shiftActive = modifiers & KEYMOD_SHIFT;
bool altActive = modifiers & KEYMOD_ALT;
bool ctrlActive = modifiers & KEYMOD_CTRL;
switch (point.state()) {
case Platform::TouchPoint::TouchPressed:
{
m_webPage->m_inputHandler->clearDidSpellCheckState();
if (!m_lastFatFingersResult.isValid())
doFatFingers(point);
Element* elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable();
if (m_lastFatFingersResult.isTextInput()) {
elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable(FatFingersResult::ShadowContentNotAllowed, true /* shouldUseRootEditableElement */);
m_shouldRequestSpellCheckOptions = m_webPage->m_inputHandler->shouldRequestSpellCheckingOptionsForPoint(point.documentContentPosition(), elementUnderFatFinger, m_spellCheckOptionRequest);
}
handleFatFingerPressed(shiftActive, altActive, ctrlActive);
break;
}
case Platform::TouchPoint::TouchReleased:
{
if (!m_shouldRequestSpellCheckOptions)
m_webPage->m_inputHandler->processPendingKeyboardVisibilityChange();
if (m_webPage->m_inputHandler->isInputMode())
m_webPage->m_inputHandler->notifyClientOfKeyboardVisibilityChange(true);
m_webPage->m_tapHighlight->hide();
IntPoint adjustedPoint = m_webPage->mapFromContentsToViewport(m_lastFatFingersResult.adjustedPosition());
PlatformMouseEvent mouseEvent(adjustedPoint, m_lastScreenPoint, PlatformEvent::MouseReleased, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen);
m_webPage->handleMouseEvent(mouseEvent);
if (m_shouldRequestSpellCheckOptions) {
IntPoint pixelPositionRelativeToViewport = m_webPage->mapToTransformed(adjustedPoint);
IntSize screenOffset(m_lastScreenPoint - pixelPositionRelativeToViewport);
m_webPage->m_inputHandler->requestSpellingCheckingOptions(m_spellCheckOptionRequest, screenOffset);
m_shouldRequestSpellCheckOptions = false;
}
m_lastFatFingersResult.reset(); // Reset the fat finger result as its no longer valid when a user's finger is not on the screen.
break;
}
case Platform::TouchPoint::TouchMoved:
{
m_webPage->m_inputHandler->clearDidSpellCheckState();
PlatformMouseEvent mouseEvent(point.documentViewportPosition(), m_lastScreenPoint, PlatformEvent::MouseMoved, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen);
m_lastScreenPoint = point.screenPosition();
m_webPage->handleMouseEvent(mouseEvent);
break;
}
default:
break;
}
}
| 170,770 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: WebRTCSessionDescriptionDescriptor MockWebRTCPeerConnectionHandler::localDescription()
{
return m_localDescription;
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | WebRTCSessionDescriptionDescriptor MockWebRTCPeerConnectionHandler::localDescription()
| 170,360 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: bool Block::IsInvisible() const
{
return bool(int(m_flags & 0x08) != 0);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | bool Block::IsInvisible() const
const Block::Frame& Block::GetFrame(int idx) const {
assert(idx >= 0);
assert(idx < m_frame_count);
const Frame& f = m_frames[idx];
assert(f.pos > 0);
assert(f.len > 0);
return f;
}
| 174,391 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
Commit Message: Stratum: extract_sockaddr: Truncate overlong addresses rather than stack overflow
Thanks to Mick Ayzenberg <mick@dejavusecurity.com> for finding this!
CWE ID: CWE-119 | bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
if (url_len >= sizeof(url_address))
{
applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'",
__func__, url_len, url_begin);
url_len = sizeof(url_address) - 1;
}
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
| 166,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static struct ucma_multicast* ucma_alloc_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc;
mc = kzalloc(sizeof(*mc), GFP_KERNEL);
if (!mc)
return NULL;
mutex_lock(&mut);
mc->id = idr_alloc(&multicast_idr, mc, 0, 0, GFP_KERNEL);
mutex_unlock(&mut);
if (mc->id < 0)
goto error;
mc->ctx = ctx;
list_add_tail(&mc->list, &ctx->mc_list);
return mc;
error:
kfree(mc);
return NULL;
}
Commit Message: infiniband: fix a possible use-after-free bug
ucma_process_join() will free the new allocated "mc" struct,
if there is any error after that, especially the copy_to_user().
But in parallel, ucma_leave_multicast() could find this "mc"
through idr_find() before ucma_process_join() frees it, since it
is already published.
So "mc" could be used in ucma_leave_multicast() after it is been
allocated and freed in ucma_process_join(), since we don't refcnt
it.
Fix this by separating "publish" from ID allocation, so that we
can get an ID first and publish it later after copy_to_user().
Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support")
Reported-by: Noam Rathaus <noamr@beyondsecurity.com>
Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com>
Signed-off-by: Jason Gunthorpe <jgg@mellanox.com>
CWE ID: CWE-416 | static struct ucma_multicast* ucma_alloc_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc;
mc = kzalloc(sizeof(*mc), GFP_KERNEL);
if (!mc)
return NULL;
mutex_lock(&mut);
mc->id = idr_alloc(&multicast_idr, NULL, 0, 0, GFP_KERNEL);
mutex_unlock(&mut);
if (mc->id < 0)
goto error;
mc->ctx = ctx;
list_add_tail(&mc->list, &ctx->mc_list);
return mc;
error:
kfree(mc);
return NULL;
}
| 169,109 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: long long CuePoint::GetTime(const Segment* pSegment) const
{
assert(pSegment);
assert(m_timecode >= 0);
const SegmentInfo* const pInfo = pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long time = scale * m_timecode;
return time;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long CuePoint::GetTime(const Segment* pSegment) const
| 174,364 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 28