instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BrowserContextDestroyer::BrowserContextDestroyer(
BrowserContext* context,
const std::set<content::RenderProcessHost*>& hosts)
: context_(context),
pending_hosts_(0) {
for (std::set<content::RenderProcessHost*>::iterator it = hosts.begin();
it != hosts.end(); ++it) {
(*it)->AddObserver(this);
++pending_hosts_;
}
}
Commit Message:
CWE ID: CWE-20
|
BrowserContextDestroyer::BrowserContextDestroyer(
std::unique_ptr<BrowserContext> context,
const std::set<content::RenderProcessHost*>& hosts,
uint32_t otr_contexts_pending_deletion)
: context_(std::move(context)),
otr_contexts_pending_deletion_(otr_contexts_pending_deletion),
finish_destroy_scheduled_(false) {
DCHECK(hosts.size() > 0 ||
(!context->IsOffTheRecord() &&
(otr_contexts_pending_deletion > 0 ||
context->HasOffTheRecordContext())));
g_contexts_pending_deletion.Get().push_back(this);
for (auto* host : hosts) {
ObserveHost(host);
}
}
| 165,418
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void SoftAVC::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer =
inHeader->pBuffer + inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20
|
void SoftAVC::setDecodeArgs(
bool SoftAVC::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer =
inHeader->pBuffer + inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
uint8_t *pBuf;
if (outHeader) {
if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) {
android_errorWriteLog(0x534e4554, "27569635");
return false;
}
pBuf = outHeader->pBuffer;
} else {
// mFlushOutBuffer always has the right size.
pBuf = mFlushOutBuffer;
}
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return true;
}
| 174,180
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int bmdma_prepare_buf(IDEDMA *dma, int is_write)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
IDEState *s = bmdma_active_if(bm);
uint32_t size;
} prd;
Commit Message:
CWE ID: CWE-399
|
static int bmdma_prepare_buf(IDEDMA *dma, int is_write)
/**
* Return the number of bytes successfully prepared.
* -1 on error.
*/
static int32_t bmdma_prepare_buf(IDEDMA *dma, int is_write)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
IDEState *s = bmdma_active_if(bm);
uint32_t size;
} prd;
| 164,840
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void MockPrinter::UpdateSettings(int cookie,
PrintMsg_PrintPages_Params* params,
const std::vector<int>& pages) {
EXPECT_EQ(document_cookie_, cookie);
params->Reset();
params->pages = pages;
SetPrintParams(&(params->params));
printer_status_ = PRINTER_PRINTING;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void MockPrinter::UpdateSettings(int cookie,
PrintMsg_PrintPages_Params* params,
const std::vector<int>& pages) {
if (document_cookie_ == -1) {
document_cookie_ = CreateDocumentCookie();
}
params->Reset();
params->pages = pages;
SetPrintParams(&(params->params));
printer_status_ = PRINTER_PRINTING;
}
| 170,257
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BluetoothDeviceChromeOS::CancelPairing() {
if (!RunPairingCallbacks(CANCELLED)) {
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
CancelPairing(
object_path_,
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError,
weak_ptr_factory_.GetWeakPtr()));
UnregisterAgent();
}
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BluetoothDeviceChromeOS::CancelPairing() {
if (!pairing_context_.get() || !pairing_context_->CancelPairing()) {
VLOG(1) << object_path_.value() << ": No pairing context or callback. "
<< "Sending explicit cancel";
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
CancelPairing(
object_path_,
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError,
weak_ptr_factory_.GetWeakPtr()));
// delegate is going to be freed before things complete, so clear out the
// context holding it.
pairing_context_.reset();
}
}
| 171,219
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int main(int argc, char **argv) {
int frame_cnt = 0;
FILE *outfile = NULL;
vpx_codec_ctx_t codec;
const VpxInterface *decoder = NULL;
VpxVideoReader *reader = NULL;
const VpxVideoInfo *info = NULL;
int n = 0;
int m = 0;
int is_range = 0;
char *nptr = NULL;
exec_name = argv[0];
if (argc != 4)
die("Invalid number of arguments.");
reader = vpx_video_reader_open(argv[1]);
if (!reader)
die("Failed to open %s for reading.", argv[1]);
if (!(outfile = fopen(argv[2], "wb")))
die("Failed to open %s for writing.", argv[2]);
n = strtol(argv[3], &nptr, 0);
m = strtol(nptr + 1, NULL, 0);
is_range = (*nptr == '-');
if (!n || !m || (*nptr != '-' && *nptr != '/'))
die("Couldn't parse pattern %s.\n", argv[3]);
info = vpx_video_reader_get_info(reader);
decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
if (!decoder)
die("Unknown input codec.");
printf("Using %s\n", vpx_codec_iface_name(decoder->interface()));
if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0))
die_codec(&codec, "Failed to initialize decoder.");
while (vpx_video_reader_read_frame(reader)) {
vpx_codec_iter_t iter = NULL;
vpx_image_t *img = NULL;
size_t frame_size = 0;
int skip;
const unsigned char *frame = vpx_video_reader_get_frame(reader,
&frame_size);
if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0))
die_codec(&codec, "Failed to decode frame.");
++frame_cnt;
skip = (is_range && frame_cnt >= n && frame_cnt <= m) ||
(!is_range && m - (frame_cnt - 1) % m <= n);
if (!skip) {
putc('.', stdout);
while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL)
vpx_img_write(img, outfile);
} else {
putc('X', stdout);
}
fflush(stdout);
}
printf("Processed %d frames.\n", frame_cnt);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
info->frame_width, info->frame_height, argv[2]);
vpx_video_reader_close(reader);
fclose(outfile);
return EXIT_SUCCESS;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
int main(int argc, char **argv) {
int frame_cnt = 0;
FILE *outfile = NULL;
vpx_codec_ctx_t codec;
const VpxInterface *decoder = NULL;
VpxVideoReader *reader = NULL;
const VpxVideoInfo *info = NULL;
int n = 0;
int m = 0;
int is_range = 0;
char *nptr = NULL;
exec_name = argv[0];
if (argc != 4)
die("Invalid number of arguments.");
reader = vpx_video_reader_open(argv[1]);
if (!reader)
die("Failed to open %s for reading.", argv[1]);
if (!(outfile = fopen(argv[2], "wb")))
die("Failed to open %s for writing.", argv[2]);
n = strtol(argv[3], &nptr, 0);
m = strtol(nptr + 1, NULL, 0);
is_range = (*nptr == '-');
if (!n || !m || (*nptr != '-' && *nptr != '/'))
die("Couldn't parse pattern %s.\n", argv[3]);
info = vpx_video_reader_get_info(reader);
decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
if (!decoder)
die("Unknown input codec.");
printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface()));
if (vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL, 0))
die_codec(&codec, "Failed to initialize decoder.");
while (vpx_video_reader_read_frame(reader)) {
vpx_codec_iter_t iter = NULL;
vpx_image_t *img = NULL;
size_t frame_size = 0;
int skip;
const unsigned char *frame = vpx_video_reader_get_frame(reader,
&frame_size);
if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0))
die_codec(&codec, "Failed to decode frame.");
++frame_cnt;
skip = (is_range && frame_cnt >= n && frame_cnt <= m) ||
(!is_range && m - (frame_cnt - 1) % m <= n);
if (!skip) {
putc('.', stdout);
while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL)
vpx_img_write(img, outfile);
} else {
putc('X', stdout);
}
fflush(stdout);
}
printf("Processed %d frames.\n", frame_cnt);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
info->frame_width, info->frame_height, argv[2]);
vpx_video_reader_close(reader);
fclose(outfile);
return EXIT_SUCCESS;
}
| 174,476
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void HTMLMediaElement::NoneSupported(const String& message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='" << message
<< "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <mlamouri@chromium.org>
Reviewed-by: Dale Curtis <dalecurtis@chromium.org>
Commit-Queue: Fredrik Hubinette <hubbe@chromium.org>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200
|
void HTMLMediaElement::NoneSupported(const String& message) {
void HTMLMediaElement::NoneSupported(const String& input_message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='"
<< input_message << "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
String empty_string;
const String& message = MediaShouldBeOpaque() ? empty_string : input_message;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
| 173,163
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(mcrypt_cfb)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_long_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_cfb)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_long_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC);
}
| 167,109
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BufferQueueConsumer::dump(String8& result, const char* prefix) const {
const IPCThreadState* ipc = IPCThreadState::self();
const pid_t pid = ipc->getCallingPid();
const uid_t uid = ipc->getCallingUid();
if ((uid != AID_SHELL)
&& !PermissionCache::checkPermission(String16(
"android.permission.DUMP"), pid, uid)) {
result.appendFormat("Permission Denial: can't dump BufferQueueConsumer "
"from pid=%d, uid=%d\n", pid, uid);
} else {
mCore->dump(result, prefix);
}
}
Commit Message: Add SN logging
Bug 27046057
Change-Id: Iede7c92e59e60795df1ec7768ebafd6b090f1c27
CWE ID: CWE-264
|
void BufferQueueConsumer::dump(String8& result, const char* prefix) const {
const IPCThreadState* ipc = IPCThreadState::self();
const pid_t pid = ipc->getCallingPid();
const uid_t uid = ipc->getCallingUid();
if ((uid != AID_SHELL)
&& !PermissionCache::checkPermission(String16(
"android.permission.DUMP"), pid, uid)) {
result.appendFormat("Permission Denial: can't dump BufferQueueConsumer "
"from pid=%d, uid=%d\n", pid, uid);
android_errorWriteWithInfoLog(0x534e4554, "27046057", uid, NULL, 0);
} else {
mCore->dump(result, prefix);
}
}
| 173,894
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: DecodeNumberField(int len, char *str, int fmask,
int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits)
{
char *cp;
/*
* Have a decimal point? Then this is a date or something with a seconds
* field...
*/
if ((cp = strchr(str, '.')) != NULL)
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[MAXDATELEN + 1];
/*
* OK, we have at most six digits to care about. Let's construct a
* string and then do the conversion to an integer.
*/
strcpy(fstr, (cp + 1));
strcpy(fstr + strlen(fstr), "000000");
*(fstr + 6) = '\0';
*fsec = strtol(fstr, NULL, 10);
#else
*fsec = strtod(cp, NULL);
#endif
*cp = '\0';
len = strlen(str);
}
/* No decimal point and no complete date yet? */
else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
{
/* yyyymmdd? */
if (len == 8)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 6);
*(str + 6) = '\0';
tm->tm_mon = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_year = atoi(str + 0);
return DTK_DATE;
}
/* yymmdd? */
else if (len == 6)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_mon = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
/* yyddd? */
else if (len == 5)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_mon = 1;
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
}
/* not all time fields are specified? */
if ((fmask & DTK_TIME_M) != DTK_TIME_M)
{
/* hhmmss */
if (len == 6)
{
*tmask = DTK_TIME_M;
tm->tm_sec = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
/* hhmm? */
else if (len == 4)
{
*tmask = DTK_TIME_M;
tm->tm_sec = 0;
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
}
return -1;
} /* DecodeNumberField() */
Commit Message: Fix handling of wide datetime input/output.
Many server functions use the MAXDATELEN constant to size a buffer for
parsing or displaying a datetime value. It was much too small for the
longest possible interval output and slightly too small for certain
valid timestamp input, particularly input with a long timezone name.
The long input was rejected needlessly; the long output caused
interval_out() to overrun its buffer. ECPG's pgtypes library has a copy
of the vulnerable functions, which bore the same vulnerabilities along
with some of its own. In contrast to the server, certain long inputs
caused stack overflow rather than failing cleanly. Back-patch to 8.4
(all supported versions).
Reported by Daniel Schüssler, reviewed by Tom Lane.
Security: CVE-2014-0063
CWE ID: CWE-119
|
DecodeNumberField(int len, char *str, int fmask,
int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits)
{
char *cp;
/*
* Have a decimal point? Then this is a date or something with a seconds
* field...
*/
if ((cp = strchr(str, '.')) != NULL)
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[7];
int i;
cp++;
/*
* OK, we have at most six digits to care about. Let's construct a
* string with those digits, zero-padded on the right, and then do
* the conversion to an integer.
*
* XXX This truncates the seventh digit, unlike rounding it as do
* the backend and the !HAVE_INT64_TIMESTAMP case.
*/
for (i = 0; i < 6; i++)
fstr[i] = *cp != '\0' ? *cp++ : '0';
fstr[i] = '\0';
*fsec = strtol(fstr, NULL, 10);
#else
*fsec = strtod(cp, NULL);
#endif
*cp = '\0';
len = strlen(str);
}
/* No decimal point and no complete date yet? */
else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
{
/* yyyymmdd? */
if (len == 8)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 6);
*(str + 6) = '\0';
tm->tm_mon = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_year = atoi(str + 0);
return DTK_DATE;
}
/* yymmdd? */
else if (len == 6)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_mon = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
/* yyddd? */
else if (len == 5)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_mon = 1;
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
}
/* not all time fields are specified? */
if ((fmask & DTK_TIME_M) != DTK_TIME_M)
{
/* hhmmss */
if (len == 6)
{
*tmask = DTK_TIME_M;
tm->tm_sec = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
/* hhmm? */
else if (len == 4)
{
*tmask = DTK_TIME_M;
tm->tm_sec = 0;
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
}
return -1;
} /* DecodeNumberField() */
| 166,464
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags);
if (offset == 0)
break;
}
}
return 0;
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399
|
dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, uint16_t *notecount)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags, notecount);
if (offset == 0)
break;
}
}
return 0;
}
| 166,777
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
return NULL;
}
| 167,791
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
RenderFrameObserver* observer;
while ((observer = it.GetNext()) != NULL) {
if (observer->OnMessageReceived(msg))
return true;
}
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(RenderFrameImpl, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
IPC_MESSAGE_HANDLER(FrameMsg_BuffersSwapped, OnBuffersSwapped)
IPC_MESSAGE_HANDLER_GENERIC(FrameMsg_CompositorFrameSwapped,
OnCompositorFrameSwapped(msg))
IPC_MESSAGE_HANDLER(FrameMsg_ChildFrameProcessGone, OnChildFrameProcessGone)
IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
OnCustomContextMenuAction)
IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
OnJavaScriptExecuteRequest)
IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
OnSetEditableSelectionOffsets)
IPC_MESSAGE_HANDLER(FrameMsg_SetCompositionFromExistingText,
OnSetCompositionFromExistingText)
IPC_MESSAGE_HANDLER(FrameMsg_ExtendSelectionAndDelete,
OnExtendSelectionAndDelete)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
#endif
IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
IPC_END_MESSAGE_MAP_EX()
if (!msg_is_ok) {
CHECK(false) << "Unable to deserialize message in RenderFrameImpl.";
}
return handled;
}
Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame.
BUG=369553
R=creis@chromium.org
Review URL: https://codereview.chromium.org/263833020
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
GetContentClient()->SetActiveURL(frame_->document().url());
ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
RenderFrameObserver* observer;
while ((observer = it.GetNext()) != NULL) {
if (observer->OnMessageReceived(msg))
return true;
}
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(RenderFrameImpl, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
IPC_MESSAGE_HANDLER(FrameMsg_BuffersSwapped, OnBuffersSwapped)
IPC_MESSAGE_HANDLER_GENERIC(FrameMsg_CompositorFrameSwapped,
OnCompositorFrameSwapped(msg))
IPC_MESSAGE_HANDLER(FrameMsg_ChildFrameProcessGone, OnChildFrameProcessGone)
IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
OnCustomContextMenuAction)
IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
OnJavaScriptExecuteRequest)
IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
OnSetEditableSelectionOffsets)
IPC_MESSAGE_HANDLER(FrameMsg_SetCompositionFromExistingText,
OnSetCompositionFromExistingText)
IPC_MESSAGE_HANDLER(FrameMsg_ExtendSelectionAndDelete,
OnExtendSelectionAndDelete)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
#endif
IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
IPC_END_MESSAGE_MAP_EX()
if (!msg_is_ok) {
int id = msg.type();
CHECK(false) << "Unable to deserialize " << id << " in RenderFrameImpl.";
}
return handled;
}
| 171,144
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int snd_ctl_replace(struct snd_card *card, struct snd_kcontrol *kcontrol,
bool add_on_replace)
{
struct snd_ctl_elem_id id;
unsigned int idx;
struct snd_kcontrol *old;
int ret;
if (!kcontrol)
return -EINVAL;
if (snd_BUG_ON(!card || !kcontrol->info)) {
ret = -EINVAL;
goto error;
}
id = kcontrol->id;
down_write(&card->controls_rwsem);
old = snd_ctl_find_id(card, &id);
if (!old) {
if (add_on_replace)
goto add;
up_write(&card->controls_rwsem);
ret = -EINVAL;
goto error;
}
ret = snd_ctl_remove(card, old);
if (ret < 0) {
up_write(&card->controls_rwsem);
goto error;
}
add:
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
ret = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return ret;
}
Commit Message: ALSA: control: Don't access controls outside of protected regions
A control that is visible on the card->controls list can be freed at any time.
This means we must not access any of its memory while not holding the
controls_rw_lock. Otherwise we risk a use after free access.
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Acked-by: Jaroslav Kysela <perex@perex.cz>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID:
|
int snd_ctl_replace(struct snd_card *card, struct snd_kcontrol *kcontrol,
bool add_on_replace)
{
struct snd_ctl_elem_id id;
unsigned int count;
unsigned int idx;
struct snd_kcontrol *old;
int ret;
if (!kcontrol)
return -EINVAL;
if (snd_BUG_ON(!card || !kcontrol->info)) {
ret = -EINVAL;
goto error;
}
id = kcontrol->id;
down_write(&card->controls_rwsem);
old = snd_ctl_find_id(card, &id);
if (!old) {
if (add_on_replace)
goto add;
up_write(&card->controls_rwsem);
ret = -EINVAL;
goto error;
}
ret = snd_ctl_remove(card, old);
if (ret < 0) {
up_write(&card->controls_rwsem);
goto error;
}
add:
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
ret = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
count = kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return ret;
}
| 166,294
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void toggle_fpga_eeprom_bus(bool cpu_own)
{
qrio_gpio_direction_output(GPIO_A, PROM_SEL_L, !cpu_own);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
|
static void toggle_fpga_eeprom_bus(bool cpu_own)
{
qrio_gpio_direction_output(QRIO_GPIO_A, PROM_SEL_L, !cpu_own);
}
| 169,634
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int zrle_send_framebuffer_update(VncState *vs, int x, int y,
int w, int h)
{
bool be = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);
size_t bytes;
int zywrle_level;
if (vs->zrle.type == VNC_ENCODING_ZYWRLE) {
if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1
|| vs->tight.quality == 9) {
zywrle_level = 0;
vs->zrle.type = VNC_ENCODING_ZRLE;
} else if (vs->tight.quality < 3) {
zywrle_level = 3;
} else if (vs->tight.quality < 6) {
zywrle_level = 2;
} else {
zywrle_level = 1;
}
} else {
zywrle_level = 0;
}
vnc_zrle_start(vs);
switch(vs->clientds.pf.bytes_per_pixel) {
case 1:
zrle_encode_8ne(vs, x, y, w, h, zywrle_level);
break;
case 2:
if (vs->clientds.pf.gmax > 0x1F) {
if (be) {
zrle_encode_16be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_16le(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_15be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_15le(vs, x, y, w, h, zywrle_level);
}
}
break;
case 4:
{
bool fits_in_ls3bytes;
bool fits_in_ms3bytes;
fits_in_ls3bytes =
((vs->clientds.pf.rmax << vs->clientds.pf.rshift) < (1 << 24) &&
(vs->clientds.pf.gmax << vs->clientds.pf.gshift) < (1 << 24) &&
(vs->clientds.pf.bmax << vs->clientds.pf.bshift) < (1 << 24));
fits_in_ms3bytes = (vs->clientds.pf.rshift > 7 &&
vs->clientds.pf.gshift > 7 &&
vs->clientds.pf.bshift > 7);
if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) {
if (be) {
zrle_encode_24abe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ale(vs, x, y, w, h, zywrle_level);
}
} else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) {
if (be) {
zrle_encode_24bbe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ble(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_32be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_32le(vs, x, y, w, h, zywrle_level);
}
}
}
break;
}
vnc_zrle_stop(vs);
bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION);
vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type);
vnc_write_u32(vs, bytes);
vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset);
return 1;
}
Commit Message:
CWE ID: CWE-125
|
static int zrle_send_framebuffer_update(VncState *vs, int x, int y,
int w, int h)
{
bool be = vs->client_be;
size_t bytes;
int zywrle_level;
if (vs->zrle.type == VNC_ENCODING_ZYWRLE) {
if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1
|| vs->tight.quality == 9) {
zywrle_level = 0;
vs->zrle.type = VNC_ENCODING_ZRLE;
} else if (vs->tight.quality < 3) {
zywrle_level = 3;
} else if (vs->tight.quality < 6) {
zywrle_level = 2;
} else {
zywrle_level = 1;
}
} else {
zywrle_level = 0;
}
vnc_zrle_start(vs);
switch (vs->client_pf.bytes_per_pixel) {
case 1:
zrle_encode_8ne(vs, x, y, w, h, zywrle_level);
break;
case 2:
if (vs->client_pf.gmax > 0x1F) {
if (be) {
zrle_encode_16be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_16le(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_15be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_15le(vs, x, y, w, h, zywrle_level);
}
}
break;
case 4:
{
bool fits_in_ls3bytes;
bool fits_in_ms3bytes;
fits_in_ls3bytes =
((vs->client_pf.rmax << vs->client_pf.rshift) < (1 << 24) &&
(vs->client_pf.gmax << vs->client_pf.gshift) < (1 << 24) &&
(vs->client_pf.bmax << vs->client_pf.bshift) < (1 << 24));
fits_in_ms3bytes = (vs->client_pf.rshift > 7 &&
vs->client_pf.gshift > 7 &&
vs->client_pf.bshift > 7);
if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) {
if (be) {
zrle_encode_24abe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ale(vs, x, y, w, h, zywrle_level);
}
} else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) {
if (be) {
zrle_encode_24bbe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ble(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_32be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_32le(vs, x, y, w, h, zywrle_level);
}
}
}
break;
}
vnc_zrle_stop(vs);
bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION);
vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type);
vnc_write_u32(vs, bytes);
vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset);
return 1;
}
| 165,468
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.psnr.psnr[0] < min_psnr_)
min_psnr_ = pkt->data.psnr.psnr[0];
}
| 174,512
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool TokenExitsSVG(const CompactHTMLToken& token) {
return DeprecatedEqualIgnoringCase(token.Data(),
SVGNames::foreignObjectTag.LocalName());
}
Commit Message: HTML parser: Fix "HTML integration point" implementation in HTMLTreeBuilderSimulator.
HTMLTreeBuilderSimulator assumed only <foreignObject> as an HTML
integration point. This CL adds <annotation-xml>, <desc>, and SVG
<title>.
Bug: 805924
Change-Id: I6793d9163d4c6bc8bf0790415baedddaac7a1fc2
Reviewed-on: https://chromium-review.googlesource.com/964038
Commit-Queue: Kent Tamura <tkent@chromium.org>
Reviewed-by: Kouhei Ueno <kouhei@chromium.org>
Cr-Commit-Position: refs/heads/master@{#543634}
CWE ID: CWE-79
|
static bool TokenExitsSVG(const CompactHTMLToken& token) {
| 173,255
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) {
ui::Texture* container = image_transport_clients_[surface_id];
DCHECK(container);
if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME ||
can_lock_compositor_ == NO_PENDING_COMMIT ||
resize_locks_.empty())
return false;
gfx::Size container_size = ConvertSizeToDIP(this, container->size());
ResizeLockList::iterator it = resize_locks_.begin();
while (it != resize_locks_.end()) {
if ((*it)->expected_size() == container_size)
break;
++it;
}
return it == resize_locks_.end() || ++it != resize_locks_.end();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) {
bool RenderWidgetHostViewAura::ShouldSkipFrame(const gfx::Size& size) {
if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME ||
can_lock_compositor_ == NO_PENDING_COMMIT ||
resize_locks_.empty())
return false;
gfx::Size container_size = ConvertSizeToDIP(this, size);
ResizeLockList::iterator it = resize_locks_.begin();
while (it != resize_locks_.end()) {
if ((*it)->expected_size() == container_size)
break;
++it;
}
return it == resize_locks_.end() || ++it != resize_locks_.end();
}
| 171,386
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void SetState(MediaStreamType stream_type, MediaRequestState new_state) {
if (stream_type == NUM_MEDIA_TYPES) {
for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
state_[static_cast<MediaStreamType>(i)] = new_state;
}
} else {
state_[stream_type] = new_state;
}
MediaObserver* media_observer =
GetContentClient()->browser()->GetMediaObserver();
if (!media_observer)
return;
media_observer->OnMediaRequestStateChanged(
target_process_id_, target_frame_id_, page_request_id,
security_origin.GetURL(), stream_type, new_state);
}
Commit Message: Fix MediaObserver notifications in MediaStreamManager.
This CL fixes the stream type used to notify MediaObserver about
cancelled MediaStream requests.
Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate
that all stream types should be cancelled.
However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this
way and the request to update the UI is ignored.
This CL sends a separate notification for each stream type so that the
UI actually gets updated for all stream types in use.
Bug: 816033
Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405
Reviewed-on: https://chromium-review.googlesource.com/939630
Commit-Queue: Guido Urdaneta <guidou@chromium.org>
Reviewed-by: Raymes Khoury <raymes@chromium.org>
Cr-Commit-Position: refs/heads/master@{#540122}
CWE ID: CWE-20
|
void SetState(MediaStreamType stream_type, MediaRequestState new_state) {
if (stream_type == NUM_MEDIA_TYPES) {
for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
state_[static_cast<MediaStreamType>(i)] = new_state;
}
} else {
state_[stream_type] = new_state;
}
MediaObserver* media_observer =
GetContentClient()->browser()->GetMediaObserver();
if (!media_observer)
return;
if (stream_type == NUM_MEDIA_TYPES) {
for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
media_observer->OnMediaRequestStateChanged(
target_process_id_, target_frame_id_, page_request_id,
security_origin.GetURL(), static_cast<MediaStreamType>(i),
new_state);
}
} else {
media_observer->OnMediaRequestStateChanged(
target_process_id_, target_frame_id_, page_request_id,
security_origin.GetURL(), stream_type, new_state);
}
}
| 172,734
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool asn1_write_LDAPString(struct asn1_data *data, const char *s)
{
asn1_write(data, s, strlen(s));
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
|
bool asn1_write_LDAPString(struct asn1_data *data, const char *s)
{
return asn1_write(data, s, strlen(s));
}
| 164,590
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE || pg > 6) {
return -1;
}
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
if (pg == 6) {
return -1; /* avoid page pg + 1 */
}
ptr2 = (itd->bufptr[pg + 1] & ITD_BUFPTR_MASK);
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
}
}
return 0;
}
Commit Message:
CWE ID: CWE-399
|
static int ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE || pg > 6) {
return -1;
}
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
if (pg == 6) {
qemu_sglist_destroy(&ehci->isgl);
return -1; /* avoid page pg + 1 */
}
ptr2 = (itd->bufptr[pg + 1] & ITD_BUFPTR_MASK);
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
}
}
return 0;
}
| 164,912
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BluetoothDeviceChromeOS::Release() {
DCHECK(agent_.get());
DCHECK(pairing_delegate_);
VLOG(1) << object_path_.value() << ": Release";
pincode_callback_.Reset();
passkey_callback_.Reset();
confirmation_callback_.Reset();
UnregisterAgent();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BluetoothDeviceChromeOS::Release() {
| 171,233
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t ProCamera2Client::dump(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("ProCamera2Client[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264
|
status_t ProCamera2Client::dump(int fd, const Vector<String16>& args) {
return BasicClient::dump(fd, args);
}
status_t ProCamera2Client::dumpClient(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("ProCamera2Client[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
| 173,940
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
int newUid, uid_t callerUid) {
ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
const int fd = socket.get();
struct stat info;
if (fstat(fd, &info)) {
return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
}
if (info.st_uid != callerUid) {
return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
}
if (S_ISSOCK(info.st_mode) == 0) {
return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
}
int optval;
socklen_t optlen;
netdutils::Status status =
getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
if (status != netdutils::status::ok) {
return status;
}
if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
}
if (fchown(fd, newUid, -1)) {
return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
}
return netdutils::status::ok;
}
Commit Message: Set optlen for UDP-encap check in XfrmController
When setting the socket owner for an encap socket XfrmController will
first attempt to verify that the socket has the UDP-encap socket option
set. When doing so it would pass in an uninitialized optlen parameter
which could cause the call to not modify the option value if the optlen
happened to be too short. So for example if the stack happened to
contain a zero where optlen was located the check would fail and the
socket owner would not be changed.
Fix this by setting optlen to the size of the option value parameter.
Test: run cts -m CtsNetTestCases
BUG: 111650288
Change-Id: I57b6e9dba09c1acda71e3ec2084652e961667bd9
(cherry picked from commit fc42a105147310bd680952d4b71fe32974bd8506)
CWE ID: CWE-909
|
netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
int newUid, uid_t callerUid) {
ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
const int fd = socket.get();
struct stat info;
if (fstat(fd, &info)) {
return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
}
if (info.st_uid != callerUid) {
return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
}
if (S_ISSOCK(info.st_mode) == 0) {
return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
}
int optval;
socklen_t optlen = sizeof(optval);
netdutils::Status status =
getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
if (status != netdutils::status::ok) {
return status;
}
if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
}
if (fchown(fd, newUid, -1)) {
return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
}
return netdutils::status::ok;
}
| 174,073
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool DoTouchScroll(const gfx::Point& point,
const gfx::Vector2d& distance,
bool wait_until_scrolled) {
EXPECT_EQ(0, GetScrollTop());
int scrollHeight = ExecuteScriptAndExtractInt(
"document.documentElement.scrollHeight");
EXPECT_EQ(1200, scrollHeight);
scoped_refptr<FrameWatcher> frame_watcher(new FrameWatcher());
frame_watcher->AttachTo(shell()->web_contents());
SyntheticSmoothScrollGestureParams params;
params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT;
params.anchor = gfx::PointF(point);
params.distances.push_back(-distance);
runner_ = new MessageLoopRunner();
std::unique_ptr<SyntheticSmoothScrollGesture> gesture(
new SyntheticSmoothScrollGesture(params));
GetWidgetHost()->QueueSyntheticGesture(
std::move(gesture),
base::Bind(&TouchActionBrowserTest::OnSyntheticGestureCompleted,
base::Unretained(this)));
runner_->Run();
runner_ = NULL;
while (wait_until_scrolled &&
frame_watcher->LastMetadata().root_scroll_offset.y() <= 0) {
frame_watcher->WaitFrames(1);
}
int scrollTop = GetScrollTop();
if (scrollTop == 0)
return false;
EXPECT_EQ(distance.y(), scrollTop);
return true;
}
Commit Message: Drive out additional flakiness of TouchAction browser test.
It is relatively stable but it has flaked a couple of times specifically
with this:
Actual: 44
Expected: distance.y()
Which is: 45
I presume that the failure is either we aren't waiting for the additional
frame or a subpixel scrolling problem. As a speculative fix wait for the
pixel item we are waiting to scroll for.
BUG=376668
Review-Url: https://codereview.chromium.org/2281613002
Cr-Commit-Position: refs/heads/master@{#414525}
CWE ID: CWE-119
|
bool DoTouchScroll(const gfx::Point& point,
const gfx::Vector2d& distance,
bool wait_until_scrolled) {
EXPECT_EQ(0, GetScrollTop());
int scrollHeight = ExecuteScriptAndExtractInt(
"document.documentElement.scrollHeight");
EXPECT_EQ(1200, scrollHeight);
scoped_refptr<FrameWatcher> frame_watcher(new FrameWatcher());
frame_watcher->AttachTo(shell()->web_contents());
SyntheticSmoothScrollGestureParams params;
params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT;
params.anchor = gfx::PointF(point);
params.distances.push_back(-distance);
runner_ = new MessageLoopRunner();
std::unique_ptr<SyntheticSmoothScrollGesture> gesture(
new SyntheticSmoothScrollGesture(params));
GetWidgetHost()->QueueSyntheticGesture(
std::move(gesture),
base::Bind(&TouchActionBrowserTest::OnSyntheticGestureCompleted,
base::Unretained(this)));
runner_->Run();
runner_ = NULL;
while (wait_until_scrolled &&
frame_watcher->LastMetadata().root_scroll_offset.y() <
distance.y()) {
frame_watcher->WaitFrames(1);
}
int scrollTop = GetScrollTop();
if (scrollTop == 0)
return false;
EXPECT_EQ(distance.y(), scrollTop);
return true;
}
| 171,600
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PP_Bool LaunchSelLdr(PP_Instance instance,
const char* alleged_url,
int socket_count,
void* imc_handles) {
std::vector<nacl::FileDescriptor> sockets;
IPC::Sender* sender = content::RenderThread::Get();
if (sender == NULL)
sender = g_background_thread_sender.Pointer()->get();
IPC::ChannelHandle channel_handle;
if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl(
GURL(alleged_url), socket_count, &sockets,
&channel_handle))) {
return PP_FALSE;
}
bool invalid_handle = channel_handle.name.empty();
#if defined(OS_POSIX)
if (!invalid_handle)
invalid_handle = (channel_handle.socket.fd == -1);
#endif
if (!invalid_handle)
g_channel_handle_map.Get()[instance] = channel_handle;
CHECK(static_cast<int>(sockets.size()) == socket_count);
for (int i = 0; i < socket_count; i++) {
static_cast<nacl::Handle*>(imc_handles)[i] =
nacl::ToNativeHandle(sockets[i]);
}
return PP_TRUE;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
PP_Bool LaunchSelLdr(PP_Instance instance,
const char* alleged_url, int socket_count,
void* imc_handles) {
std::vector<nacl::FileDescriptor> sockets;
IPC::Sender* sender = content::RenderThread::Get();
if (sender == NULL)
sender = g_background_thread_sender.Pointer()->get();
if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl(
GURL(alleged_url), socket_count, &sockets)))
return PP_FALSE;
CHECK(static_cast<int>(sockets.size()) == socket_count);
for (int i = 0; i < socket_count; i++) {
static_cast<nacl::Handle*>(imc_handles)[i] =
nacl::ToNativeHandle(sockets[i]);
}
return PP_TRUE;
}
| 170,736
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: cib_remote_msg(gpointer data)
{
const char *value = NULL;
xmlNode *command = NULL;
cib_client_t *client = data;
crm_trace("%s callback", client->encrypted ? "secure" : "clear-text");
command = crm_recv_remote_msg(client->session, client->encrypted);
if (command == NULL) {
return -1;
}
value = crm_element_name(command);
if (safe_str_neq(value, "cib_command")) {
crm_log_xml_trace(command, "Bad command: ");
goto bail;
}
if (client->name == NULL) {
value = crm_element_value(command, F_CLIENTNAME);
if (value == NULL) {
client->name = strdup(client->id);
} else {
client->name = strdup(value);
}
}
if (client->callback_id == NULL) {
value = crm_element_value(command, F_CIB_CALLBACK_TOKEN);
if (value != NULL) {
client->callback_id = strdup(value);
crm_trace("Callback channel for %s is %s", client->id, client->callback_id);
} else {
client->callback_id = strdup(client->id);
}
}
/* unset dangerous options */
xml_remove_prop(command, F_ORIG);
xml_remove_prop(command, F_CIB_HOST);
xml_remove_prop(command, F_CIB_GLOBAL_UPDATE);
crm_xml_add(command, F_TYPE, T_CIB);
crm_xml_add(command, F_CIB_CLIENTID, client->id);
crm_xml_add(command, F_CIB_CLIENTNAME, client->name);
#if ENABLE_ACL
crm_xml_add(command, F_CIB_USER, client->user);
#endif
if (crm_element_value(command, F_CIB_CALLID) == NULL) {
char *call_uuid = crm_generate_uuid();
/* fix the command */
crm_xml_add(command, F_CIB_CALLID, call_uuid);
free(call_uuid);
}
if (crm_element_value(command, F_CIB_CALLOPTS) == NULL) {
crm_xml_add_int(command, F_CIB_CALLOPTS, 0);
}
crm_log_xml_trace(command, "Remote command: ");
cib_common_callback_worker(0, 0, command, client, TRUE);
bail:
free_xml(command);
command = NULL;
return 0;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_remote_msg(gpointer data)
static void
cib_handle_remote_msg(cib_client_t *client, xmlNode *command)
{
const char *value = NULL;
value = crm_element_name(command);
if (safe_str_neq(value, "cib_command")) {
crm_log_xml_trace(command, "Bad command: ");
return;
}
if (client->name == NULL) {
value = crm_element_value(command, F_CLIENTNAME);
if (value == NULL) {
client->name = strdup(client->id);
} else {
client->name = strdup(value);
}
}
if (client->callback_id == NULL) {
value = crm_element_value(command, F_CIB_CALLBACK_TOKEN);
if (value != NULL) {
client->callback_id = strdup(value);
crm_trace("Callback channel for %s is %s", client->id, client->callback_id);
} else {
client->callback_id = strdup(client->id);
}
}
/* unset dangerous options */
xml_remove_prop(command, F_ORIG);
xml_remove_prop(command, F_CIB_HOST);
xml_remove_prop(command, F_CIB_GLOBAL_UPDATE);
crm_xml_add(command, F_TYPE, T_CIB);
crm_xml_add(command, F_CIB_CLIENTID, client->id);
crm_xml_add(command, F_CIB_CLIENTNAME, client->name);
#if ENABLE_ACL
crm_xml_add(command, F_CIB_USER, client->user);
#endif
if (crm_element_value(command, F_CIB_CALLID) == NULL) {
char *call_uuid = crm_generate_uuid();
/* fix the command */
crm_xml_add(command, F_CIB_CALLID, call_uuid);
free(call_uuid);
}
if (crm_element_value(command, F_CIB_CALLOPTS) == NULL) {
crm_xml_add_int(command, F_CIB_CALLOPTS, 0);
}
crm_log_xml_trace(command, "Remote command: ");
cib_common_callback_worker(0, 0, command, client, TRUE);
}
int
cib_remote_msg(gpointer data)
{
xmlNode *command = NULL;
cib_client_t *client = data;
int disconnected = 0;
int timeout = client->remote_auth ? -1 : 1000;
crm_trace("%s callback", client->encrypted ? "secure" : "clear-text");
#ifdef HAVE_GNUTLS_GNUTLS_H
if (client->encrypted && (client->handshake_complete == FALSE)) {
int rc = 0;
/* Muliple calls to handshake will be required, this callback
* will be invoked once the client sends more handshake data. */
do {
rc = gnutls_handshake(*client->session);
if (rc < 0 && rc != GNUTLS_E_AGAIN) {
crm_err("Remote cib tls handshake failed");
return -1;
}
} while (rc == GNUTLS_E_INTERRUPTED);
if (rc == 0) {
crm_debug("Remote cib tls handshake completed");
client->handshake_complete = TRUE;
if (client->remote_auth_timeout) {
g_source_remove(client->remote_auth_timeout);
}
/* after handshake, clients must send auth in a few seconds */
client->remote_auth_timeout = g_timeout_add(REMOTE_AUTH_TIMEOUT, remote_auth_timeout_cb, client);
}
return 0;
}
#endif
crm_recv_remote_msg(client->session, &client->recv_buf, client->encrypted, timeout, &disconnected);
/* must pass auth before we will process anything else */
if (client->remote_auth == FALSE) {
xmlNode *reg;
#if ENABLE_ACL
const char *user = NULL;
#endif
command = crm_parse_remote_buffer(&client->recv_buf);
if (cib_remote_auth(command) == FALSE) {
free_xml(command);
return -1;
}
crm_debug("remote connection authenticated successfully");
client->remote_auth = TRUE;
g_source_remove(client->remote_auth_timeout);
client->remote_auth_timeout = 0;
client->name = crm_element_value_copy(command, "name");
#if ENABLE_ACL
user = crm_element_value(command, "user");
if (user) {
new_client->user = strdup(user);
}
#endif
/* send ACK */
reg = create_xml_node(NULL, "cib_result");
crm_xml_add(reg, F_CIB_OPERATION, CRM_OP_REGISTER);
crm_xml_add(reg, F_CIB_CLIENTID, client->id);
crm_send_remote_msg(client->session, reg, client->encrypted);
free_xml(reg);
free_xml(command);
}
command = crm_parse_remote_buffer(&client->recv_buf);
while (command) {
crm_trace("command received");
cib_handle_remote_msg(client, command);
free_xml(command);
command = crm_parse_remote_buffer(&client->recv_buf);
}
if (disconnected) {
crm_trace("disconnected while receiving remote cib msg.");
return -1;
}
return 0;
}
| 166,149
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void EnqueueData() {
scoped_array<uint8> audio_data(new uint8[kRawDataSize]);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_channel(), 0u);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_frame(), 0u);
size_t length = kRawDataSize / algorithm_.bytes_per_channel();
switch (algorithm_.bytes_per_channel()) {
case 4:
WriteFakeData<int32>(audio_data.get(), length);
break;
case 2:
WriteFakeData<int16>(audio_data.get(), length);
break;
case 1:
WriteFakeData<uint8>(audio_data.get(), length);
break;
default:
NOTREACHED() << "Unsupported audio bit depth in crossfade.";
}
algorithm_.EnqueueBuffer(new DataBuffer(audio_data.Pass(), kRawDataSize));
bytes_enqueued_ += kRawDataSize;
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void EnqueueData() {
scoped_array<uint8> audio_data(new uint8[kRawDataSize]);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_channel(), 0u);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_frame(), 0u);
// The value of the data is meaningless; we just want non-zero data to
// differentiate it from muted data.
memset(audio_data.get(), 1, kRawDataSize);
algorithm_.EnqueueBuffer(new DataBuffer(audio_data.Pass(), kRawDataSize));
bytes_enqueued_ += kRawDataSize;
}
| 171,532
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void jp2_box_dump(jp2_box_t *box, FILE *out)
{
jp2_boxinfo_t *boxinfo;
boxinfo = jp2_boxinfolookup(box->type);
assert(boxinfo);
fprintf(out, "JP2 box: ");
fprintf(out, "type=%c%s%c (0x%08"PRIxFAST32"); length=%"PRIuFAST32"\n", '"', boxinfo->name,
'"', box->type, box->len);
if (box->ops->dumpdata) {
(*box->ops->dumpdata)(box, out);
}
}
Commit Message: Fixed another problem with incorrect cleanup of JP2 box data upon error.
CWE ID: CWE-476
|
void jp2_box_dump(jp2_box_t *box, FILE *out)
{
jp2_boxinfo_t *boxinfo;
boxinfo = jp2_boxinfolookup(box->type);
assert(boxinfo);
fprintf(out, "JP2 box: ");
fprintf(out, "type=%c%s%c (0x%08"PRIxFAST32"); length=%"PRIuFAST32"\n", '"',
boxinfo->name, '"', box->type, box->len);
if (box->ops->dumpdata) {
(*box->ops->dumpdata)(box, out);
}
}
| 168,472
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void encode_frame(vpx_codec_ctx_t *codec,
vpx_image_t *img,
int frame_index,
VpxVideoWriter *writer) {
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0,
VPX_DL_GOOD_QUALITY);
if (res != VPX_CODEC_OK)
die_codec(codec, "Failed to encode frame");
while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
if (!vpx_video_writer_write_frame(writer,
pkt->data.frame.buf,
pkt->data.frame.sz,
pkt->data.frame.pts)) {
die_codec(codec, "Failed to write compressed frame");
}
printf(keyframe ? "K" : ".");
fflush(stdout);
}
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
static void encode_frame(vpx_codec_ctx_t *codec,
static int encode_frame(vpx_codec_ctx_t *codec,
vpx_image_t *img,
int frame_index,
VpxVideoWriter *writer) {
int got_pkts = 0;
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0,
VPX_DL_GOOD_QUALITY);
if (res != VPX_CODEC_OK)
die_codec(codec, "Failed to encode frame");
while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
got_pkts = 1;
if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
if (!vpx_video_writer_write_frame(writer,
pkt->data.frame.buf,
pkt->data.frame.sz,
pkt->data.frame.pts)) {
die_codec(codec, "Failed to write compressed frame");
}
printf(keyframe ? "K" : ".");
fflush(stdout);
}
}
return got_pkts;
}
| 174,481
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(SplFileObject, setMaxLineLen)
{
long max_len;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) {
return;
}
if (max_len < 0) {
zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero");
return;
}
intern->u.file.max_line_len = max_len;
} /* }}} */
/* {{{ proto int SplFileObject::getMaxLineLen()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, setMaxLineLen)
{
long max_len;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) {
return;
}
if (max_len < 0) {
zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero");
return;
}
intern->u.file.max_line_len = max_len;
} /* }}} */
/* {{{ proto int SplFileObject::getMaxLineLen()
| 167,058
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size)
{
bee_t *bee = ic->bee;
bee_user_t *bu = bee_user_by_handle(bee, ic, handle);
if (bee->ui->ft_in_start) {
return bee->ui->ft_in_start(bee, bu, file_name, file_size);
} else {
return NULL;
}
}
Commit Message: imcb_file_send_start: handle ft attempts from non-existing users
CWE ID: CWE-476
|
file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size)
{
bee_t *bee = ic->bee;
bee_user_t *bu = bee_user_by_handle(bee, ic, handle);
if (bee->ui->ft_in_start && bu) {
return bee->ui->ft_in_start(bee, bu, file_name, file_size);
} else {
return NULL;
}
}
| 168,506
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static char *print_value( cJSON *item, int depth, int fmt )
{
char *out = 0;
if ( ! item )
return 0;
switch ( ( item->type ) & 255 ) {
case cJSON_NULL: out = cJSON_strdup( "null" ); break;
case cJSON_False: out = cJSON_strdup( "false" ); break;
case cJSON_True: out = cJSON_strdup( "true" ); break;
case cJSON_Number: out = print_number( item ); break;
case cJSON_String: out = print_string( item ); break;
case cJSON_Array: out = print_array( item, depth, fmt ); break;
case cJSON_Object: out = print_object( item, depth, fmt ); break;
}
return out;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
static char *print_value( cJSON *item, int depth, int fmt )
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p)
{
char *out=0;
if (!item) return 0;
if (p)
{
switch ((item->type)&255)
{
case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;}
case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;}
case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;}
case cJSON_Number: out=print_number(item,p);break;
case cJSON_String: out=print_string(item,p);break;
case cJSON_Array: out=print_array(item,depth,fmt,p);break;
case cJSON_Object: out=print_object(item,depth,fmt,p);break;
}
}
else
{
switch ((item->type)&255)
{
case cJSON_NULL: out=cJSON_strdup("null"); break;
case cJSON_False: out=cJSON_strdup("false");break;
case cJSON_True: out=cJSON_strdup("true"); break;
case cJSON_Number: out=print_number(item,0);break;
case cJSON_String: out=print_string(item,0);break;
case cJSON_Array: out=print_array(item,depth,fmt,0);break;
case cJSON_Object: out=print_object(item,depth,fmt,0);break;
}
}
return out;
}
| 167,311
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo(
int child_id,
int render_view_route_id,
int render_frame_route_id,
PreviewsState previews_state,
bool download,
ResourceContext* context) {
return new ResourceRequestInfoImpl(
ResourceRequesterInfo::CreateForDownloadOrPageSave(child_id),
render_view_route_id,
-1, // frame_tree_node_id
ChildProcessHost::kInvalidUniqueID, // plugin_child_id
MakeRequestID(), render_frame_route_id,
false, // is_main_frame
{}, // fetch_window_id
RESOURCE_TYPE_SUB_RESOURCE, ui::PAGE_TRANSITION_LINK,
download, // is_download
false, // is_stream
download, // allow_download
false, // has_user_gesture
false, // enable_load_timing
false, // enable_upload_progress
false, // do_not_prompt_for_login
false, // keepalive
network::mojom::ReferrerPolicy::kDefault,
false, // is_prerendering
context,
false, // report_raw_headers
false, // report_security_info
true, // is_async
previews_state, // previews_state
nullptr, // body
false); // initiated_in_secure_context
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <japhet@chromium.org>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <clamy@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
|
ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo(
int child_id,
int render_view_route_id,
int render_frame_route_id,
int frame_tree_node_id,
PreviewsState previews_state,
bool download,
ResourceContext* context) {
return new ResourceRequestInfoImpl(
ResourceRequesterInfo::CreateForDownloadOrPageSave(child_id),
render_view_route_id, frame_tree_node_id,
ChildProcessHost::kInvalidUniqueID, // plugin_child_id
MakeRequestID(), render_frame_route_id,
false, // is_main_frame
{}, // fetch_window_id
RESOURCE_TYPE_SUB_RESOURCE, ui::PAGE_TRANSITION_LINK,
download, // is_download
false, // is_stream
download, // allow_download
false, // has_user_gesture
false, // enable_load_timing
false, // enable_upload_progress
false, // do_not_prompt_for_login
false, // keepalive
network::mojom::ReferrerPolicy::kDefault,
false, // is_prerendering
context,
false, // report_raw_headers
false, // report_security_info
true, // is_async
previews_state, // previews_state
nullptr, // body
false); // initiated_in_secure_context
}
| 173,026
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: jbig2_decode_mmr_init(Jbig2MmrCtx *mmr, int width, int height, const byte *data, size_t size)
{
int i;
uint32_t word = 0;
mmr->width = width;
mmr->size = size;
mmr->data_index = 0;
mmr->bit_index = 0;
for (i = 0; i < size && i < 4; i++)
word |= (data[i] << ((3 - i) << 3));
mmr->word = word;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_decode_mmr_init(Jbig2MmrCtx *mmr, int width, int height, const byte *data, size_t size)
{
size_t i;
uint32_t word = 0;
mmr->width = width;
mmr->size = size;
mmr->data_index = 0;
mmr->bit_index = 0;
for (i = 0; i < size && i < 4; i++)
word |= (data[i] << ((3 - i) << 3));
mmr->word = word;
}
| 165,493
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
if (length > INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX);
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
| 167,066
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: char* _multi_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc( len + 2 );
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
chr[ len ++ ] = '\0';
return chr;
}
Commit Message: New Pre Source
CWE ID: CWE-119
|
char* _multi_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return NULL;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc( len + 2 );
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
chr[ len ++ ] = '\0';
return chr;
}
| 169,313
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: NavigateParams::NavigateParams(Browser* a_browser,
TabContentsWrapper* a_target_contents)
: target_contents(a_target_contents),
source_contents(NULL),
disposition(CURRENT_TAB),
transition(content::PAGE_TRANSITION_LINK),
tabstrip_index(-1),
tabstrip_add_types(TabStripModel::ADD_ACTIVE),
window_action(NO_ACTION),
user_gesture(true),
path_behavior(RESPECT),
ref_behavior(IGNORE_REF),
browser(a_browser),
profile(NULL) {
}
Commit Message: Fix memory error in previous CL.
BUG=100315
BUG=99016
TEST=Memory bots go green
Review URL: http://codereview.chromium.org/8302001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
NavigateParams::NavigateParams(Browser* a_browser,
TabContentsWrapper* a_target_contents)
: target_contents(a_target_contents),
source_contents(NULL),
disposition(CURRENT_TAB),
transition(content::PAGE_TRANSITION_LINK),
is_renderer_initiated(false),
tabstrip_index(-1),
tabstrip_add_types(TabStripModel::ADD_ACTIVE),
window_action(NO_ACTION),
user_gesture(true),
path_behavior(RESPECT),
ref_behavior(IGNORE_REF),
browser(a_browser),
profile(NULL) {
}
| 170,250
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void Block::SetKey(bool bKey)
{
if (bKey)
m_flags |= static_cast<unsigned char>(1 << 7);
else
m_flags &= 0x7F;
}
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
|
void Block::SetKey(bool bKey)
Block::Lacing Block::GetLacing() const {
const int value = int(m_flags & 0x06) >> 1;
return static_cast<Lacing>(value);
}
| 174,440
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void SetManualFallbacks(bool enabled) {
std::vector<std::string> features = {
password_manager::features::kEnableManualFallbacksFilling.name,
password_manager::features::kEnableManualFallbacksFillingStandalone
.name,
password_manager::features::kEnableManualFallbacksGeneration.name};
if (enabled) {
scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","),
std::string());
} else {
scoped_feature_list_.InitFromCommandLine(std::string(),
base::JoinString(features, ","));
}
}
Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature.
Fixing names of password_manager kEnableManualFallbacksFilling feature
as per the naming convention.
Bug: 785953
Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03
Reviewed-on: https://chromium-review.googlesource.com/900566
Reviewed-by: Vaclav Brozek <vabr@chromium.org>
Commit-Queue: NIKHIL SAHNI <nikhil.sahni@samsung.com>
Cr-Commit-Position: refs/heads/master@{#534923}
CWE ID: CWE-264
|
void SetManualFallbacks(bool enabled) {
std::vector<std::string> features = {
password_manager::features::kManualFallbacksFilling.name,
password_manager::features::kEnableManualFallbacksFillingStandalone
.name,
password_manager::features::kEnableManualFallbacksGeneration.name};
if (enabled) {
scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","),
std::string());
} else {
scoped_feature_list_.InitFromCommandLine(std::string(),
base::JoinString(features, ","));
}
}
| 171,749
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int SocketStream::DoBeforeConnect() {
next_state_ = STATE_BEFORE_CONNECT_COMPLETE;
if (!context_.get() || !context_->network_delegate()) {
return OK;
}
int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect(
this, io_callback_);
if (result != OK && result != ERR_IO_PENDING)
next_state_ = STATE_CLOSE;
return result;
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
int SocketStream::DoBeforeConnect() {
next_state_ = STATE_BEFORE_CONNECT_COMPLETE;
if (!context_ || !context_->network_delegate())
return OK;
int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect(
this, io_callback_);
if (result != OK && result != ERR_IO_PENDING)
next_state_ = STATE_CLOSE;
return result;
}
| 171,253
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: png_get_asm_flags (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
return (png_ptr? 0L: 0L);
}
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_get_asm_flags (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
PNG_UNUSED(png_ptr)
return 0L;
}
| 172,165
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: prologProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
}
Commit Message: xmlparse.c: Deny internal entities closing the doctype
CWE ID: CWE-611
|
prologProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE);
}
| 169,533
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(FilesystemIterator, getFlags)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK));
} /* }}} */
/* {{{ proto void FilesystemIterator::setFlags(long $flags)
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(FilesystemIterator, getFlags)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK));
} /* }}} */
/* {{{ proto void FilesystemIterator::setFlags(long $flags)
| 167,044
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long mkvparser::UnserializeInt(
IMkvReader* pReader,
long long pos,
long size,
long long& result)
{
assert(pReader);
assert(pos >= 0);
assert(size > 0);
assert(size <= 8);
{
signed char b;
const long status = pReader->Read(pos, 1, (unsigned char*)&b);
if (status < 0)
return status;
result = b;
++pos;
}
for (long i = 1; i < size; ++i)
{
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return 0; //success
}
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 mkvparser::UnserializeInt(
if (size_ >= LONG_MAX) // we need (size+1) chars
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
str = new (std::nothrow) char[size + 1];
if (str == NULL)
return -1;
unsigned char* const buf = reinterpret_cast<unsigned char*>(str);
const long status = pReader->Read(pos, size, buf);
| 174,448
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: std::string utf16ToUtf8(const StringPiece16& utf16) {
ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
if (utf8Length <= 0) {
return {};
}
std::string utf8;
utf8.resize(utf8Length);
utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin());
return utf8;
}
Commit Message: Add bound checks to utf16_to_utf8
Test: ran libaapt2_tests64
Bug: 29250543
Change-Id: I1ebc017af623b6514cf0c493e8cd8e1d59ea26c3
(cherry picked from commit 4781057e78f63e0e99af109cebf3b6a78f4bfbb6)
CWE ID: CWE-119
|
std::string utf16ToUtf8(const StringPiece16& utf16) {
ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
if (utf8Length <= 0) {
return {};
}
std::string utf8;
// Make room for '\0' explicitly.
utf8.resize(utf8Length + 1);
utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8Length + 1);
utf8.resize(utf8Length);
return utf8;
}
| 174,160
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int key_verify(pam_handle_t *pamh, int flags, PKCS11_KEY *authkey)
{
int ok = 0;
unsigned char challenge[30];
unsigned char signature[256];
unsigned int siglen = sizeof signature;
const EVP_MD *md = EVP_sha1();
EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
EVP_PKEY *privkey = PKCS11_get_private_key(authkey);
EVP_PKEY *pubkey = PKCS11_get_public_key(authkey);
/* Verify a SHA-1 hash of random data, signed by the key.
*
* Note that this will not work keys that aren't eligible for signing.
* Unfortunately, libp11 currently has no way of checking
* C_GetAttributeValue(CKA_SIGN), see
* https://github.com/OpenSC/libp11/issues/219. Since we don't want to
* implement try and error, we live with this limitation */
if (1 != randomize(pamh, challenge, sizeof challenge)) {
goto err;
}
if (NULL == pubkey || NULL == privkey || NULL == md_ctx || NULL == md
|| !EVP_SignInit(md_ctx, md)
|| !EVP_SignUpdate(md_ctx, challenge, sizeof challenge)
|| !EVP_SignFinal(md_ctx, signature, &siglen, privkey)
|| !EVP_MD_CTX_reset(md_ctx)
|| !EVP_VerifyInit(md_ctx, md)
|| !EVP_VerifyUpdate(md_ctx, challenge, sizeof challenge)
|| 1 != EVP_VerifyFinal(md_ctx, signature, siglen, pubkey)) {
pam_syslog(pamh, LOG_DEBUG, "Error verifying key: %s\n",
ERR_reason_error_string(ERR_get_error()));
prompt(flags, pamh, PAM_ERROR_MSG, NULL, _("Error verifying key"));
goto err;
}
ok = 1;
err:
if (NULL != pubkey)
EVP_PKEY_free(pubkey);
if (NULL != privkey)
EVP_PKEY_free(privkey);
if (NULL != md_ctx) {
EVP_MD_CTX_free(md_ctx);
}
return ok;
}
Commit Message: Use EVP_PKEY_size() to allocate correct size of signature buffer. (#18)
Do not use fixed buffer size for signature, EVP_SignFinal() requires
buffer for signature at least EVP_PKEY_size(pkey) bytes in size.
Fixes crash when using 4K RSA signatures (https://github.com/OpenSC/pam_p11/issues/16, https://github.com/OpenSC/pam_p11/issues/15)
CWE ID: CWE-119
|
static int key_verify(pam_handle_t *pamh, int flags, PKCS11_KEY *authkey)
{
int ok = 0;
unsigned char challenge[30];
unsigned char *signature = NULL;
unsigned int siglen;
const EVP_MD *md = EVP_sha1();
EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
EVP_PKEY *privkey = PKCS11_get_private_key(authkey);
EVP_PKEY *pubkey = PKCS11_get_public_key(authkey);
if (NULL == privkey)
goto err;
siglen = EVP_PKEY_size(privkey);
if (siglen <= 0)
goto err;
signature = malloc(siglen);
if (NULL == signature)
goto err;
/* Verify a SHA-1 hash of random data, signed by the key.
*
* Note that this will not work keys that aren't eligible for signing.
* Unfortunately, libp11 currently has no way of checking
* C_GetAttributeValue(CKA_SIGN), see
* https://github.com/OpenSC/libp11/issues/219. Since we don't want to
* implement try and error, we live with this limitation */
if (1 != randomize(pamh, challenge, sizeof challenge)) {
goto err;
}
if (NULL == pubkey || NULL == privkey || NULL == md_ctx || NULL == md
|| !EVP_SignInit(md_ctx, md)
|| !EVP_SignUpdate(md_ctx, challenge, sizeof challenge)
|| !EVP_SignFinal(md_ctx, signature, &siglen, privkey)
|| !EVP_MD_CTX_reset(md_ctx)
|| !EVP_VerifyInit(md_ctx, md)
|| !EVP_VerifyUpdate(md_ctx, challenge, sizeof challenge)
|| 1 != EVP_VerifyFinal(md_ctx, signature, siglen, pubkey)) {
pam_syslog(pamh, LOG_DEBUG, "Error verifying key: %s\n",
ERR_reason_error_string(ERR_get_error()));
prompt(flags, pamh, PAM_ERROR_MSG, NULL, _("Error verifying key"));
goto err;
}
ok = 1;
err:
free(signature);
if (NULL != pubkey)
EVP_PKEY_free(pubkey);
if (NULL != privkey)
EVP_PKEY_free(privkey);
if (NULL != md_ctx) {
EVP_MD_CTX_free(md_ctx);
}
return ok;
}
| 169,513
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: my_object_async_throw_error (MyObject *obj, DBusGMethodInvocation *context)
{
IncrementData *data = g_new0(IncrementData, 1);
data->context = context;
g_idle_add ((GSourceFunc)do_async_error, data);
}
Commit Message:
CWE ID: CWE-264
|
my_object_async_throw_error (MyObject *obj, DBusGMethodInvocation *context)
| 165,089
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RenderViewHostImpl::CreateNewWindow(
int route_id,
const ViewHostMsg_CreateWindow_Params& params,
SessionStorageNamespace* session_storage_namespace) {
ViewHostMsg_CreateWindow_Params validated_params(params);
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
delegate_->CreateNewWindow(route_id, validated_params,
session_storage_namespace);
}
Commit Message: Filter more incoming URLs in the CreateWindow path.
BUG=170532
Review URL: https://chromiumcodereview.appspot.com/12036002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderViewHostImpl::CreateNewWindow(
int route_id,
const ViewHostMsg_CreateWindow_Params& params,
SessionStorageNamespace* session_storage_namespace) {
ViewHostMsg_CreateWindow_Params validated_params(params);
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
FilterURL(policy, GetProcess(), false, &validated_params.opener_url);
FilterURL(policy, GetProcess(), true,
&validated_params.opener_security_origin);
delegate_->CreateNewWindow(route_id, validated_params,
session_storage_namespace);
}
| 171,498
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RenderWidgetHostViewGtk::AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params,
int gpu_host_id) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, true, 0);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderWidgetHostViewGtk::AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params,
int gpu_host_id) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, params.surface_handle, 0);
}
| 171,391
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
struct sshbuf *b = NULL;
int r;
const u_char *inblob, *outblob;
size_t inl, outl;
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
(r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
goto out;
if (inl == 0)
state->compression_in_started = 0;
else if (inl != sizeof(state->compression_in_stream)) {
r = SSH_ERR_INTERNAL_ERROR;
goto out;
} else {
state->compression_in_started = 1;
memcpy(&state->compression_in_stream, inblob, inl);
}
if (outl == 0)
state->compression_out_started = 0;
else if (outl != sizeof(state->compression_out_stream)) {
r = SSH_ERR_INTERNAL_ERROR;
goto out;
} else {
state->compression_out_started = 1;
memcpy(&state->compression_out_stream, outblob, outl);
}
r = 0;
out:
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
|
ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
| 168,654
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_pclr_t *pclr = &box->data.pclr;
int lutsize;
unsigned int i;
unsigned int j;
int_fast32_t x;
pclr->lutdata = 0;
if (jp2_getuint16(in, &pclr->numlutents) ||
jp2_getuint8(in, &pclr->numchans)) {
return -1;
}
lutsize = pclr->numlutents * pclr->numchans;
if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) {
return -1;
}
if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < pclr->numchans; ++i) {
if (jp2_getuint8(in, &pclr->bpc[i])) {
return -1;
}
}
for (i = 0; i < pclr->numlutents; ++i) {
for (j = 0; j < pclr->numchans; ++j) {
if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,
(pclr->bpc[j] & 0x7f) + 1, &x)) {
return -1;
}
pclr->lutdata[i * pclr->numchans + j] = x;
}
}
return 0;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476
|
static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_pclr_t *pclr = &box->data.pclr;
int lutsize;
unsigned int i;
unsigned int j;
int_fast32_t x;
pclr->lutdata = 0;
pclr->bpc = 0;
if (jp2_getuint16(in, &pclr->numlutents) ||
jp2_getuint8(in, &pclr->numchans)) {
return -1;
}
lutsize = pclr->numlutents * pclr->numchans;
if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) {
return -1;
}
if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < pclr->numchans; ++i) {
if (jp2_getuint8(in, &pclr->bpc[i])) {
return -1;
}
}
for (i = 0; i < pclr->numlutents; ++i) {
for (j = 0; j < pclr->numchans; ++j) {
if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,
(pclr->bpc[j] & 0x7f) + 1, &x)) {
return -1;
}
pclr->lutdata[i * pclr->numchans + j] = x;
}
}
return 0;
}
| 168,323
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftVPXEncoder::internalSetParameter(OMX_INDEXTYPE index,
const OMX_PTR param) {
const int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
return internalSetBitrateParams(
(const OMX_VIDEO_PARAM_BITRATETYPE *)param);
case OMX_IndexParamVideoVp8:
return internalSetVp8Params(
(const OMX_VIDEO_PARAM_VP8TYPE *)param);
case OMX_IndexParamVideoAndroidVp8Encoder:
return internalSetAndroidVp8Params(
(const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *)param);
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, param);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftVPXEncoder::internalSetParameter(OMX_INDEXTYPE index,
const OMX_PTR param) {
const int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate: {
const OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(const OMX_VIDEO_PARAM_BITRATETYPE*) param;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
return internalSetBitrateParams(bitRate);
}
case OMX_IndexParamVideoVp8: {
const OMX_VIDEO_PARAM_VP8TYPE *vp8Params =
(const OMX_VIDEO_PARAM_VP8TYPE*) param;
if (!isValidOMXParam(vp8Params)) {
return OMX_ErrorBadParameter;
}
return internalSetVp8Params(vp8Params);
}
case OMX_IndexParamVideoAndroidVp8Encoder: {
const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *vp8AndroidParams =
(const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE*) param;
if (!isValidOMXParam(vp8AndroidParams)) {
return OMX_ErrorBadParameter;
}
return internalSetAndroidVp8Params(vp8AndroidParams);
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, param);
}
}
| 174,214
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=26861
CWE ID: CWE-399
|
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
if (SeekBlob(image,offset,SEEK_CUR) < 0)
break;
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 170,122
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BaseRenderingContext2D::setFillStyle(
const StringOrCanvasGradientOrCanvasPattern& style) {
DCHECK(!style.IsNull());
ValidateStateStack();
String color_string;
CanvasStyle* canvas_style = nullptr;
if (style.IsString()) {
color_string = style.GetAsString();
if (color_string == GetState().UnparsedFillColor())
return;
Color parsed_color = 0;
if (!ParseColorOrCurrentColor(parsed_color, color_string))
return;
if (GetState().FillStyle()->IsEquivalentRGBA(parsed_color.Rgb())) {
ModifiableState().SetUnparsedFillColor(color_string);
return;
}
canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb());
} else if (style.IsCanvasGradient()) {
canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient());
} else if (style.IsCanvasPattern()) {
CanvasPattern* canvas_pattern = style.GetAsCanvasPattern();
if (OriginClean() && !canvas_pattern->OriginClean()) {
SetOriginTainted();
ClearResolvedFilters();
}
if (canvas_pattern->GetPattern()->IsTextureBacked())
DisableDeferral(kDisableDeferralReasonUsingTextureBackedPattern);
canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern);
}
DCHECK(canvas_style);
ModifiableState().SetFillStyle(canvas_style);
ModifiableState().SetUnparsedFillColor(color_string);
ModifiableState().ClearResolvedFilter();
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <fs@opera.com>
Commit-Queue: Chris Harrelson <chrishtr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200
|
void BaseRenderingContext2D::setFillStyle(
const StringOrCanvasGradientOrCanvasPattern& style) {
DCHECK(!style.IsNull());
ValidateStateStack();
String color_string;
CanvasStyle* canvas_style = nullptr;
if (style.IsString()) {
color_string = style.GetAsString();
if (color_string == GetState().UnparsedFillColor())
return;
Color parsed_color = 0;
if (!ParseColorOrCurrentColor(parsed_color, color_string))
return;
if (GetState().FillStyle()->IsEquivalentRGBA(parsed_color.Rgb())) {
ModifiableState().SetUnparsedFillColor(color_string);
return;
}
canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb());
} else if (style.IsCanvasGradient()) {
canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient());
} else if (style.IsCanvasPattern()) {
CanvasPattern* canvas_pattern = style.GetAsCanvasPattern();
if (!origin_tainted_by_content_ && !canvas_pattern->OriginClean()) {
SetOriginTaintedByContent();
}
if (canvas_pattern->GetPattern()->IsTextureBacked())
DisableDeferral(kDisableDeferralReasonUsingTextureBackedPattern);
canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern);
}
DCHECK(canvas_style);
ModifiableState().SetFillStyle(canvas_style);
ModifiableState().SetUnparsedFillColor(color_string);
ModifiableState().ClearResolvedFilter();
}
| 172,908
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 left;
UINT32 runlength = 1;
UINT32 planeSize = 0;
left = originalSize;
/**
* We quit the loop if the running compressed size is larger than the original.
* In such cases data will be sent uncompressed.
*/
while (left > 4 && planeSize < originalSize - 4)
{
if (left > 5 && *in == *(in + 1))
{
runlength++;
}
else if (runlength == 1)
{
*out++ = *in;
planeSize++;
}
else if (runlength < 256)
{
*out++ = *in;
*out++ = *in;
*out++ = runlength - 2;
runlength = 1;
planeSize += 3;
}
else
{
*out++ = *in;
*out++ = *in;
*out++ = 0xFF;
*out++ = (runlength & 0x000000FF);
*out++ = (runlength & 0x0000FF00) >> 8;
*out++ = (runlength & 0x00FF0000) >> 16;
*out++ = (runlength & 0xFF000000) >> 24;
runlength = 1;
planeSize += 7;
}
in++;
left--;
}
if (planeSize < originalSize - 4)
CopyMemory(out, in, 4);
planeSize += 4;
return planeSize;
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787
|
static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)
static UINT32 nsc_rle_encode(const BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 left;
UINT32 runlength = 1;
UINT32 planeSize = 0;
left = originalSize;
/**
* We quit the loop if the running compressed size is larger than the original.
* In such cases data will be sent uncompressed.
*/
while (left > 4 && planeSize < originalSize - 4)
{
if (left > 5 && *in == *(in + 1))
{
runlength++;
}
else if (runlength == 1)
{
*out++ = *in;
planeSize++;
}
else if (runlength < 256)
{
*out++ = *in;
*out++ = *in;
*out++ = runlength - 2;
runlength = 1;
planeSize += 3;
}
else
{
*out++ = *in;
*out++ = *in;
*out++ = 0xFF;
*out++ = (runlength & 0x000000FF);
*out++ = (runlength & 0x0000FF00) >> 8;
*out++ = (runlength & 0x00FF0000) >> 16;
*out++ = (runlength & 0xFF000000) >> 24;
runlength = 1;
planeSize += 7;
}
in++;
left--;
}
if (planeSize < originalSize - 4)
CopyMemory(out, in, 4);
planeSize += 4;
return planeSize;
}
| 169,290
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int64 GetOriginalListPrefValue(size_t index) {
return ListPrefInt64Value(*original_update_, index);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
|
int64 GetOriginalListPrefValue(size_t index) {
return original_.GetListPrefValue(index);
}
| 171,323
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void UserSelectionScreen::FillUserDictionary(
user_manager::User* user,
bool is_owner,
bool is_signin_to_add,
proximity_auth::mojom::AuthType auth_type,
const std::vector<std::string>* public_session_recommended_locales,
base::DictionaryValue* user_dict) {
const bool is_public_session =
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT;
const bool is_legacy_supervised_user =
user->GetType() == user_manager::USER_TYPE_SUPERVISED;
const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD;
user_dict->SetString(kKeyUsername, user->GetAccountId().Serialize());
user_dict->SetString(kKeyEmailAddress, user->display_email());
user_dict->SetString(kKeyDisplayName, user->GetDisplayName());
user_dict->SetBoolean(kKeyPublicAccount, is_public_session);
user_dict->SetBoolean(kKeyLegacySupervisedUser, is_legacy_supervised_user);
user_dict->SetBoolean(kKeyChildUser, is_child_user);
user_dict->SetBoolean(kKeyDesktopUser, false);
user_dict->SetInteger(kKeyInitialAuthType, static_cast<int>(auth_type));
user_dict->SetBoolean(kKeySignedIn, user->is_logged_in());
user_dict->SetBoolean(kKeyIsOwner, is_owner);
user_dict->SetBoolean(kKeyIsActiveDirectory, user->IsActiveDirectoryUser());
user_dict->SetBoolean(kKeyAllowFingerprint, AllowFingerprintForUser(user));
FillMultiProfileUserPrefs(user, user_dict, is_signin_to_add);
if (is_public_session) {
AddPublicSessionDetailsToUserDictionaryEntry(
user_dict, public_session_recommended_locales);
}
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org>
Commit-Queue: Jacob Dufault <jdufault@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID:
|
void UserSelectionScreen::FillUserDictionary(
const user_manager::User* user,
bool is_owner,
bool is_signin_to_add,
proximity_auth::mojom::AuthType auth_type,
const std::vector<std::string>* public_session_recommended_locales,
base::DictionaryValue* user_dict) {
const bool is_public_session =
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT;
const bool is_legacy_supervised_user =
user->GetType() == user_manager::USER_TYPE_SUPERVISED;
const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD;
user_dict->SetString(kKeyUsername, user->GetAccountId().Serialize());
user_dict->SetString(kKeyEmailAddress, user->display_email());
user_dict->SetString(kKeyDisplayName, user->GetDisplayName());
user_dict->SetBoolean(kKeyPublicAccount, is_public_session);
user_dict->SetBoolean(kKeyLegacySupervisedUser, is_legacy_supervised_user);
user_dict->SetBoolean(kKeyChildUser, is_child_user);
user_dict->SetBoolean(kKeyDesktopUser, false);
user_dict->SetInteger(kKeyInitialAuthType, static_cast<int>(auth_type));
user_dict->SetBoolean(kKeySignedIn, user->is_logged_in());
user_dict->SetBoolean(kKeyIsOwner, is_owner);
user_dict->SetBoolean(kKeyIsActiveDirectory, user->IsActiveDirectoryUser());
user_dict->SetBoolean(kKeyAllowFingerprint, AllowFingerprintForUser(user));
FillMultiProfileUserPrefs(user, user_dict, is_signin_to_add);
if (is_public_session) {
AddPublicSessionDetailsToUserDictionaryEntry(
user_dict, public_session_recommended_locales);
}
}
| 172,200
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool Performance::PassesTimingAllowCheck(
const ResourceResponse& response,
const SecurityOrigin& initiator_security_origin,
const AtomicString& original_timing_allow_origin,
ExecutionContext* context) {
scoped_refptr<const SecurityOrigin> resource_origin =
SecurityOrigin::Create(response.Url());
if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin))
return true;
const AtomicString& timing_allow_origin_string =
original_timing_allow_origin.IsEmpty()
? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin)
: original_timing_allow_origin;
if (timing_allow_origin_string.IsEmpty() ||
EqualIgnoringASCIICase(timing_allow_origin_string, "null"))
return false;
if (timing_allow_origin_string == "*") {
UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin);
return true;
}
const String& security_origin = initiator_security_origin.ToString();
Vector<String> timing_allow_origins;
timing_allow_origin_string.GetString().Split(',', timing_allow_origins);
if (timing_allow_origins.size() > 1) {
UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin);
} else if (timing_allow_origins.size() == 1 &&
timing_allow_origin_string != "*") {
UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin);
}
for (const String& allow_origin : timing_allow_origins) {
const String allow_origin_stripped = allow_origin.StripWhiteSpace();
if (allow_origin_stripped == security_origin ||
allow_origin_stripped == "*") {
return true;
}
}
return false;
}
Commit Message: Fix timing allow check algorithm for service workers
This CL uses the OriginalURLViaServiceWorker() in the timing allow check
algorithm if the response WasFetchedViaServiceWorker(). This way, if a
service worker changes a same origin request to become cross origin,
then the timing allow check algorithm will still fail.
resource-timing-worker.js is changed so it avoids an empty Response,
which is an odd case in terms of same origin checks.
Bug: 837275
Change-Id: I7e497a6fcc2ee14244121b915ca5f5cceded417a
Reviewed-on: https://chromium-review.googlesource.com/1038229
Commit-Queue: Nicolás Peña Moreno <npm@chromium.org>
Reviewed-by: Yoav Weiss <yoav@yoav.ws>
Reviewed-by: Timothy Dresser <tdresser@chromium.org>
Cr-Commit-Position: refs/heads/master@{#555476}
CWE ID: CWE-200
|
bool Performance::PassesTimingAllowCheck(
const ResourceResponse& response,
const SecurityOrigin& initiator_security_origin,
const AtomicString& original_timing_allow_origin,
ExecutionContext* context) {
const KURL& response_url = response.WasFetchedViaServiceWorker()
? response.OriginalURLViaServiceWorker()
: response.Url();
scoped_refptr<const SecurityOrigin> resource_origin =
SecurityOrigin::Create(response_url);
if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin))
return true;
const AtomicString& timing_allow_origin_string =
original_timing_allow_origin.IsEmpty()
? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin)
: original_timing_allow_origin;
if (timing_allow_origin_string.IsEmpty() ||
EqualIgnoringASCIICase(timing_allow_origin_string, "null"))
return false;
if (timing_allow_origin_string == "*") {
UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin);
return true;
}
const String& security_origin = initiator_security_origin.ToString();
Vector<String> timing_allow_origins;
timing_allow_origin_string.GetString().Split(',', timing_allow_origins);
if (timing_allow_origins.size() > 1) {
UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin);
} else if (timing_allow_origins.size() == 1 &&
timing_allow_origin_string != "*") {
UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin);
}
for (const String& allow_origin : timing_allow_origins) {
const String allow_origin_stripped = allow_origin.StripWhiteSpace();
if (allow_origin_stripped == security_origin ||
allow_origin_stripped == "*") {
return true;
}
}
return false;
}
| 173,143
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc,
uint32_t prefix, int length)
{
if (!bitstream_read_bit(bc)) { // Leaf
if(hc->current >= 256){
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if(length){
hc->bits[hc->current] = prefix;
hc->lengths[hc->current] = length;
} else {
hc->bits[hc->current] = 0;
hc->lengths[hc->current] = 0;
}
hc->values[hc->current] = bitstream_read(bc, 8);
hc->current++;
if(hc->maxlength < length)
hc->maxlength = length;
return 0;
} else { //Node
int r;
length++;
r = smacker_decode_tree(bc, hc, prefix, length);
if(r)
return r;
return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length);
}
}
Commit Message: smacker: add sanity check for length in smacker_decode_tree()
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
Bug-Id: 1098
Cc: libav-stable@libav.org
Signed-off-by: Sean McGovern <gseanmcg@gmail.com>
CWE ID: CWE-119
|
static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc,
uint32_t prefix, int length)
{
if (length > SMKTREE_DECODE_MAX_RECURSION) {
av_log(NULL, AV_LOG_ERROR, "Maximum tree recursion level exceeded.\n");
return AVERROR_INVALIDDATA;
}
if (!bitstream_read_bit(bc)) { // Leaf
if(hc->current >= 256){
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if(length){
hc->bits[hc->current] = prefix;
hc->lengths[hc->current] = length;
} else {
hc->bits[hc->current] = 0;
hc->lengths[hc->current] = 0;
}
hc->values[hc->current] = bitstream_read(bc, 8);
hc->current++;
if(hc->maxlength < length)
hc->maxlength = length;
return 0;
} else { //Node
int r;
length++;
r = smacker_decode_tree(bc, hc, prefix, length);
if(r)
return r;
return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length);
}
}
| 167,671
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SimpleSoftOMXComponent::useBuffer(
OMX_BUFFERHEADERTYPE **header,
OMX_U32 portIndex,
OMX_PTR appPrivate,
OMX_U32 size,
OMX_U8 *ptr) {
Mutex::Autolock autoLock(mLock);
CHECK_LT(portIndex, mPorts.size());
*header = new OMX_BUFFERHEADERTYPE;
(*header)->nSize = sizeof(OMX_BUFFERHEADERTYPE);
(*header)->nVersion.s.nVersionMajor = 1;
(*header)->nVersion.s.nVersionMinor = 0;
(*header)->nVersion.s.nRevision = 0;
(*header)->nVersion.s.nStep = 0;
(*header)->pBuffer = ptr;
(*header)->nAllocLen = size;
(*header)->nFilledLen = 0;
(*header)->nOffset = 0;
(*header)->pAppPrivate = appPrivate;
(*header)->pPlatformPrivate = NULL;
(*header)->pInputPortPrivate = NULL;
(*header)->pOutputPortPrivate = NULL;
(*header)->hMarkTargetComponent = NULL;
(*header)->pMarkData = NULL;
(*header)->nTickCount = 0;
(*header)->nTimeStamp = 0;
(*header)->nFlags = 0;
(*header)->nOutputPortIndex = portIndex;
(*header)->nInputPortIndex = portIndex;
PortInfo *port = &mPorts.editItemAt(portIndex);
CHECK(mState == OMX_StateLoaded || port->mDef.bEnabled == OMX_FALSE);
CHECK_LT(port->mBuffers.size(), port->mDef.nBufferCountActual);
port->mBuffers.push();
BufferInfo *buffer =
&port->mBuffers.editItemAt(port->mBuffers.size() - 1);
buffer->mHeader = *header;
buffer->mOwnedByUs = false;
if (port->mBuffers.size() == port->mDef.nBufferCountActual) {
port->mDef.bPopulated = OMX_TRUE;
checkTransitions();
}
return OMX_ErrorNone;
}
Commit Message: Check buffer size in useBuffer in software components
Test: No more crash from oob read/write with running poc.
Bug: 63522430
Change-Id: I232d256eacdfaa9347902fe9b42650999f0d2d85
(cherry picked from commit 4e79910fdb303fd28a37a9401bed1b7fbccb1373)
CWE ID: CWE-200
|
OMX_ERRORTYPE SimpleSoftOMXComponent::useBuffer(
OMX_BUFFERHEADERTYPE **header,
OMX_U32 portIndex,
OMX_PTR appPrivate,
OMX_U32 size,
OMX_U8 *ptr) {
Mutex::Autolock autoLock(mLock);
CHECK_LT(portIndex, mPorts.size());
PortInfo *port = &mPorts.editItemAt(portIndex);
if (size < port->mDef.nBufferSize) {
ALOGE("b/63522430, Buffer size is too small.");
android_errorWriteLog(0x534e4554, "63522430");
return OMX_ErrorBadParameter;
}
*header = new OMX_BUFFERHEADERTYPE;
(*header)->nSize = sizeof(OMX_BUFFERHEADERTYPE);
(*header)->nVersion.s.nVersionMajor = 1;
(*header)->nVersion.s.nVersionMinor = 0;
(*header)->nVersion.s.nRevision = 0;
(*header)->nVersion.s.nStep = 0;
(*header)->pBuffer = ptr;
(*header)->nAllocLen = size;
(*header)->nFilledLen = 0;
(*header)->nOffset = 0;
(*header)->pAppPrivate = appPrivate;
(*header)->pPlatformPrivate = NULL;
(*header)->pInputPortPrivate = NULL;
(*header)->pOutputPortPrivate = NULL;
(*header)->hMarkTargetComponent = NULL;
(*header)->pMarkData = NULL;
(*header)->nTickCount = 0;
(*header)->nTimeStamp = 0;
(*header)->nFlags = 0;
(*header)->nOutputPortIndex = portIndex;
(*header)->nInputPortIndex = portIndex;
CHECK(mState == OMX_StateLoaded || port->mDef.bEnabled == OMX_FALSE);
CHECK_LT(port->mBuffers.size(), port->mDef.nBufferCountActual);
port->mBuffers.push();
BufferInfo *buffer =
&port->mBuffers.editItemAt(port->mBuffers.size() - 1);
buffer->mHeader = *header;
buffer->mOwnedByUs = false;
if (port->mBuffers.size() == port->mDef.nBufferCountActual) {
port->mDef.bPopulated = OMX_TRUE;
checkTransitions();
}
return OMX_ErrorNone;
}
| 173,977
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: isofs_export_encode_fh(struct inode *inode,
__u32 *fh32,
int *max_len,
struct inode *parent)
{
struct iso_inode_info * ei = ISOFS_I(inode);
int len = *max_len;
int type = 1;
__u16 *fh16 = (__u16*)fh32;
/*
* WARNING: max_len is 5 for NFSv2. Because of this
* limitation, we use the lower 16 bits of fh32[1] to hold the
* offset of the inode and the upper 16 bits of fh32[1] to
* hold the offset of the parent.
*/
if (parent && (len < 5)) {
*max_len = 5;
return 255;
} else if (len < 3) {
*max_len = 3;
return 255;
}
len = 3;
fh32[0] = ei->i_iget5_block;
fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */
fh32[2] = inode->i_generation;
if (parent) {
struct iso_inode_info *eparent;
eparent = ISOFS_I(parent);
fh32[3] = eparent->i_iget5_block;
fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */
fh32[4] = parent->i_generation;
len = 5;
type = 2;
}
*max_len = len;
return type;
}
Commit Message: isofs: avoid info leak on export
For type 1 the parent_offset member in struct isofs_fid gets copied
uninitialized to userland. Fix this by initializing it to 0.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: Jan Kara <jack@suse.cz>
CWE ID: CWE-200
|
isofs_export_encode_fh(struct inode *inode,
__u32 *fh32,
int *max_len,
struct inode *parent)
{
struct iso_inode_info * ei = ISOFS_I(inode);
int len = *max_len;
int type = 1;
__u16 *fh16 = (__u16*)fh32;
/*
* WARNING: max_len is 5 for NFSv2. Because of this
* limitation, we use the lower 16 bits of fh32[1] to hold the
* offset of the inode and the upper 16 bits of fh32[1] to
* hold the offset of the parent.
*/
if (parent && (len < 5)) {
*max_len = 5;
return 255;
} else if (len < 3) {
*max_len = 3;
return 255;
}
len = 3;
fh32[0] = ei->i_iget5_block;
fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */
fh16[3] = 0; /* avoid leaking uninitialized data */
fh32[2] = inode->i_generation;
if (parent) {
struct iso_inode_info *eparent;
eparent = ISOFS_I(parent);
fh32[3] = eparent->i_iget5_block;
fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */
fh32[4] = parent->i_generation;
len = 5;
type = 2;
}
*max_len = len;
return type;
}
| 166,177
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b, *avail, nl);
if (len >= 0)
len += tested;
}
return (len);
}
Commit Message: Issue 747 (and others?): Avoid OOB read when parsing multiple long lines
The mtree bidder needs to look several lines ahead
in the input. It does this by extending the read-ahead
and parsing subsequent lines from the same growing buffer.
A bookkeeping error when extending the read-ahead would
sometimes lead it to significantly over-count the
size of the line being read.
CWE ID: CWE-125
|
next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b + len, *avail - len, nl);
if (len >= 0)
len += tested;
}
return (len);
}
| 168,765
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap)
{
int i;
int j;
int x;
int c;
int numcolors;
int actualnumcolors;
switch (hdr->maptype) {
case RAS_MT_NONE:
break;
case RAS_MT_EQUALRGB:
{
jas_eprintf("warning: palettized images not fully supported\n");
numcolors = 1 << hdr->depth;
assert(numcolors <= RAS_CMAP_MAXSIZ);
actualnumcolors = hdr->maplength / 3;
for (i = 0; i < numcolors; i++) {
cmap->data[i] = 0;
}
if ((hdr->maplength % 3) || hdr->maplength < 0 ||
hdr->maplength > 3 * numcolors) {
return -1;
}
for (i = 0; i < 3; i++) {
for (j = 0; j < actualnumcolors; j++) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
x = 0;
switch (i) {
case 0:
x = RAS_RED(c);
break;
case 1:
x = RAS_GREEN(c);
break;
case 2:
x = RAS_BLUE(c);
break;
}
cmap->data[j] |= x;
}
}
}
break;
default:
return -1;
break;
}
return 0;
}
Commit Message: Fixed a few bugs in the RAS encoder and decoder where errors were tested
with assertions instead of being gracefully handled.
CWE ID:
|
static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap)
{
int i;
int j;
int x;
int c;
int numcolors;
int actualnumcolors;
switch (hdr->maptype) {
case RAS_MT_NONE:
break;
case RAS_MT_EQUALRGB:
{
jas_eprintf("warning: palettized images not fully supported\n");
numcolors = 1 << hdr->depth;
if (numcolors > RAS_CMAP_MAXSIZ) {
return -1;
}
actualnumcolors = hdr->maplength / 3;
for (i = 0; i < numcolors; i++) {
cmap->data[i] = 0;
}
if ((hdr->maplength % 3) || hdr->maplength < 0 ||
hdr->maplength > 3 * numcolors) {
return -1;
}
for (i = 0; i < 3; i++) {
for (j = 0; j < actualnumcolors; j++) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
x = 0;
switch (i) {
case 0:
x = RAS_RED(c);
break;
case 1:
x = RAS_GREEN(c);
break;
case 2:
x = RAS_BLUE(c);
break;
}
cmap->data[j] |= x;
}
}
}
break;
default:
return -1;
break;
}
return 0;
}
| 168,739
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
Commit Message: fs: prevent page refcount overflow in pipe_buf_get
Change pipe_buf_get() to return a bool indicating whether it succeeded
in raising the refcount of the page (if the thing in the pipe is a page).
This removes another mechanism for overflowing the page refcount. All
callers converted to handle a failure.
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Matthew Wilcox <willy@infradead.org>
Cc: stable@kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-416
|
static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
if (!pipe_buf_get(ipipe, ibuf)) {
if (ret == 0)
ret = -EFAULT;
break;
}
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
| 170,231
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TestFeaturesNativeHandler::TestFeaturesNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("GetAPIFeatures",
base::Bind(&TestFeaturesNativeHandler::GetAPIFeatures,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284
|
TestFeaturesNativeHandler::TestFeaturesNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("GetAPIFeatures", "test",
base::Bind(&TestFeaturesNativeHandler::GetAPIFeatures,
base::Unretained(this)));
}
| 172,254
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int getSingletonPos(const char* str)
{
int result =-1;
int i=0;
int len = 0;
if( str && ((len=strlen(str))>0) ){
for( i=0; i<len ; i++){
if( isIDSeparator(*(str+i)) ){
if( i==1){
/* string is of the form x-avy or a-prv1 */
result =0;
break;
} else {
/* delimiter found; check for singleton */
if( isIDSeparator(*(str+i+2)) ){
/* a singleton; so send the position of separator before singleton */
result = i+1;
break;
}
}
}
}/* end of for */
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
static int getSingletonPos(const char* str)
{
int result =-1;
int i=0;
int len = 0;
if( str && ((len=strlen(str))>0) ){
for( i=0; i<len ; i++){
if( isIDSeparator(*(str+i)) ){
if( i==1){
/* string is of the form x-avy or a-prv1 */
result =0;
break;
} else {
/* delimiter found; check for singleton */
if( isIDSeparator(*(str+i+2)) ){
/* a singleton; so send the position of separator before singleton */
result = i+1;
break;
}
}
}
}/* end of for */
}
return result;
}
| 167,202
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool AXObject::isLiveRegion() const {
const AtomicString& liveRegion = liveRegionStatus();
return equalIgnoringCase(liveRegion, "polite") ||
equalIgnoringCase(liveRegion, "assertive");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXObject::isLiveRegion() const {
const AtomicString& liveRegion = liveRegionStatus();
return equalIgnoringASCIICase(liveRegion, "polite") ||
equalIgnoringASCIICase(liveRegion, "assertive");
}
| 171,927
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
{
char
message[MagickPathExtent],
*text;
uint32
count,
length,
type;
unsigned long
*tietz;
if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
(void) SetImageProperty(image,"tiff:artist",text,exception);
if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
(void) SetImageProperty(image,"tiff:copyright",text,exception);
if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
(void) SetImageProperty(image,"tiff:timestamp",text,exception);
if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
(void) SetImageProperty(image,"tiff:document",text,exception);
if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
(void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
(void) SetImageProperty(image,"comment",text,exception);
if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
(void) SetImageProperty(image,"tiff:make",text,exception);
if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
(void) SetImageProperty(image,"tiff:model",text,exception);
if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:image-id",message,exception);
}
if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
(void) SetImageProperty(image,"label",text,exception);
if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
(void) SetImageProperty(image,"tiff:software",text,exception);
if (TIFFGetField(tiff,33423,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
}
if (TIFFGetField(tiff,36867,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
}
if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
switch (type)
{
case 0x01:
{
(void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE",
exception);
break;
}
case 0x02:
{
(void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception);
break;
}
case 0x04:
{
(void) SetImageProperty(image,"tiff:subfiletype","MASK",exception);
break;
}
default:
break;
}
if (TIFFGetField(tiff,37706,&length,&tietz) == 1)
{
(void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]);
(void) SetImageProperty(image,"tiff:tietz_offset",message,exception);
}
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/298
CWE ID: CWE-476
|
static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
{
char
message[MagickPathExtent],
*text;
uint32
count,
length,
type;
unsigned long
*tietz;
if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:artist",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:copyright",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:timestamp",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:document",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"comment",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:make",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:model",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) &&
(text != (char *) NULL))
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:image-id",message,exception);
}
if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"label",text,exception);
if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:software",text,exception);
if ((TIFFGetField(tiff,33423,&count,&text) == 1) &&
(text != (char *) NULL))
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
}
if ((TIFFGetField(tiff,36867,&count,&text) == 1) &&
(text != (char *) NULL))
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
}
if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
switch (type)
{
case 0x01:
{
(void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE",
exception);
break;
}
case 0x02:
{
(void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception);
break;
}
case 0x04:
{
(void) SetImageProperty(image,"tiff:subfiletype","MASK",exception);
break;
}
default:
break;
}
if ((TIFFGetField(tiff,37706,&length,&tietz) == 1) &&
(tietz != (unsigned long *) NULL))
{
(void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]);
(void) SetImageProperty(image,"tiff:tietz_offset",message,exception);
}
}
| 168,679
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static PixelChannels **AcquirePixelThreadSet(const Image *image)
{
PixelChannels
**pixels;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (PixelChannels **) NULL)
return((PixelChannels **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
register ssize_t
j;
pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns,
sizeof(**pixels));
if (pixels[i] == (PixelChannels *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) image->columns; j++)
{
register ssize_t
k;
for (k=0; k < MaxPixelChannels; k++)
pixels[i][j].channel[k]=0.0;
}
}
return(pixels);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1586
CWE ID: CWE-119
|
static PixelChannels **AcquirePixelThreadSet(const Image *image)
static PixelChannels **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
PixelChannels
**pixels;
register ssize_t
i;
size_t
columns,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (PixelChannels **) NULL)
return((PixelChannels **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) number_threads; i++)
{
register ssize_t
j;
pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels));
if (pixels[i] == (PixelChannels *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
{
register ssize_t
k;
for (k=0; k < MaxPixelChannels; k++)
pixels[i][j].channel[k]=0.0;
}
}
return(pixels);
}
| 170,205
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ShellSurface::CreateShellSurfaceWidget(ui::WindowShowState show_state) {
DCHECK(enabled());
DCHECK(!widget_);
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
params.delegate = this;
params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.show_state = show_state;
params.parent =
ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), container_);
params.bounds = initial_bounds_;
bool activatable = activatable_ && !surface_->GetHitTestBounds().IsEmpty();
params.activatable = activatable ? views::Widget::InitParams::ACTIVATABLE_YES
: views::Widget::InitParams::ACTIVATABLE_NO;
widget_ = new ShellSurfaceWidget(this);
widget_->Init(params);
widget_->set_movement_disabled(!initial_bounds_.IsEmpty());
aura::Window* window = widget_->GetNativeWindow();
window->SetName("ExoShellSurface");
window->AddChild(surface_->window());
window->SetEventTargeter(base::WrapUnique(new CustomWindowTargeter));
SetApplicationId(window, &application_id_);
SetMainSurface(window, surface_);
window->AddObserver(this);
ash::wm::GetWindowState(window)->AddObserver(this);
if (parent_)
wm::AddTransientChild(parent_, window);
ash::wm::GetWindowState(window)->set_window_position_managed(
ash::wm::ToWindowShowState(ash::wm::WINDOW_STATE_TYPE_AUTO_POSITIONED) ==
show_state &&
initial_bounds_.IsEmpty());
views::FocusManager* focus_manager = widget_->GetFocusManager();
for (const auto& entry : kCloseWindowAccelerators) {
focus_manager->RegisterAccelerator(
ui::Accelerator(entry.keycode, entry.modifiers),
ui::AcceleratorManager::kNormalPriority, this);
}
pending_show_widget_ = true;
}
Commit Message: exo: Reduce side-effects of dynamic activation code.
This code exists for clients that need to managed their own system
modal dialogs. Since the addition of the remote surface API we
can limit the impact of this to surfaces created for system modal
container.
BUG=29528396
Review-Url: https://codereview.chromium.org/2084023003
Cr-Commit-Position: refs/heads/master@{#401115}
CWE ID: CWE-416
|
void ShellSurface::CreateShellSurfaceWidget(ui::WindowShowState show_state) {
DCHECK(enabled());
DCHECK(!widget_);
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
params.delegate = this;
params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.show_state = show_state;
params.parent =
ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), container_);
params.bounds = initial_bounds_;
bool activatable = activatable_;
// ShellSurfaces in system modal container are only activatable if input
// region is non-empty. See OnCommitSurface() for more details.
if (container_ == ash::kShellWindowId_SystemModalContainer)
activatable &= !surface_->GetHitTestBounds().IsEmpty();
params.activatable = activatable ? views::Widget::InitParams::ACTIVATABLE_YES
: views::Widget::InitParams::ACTIVATABLE_NO;
widget_ = new ShellSurfaceWidget(this);
widget_->Init(params);
widget_->set_movement_disabled(!initial_bounds_.IsEmpty());
aura::Window* window = widget_->GetNativeWindow();
window->SetName("ExoShellSurface");
window->AddChild(surface_->window());
window->SetEventTargeter(base::WrapUnique(new CustomWindowTargeter));
SetApplicationId(window, &application_id_);
SetMainSurface(window, surface_);
window->AddObserver(this);
ash::wm::GetWindowState(window)->AddObserver(this);
if (parent_)
wm::AddTransientChild(parent_, window);
ash::wm::GetWindowState(window)->set_window_position_managed(
ash::wm::ToWindowShowState(ash::wm::WINDOW_STATE_TYPE_AUTO_POSITIONED) ==
show_state &&
initial_bounds_.IsEmpty());
views::FocusManager* focus_manager = widget_->GetFocusManager();
for (const auto& entry : kCloseWindowAccelerators) {
focus_manager->RegisterAccelerator(
ui::Accelerator(entry.keycode, entry.modifiers),
ui::AcceleratorManager::kNormalPriority, this);
}
pending_show_widget_ = true;
}
| 171,638
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid)
{
FILE *fp = fopen(dest_filename, "w");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
const int dest_fd = fileno(fp);
if (fchown(dest_fd, uid, gid) < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
fclose(fp);
unlink(dest_filename);
return false;
}
fclose(fp);
return true;
}
Commit Message: ccpp: open file for dump_fd_info with O_EXCL
To avoid possible races.
Related: #1211835
Signed-off-by: Jakub Filak <jfilak@redhat.com>
CWE ID: CWE-59
|
static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid)
{
FILE *fp = fopen(dest_filename, "wx");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
const int dest_fd = fileno(fp);
if (fchown(dest_fd, uid, gid) < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
fclose(fp);
unlink(dest_filename);
return false;
}
fclose(fp);
return true;
}
| 170,138
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip_checkentry(&e->ip))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e,
e->target_offset, e->next_offset);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
CWE ID: CWE-264
|
check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip_checkentry(&e->ip))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e, e->elems,
e->target_offset, e->next_offset);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
| 167,217
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void FocusIn(const char* input_context_path) {
if (!input_context_path) {
LOG(ERROR) << "NULL context passed";
} else {
DLOG(INFO) << "FocusIn: " << input_context_path;
}
input_context_path_ = Or(input_context_path, "");
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void FocusIn(const char* input_context_path) {
| 170,532
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void hid_input_field(struct hid_device *hid, struct hid_field *field,
__u8 *data, int interrupt)
{
unsigned n;
unsigned count = field->report_count;
unsigned offset = field->report_offset;
unsigned size = field->report_size;
__s32 min = field->logical_minimum;
__s32 max = field->logical_maximum;
__s32 *value;
value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);
if (!value)
return;
for (n = 0; n < count; n++) {
value[n] = min < 0 ?
snto32(hid_field_extract(hid, data, offset + n * size,
size), size) :
hid_field_extract(hid, data, offset + n * size, size);
/* Ignore report if ErrorRollOver */
if (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&
value[n] >= min && value[n] <= max &&
field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)
goto exit;
}
for (n = 0; n < count; n++) {
if (HID_MAIN_ITEM_VARIABLE & field->flags) {
hid_process_event(hid, field, &field->usage[n], value[n], interrupt);
continue;
}
if (field->value[n] >= min && field->value[n] <= max
&& field->usage[field->value[n] - min].hid
&& search(value, field->value[n], count))
hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);
if (value[n] >= min && value[n] <= max
&& field->usage[value[n] - min].hid
&& search(field->value, value[n], count))
hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);
}
memcpy(field->value, value, count * sizeof(__s32));
exit:
kfree(value);
}
Commit Message: HID: core: prevent out-of-bound readings
Plugging a Logitech DJ receiver with KASAN activated raises a bunch of
out-of-bound readings.
The fields are allocated up to MAX_USAGE, meaning that potentially, we do
not have enough fields to fit the incoming values.
Add checks and silence KASAN.
Signed-off-by: Benjamin Tissoires <benjamin.tissoires@redhat.com>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID: CWE-125
|
static void hid_input_field(struct hid_device *hid, struct hid_field *field,
__u8 *data, int interrupt)
{
unsigned n;
unsigned count = field->report_count;
unsigned offset = field->report_offset;
unsigned size = field->report_size;
__s32 min = field->logical_minimum;
__s32 max = field->logical_maximum;
__s32 *value;
value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);
if (!value)
return;
for (n = 0; n < count; n++) {
value[n] = min < 0 ?
snto32(hid_field_extract(hid, data, offset + n * size,
size), size) :
hid_field_extract(hid, data, offset + n * size, size);
/* Ignore report if ErrorRollOver */
if (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&
value[n] >= min && value[n] <= max &&
value[n] - min < field->maxusage &&
field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)
goto exit;
}
for (n = 0; n < count; n++) {
if (HID_MAIN_ITEM_VARIABLE & field->flags) {
hid_process_event(hid, field, &field->usage[n], value[n], interrupt);
continue;
}
if (field->value[n] >= min && field->value[n] <= max
&& field->value[n] - min < field->maxusage
&& field->usage[field->value[n] - min].hid
&& search(value, field->value[n], count))
hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);
if (value[n] >= min && value[n] <= max
&& value[n] - min < field->maxusage
&& field->usage[value[n] - min].hid
&& search(field->value, value[n], count))
hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);
}
memcpy(field->value, value, count * sizeof(__s32));
exit:
kfree(value);
}
| 166,921
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: u32 h264bsdInitDpb(
dpbStorage_t *dpb,
u32 picSizeInMbs,
u32 dpbSize,
u32 maxRefFrames,
u32 maxFrameNum,
u32 noReordering)
{
/* Variables */
u32 i;
/* Code */
ASSERT(picSizeInMbs);
ASSERT(maxRefFrames <= MAX_NUM_REF_PICS);
ASSERT(maxRefFrames <= dpbSize);
ASSERT(maxFrameNum);
ASSERT(dpbSize);
dpb->maxLongTermFrameIdx = NO_LONG_TERM_FRAME_INDICES;
dpb->maxRefFrames = MAX(maxRefFrames, 1);
if (noReordering)
dpb->dpbSize = dpb->maxRefFrames;
else
dpb->dpbSize = dpbSize;
dpb->maxFrameNum = maxFrameNum;
dpb->noReordering = noReordering;
dpb->fullness = 0;
dpb->numRefFrames = 0;
dpb->prevRefFrameNum = 0;
ALLOCATE(dpb->buffer, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t);
if (dpb->buffer == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->buffer, 0,
(MAX_NUM_REF_IDX_L0_ACTIVE + 1)*sizeof(dpbPicture_t));
for (i = 0; i < dpb->dpbSize + 1; i++)
{
/* Allocate needed amount of memory, which is:
* image size + 32 + 15, where 32 cames from the fact that in ARM OpenMax
* DL implementation Functions may read beyond the end of an array,
* by a maximum of 32 bytes. And +15 cames for the need to align memory
* to 16-byte boundary */
ALLOCATE(dpb->buffer[i].pAllocatedData, (picSizeInMbs*384 + 32+15), u8);
if (dpb->buffer[i].pAllocatedData == NULL)
return(MEMORY_ALLOCATION_ERROR);
dpb->buffer[i].data = ALIGN(dpb->buffer[i].pAllocatedData, 16);
}
ALLOCATE(dpb->list, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t*);
ALLOCATE(dpb->outBuf, dpb->dpbSize+1, dpbOutPicture_t);
if (dpb->list == NULL || dpb->outBuf == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->list, 0,
((MAX_NUM_REF_IDX_L0_ACTIVE + 1) * sizeof(dpbPicture_t*)) );
dpb->numOut = dpb->outIndex = 0;
return(HANTRO_OK);
}
Commit Message: Fix potential overflow
Bug: 28533562
Change-Id: I798ab24caa4c81f3ba564cad7c9ee019284fb702
CWE ID: CWE-119
|
u32 h264bsdInitDpb(
dpbStorage_t *dpb,
u32 picSizeInMbs,
u32 dpbSize,
u32 maxRefFrames,
u32 maxFrameNum,
u32 noReordering)
{
/* Variables */
u32 i;
/* Code */
ASSERT(picSizeInMbs);
ASSERT(maxRefFrames <= MAX_NUM_REF_PICS);
ASSERT(maxRefFrames <= dpbSize);
ASSERT(maxFrameNum);
ASSERT(dpbSize);
// see comment in loop below about size calculation
if (picSizeInMbs > (UINT32_MAX - 32 - 15) / 384) {
ALOGE("b/28533562");
android_errorWriteLog(0x534e4554, "28533562");
return(MEMORY_ALLOCATION_ERROR);
}
dpb->maxLongTermFrameIdx = NO_LONG_TERM_FRAME_INDICES;
dpb->maxRefFrames = MAX(maxRefFrames, 1);
if (noReordering)
dpb->dpbSize = dpb->maxRefFrames;
else
dpb->dpbSize = dpbSize;
dpb->maxFrameNum = maxFrameNum;
dpb->noReordering = noReordering;
dpb->fullness = 0;
dpb->numRefFrames = 0;
dpb->prevRefFrameNum = 0;
ALLOCATE(dpb->buffer, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t);
if (dpb->buffer == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->buffer, 0,
(MAX_NUM_REF_IDX_L0_ACTIVE + 1)*sizeof(dpbPicture_t));
for (i = 0; i < dpb->dpbSize + 1; i++)
{
/* Allocate needed amount of memory, which is:
* image size + 32 + 15, where 32 cames from the fact that in ARM OpenMax
* DL implementation Functions may read beyond the end of an array,
* by a maximum of 32 bytes. And +15 cames for the need to align memory
* to 16-byte boundary */
ALLOCATE(dpb->buffer[i].pAllocatedData, (picSizeInMbs*384 + 32+15), u8);
if (dpb->buffer[i].pAllocatedData == NULL)
return(MEMORY_ALLOCATION_ERROR);
dpb->buffer[i].data = ALIGN(dpb->buffer[i].pAllocatedData, 16);
}
ALLOCATE(dpb->list, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t*);
ALLOCATE(dpb->outBuf, dpb->dpbSize+1, dpbOutPicture_t);
if (dpb->list == NULL || dpb->outBuf == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->list, 0,
((MAX_NUM_REF_IDX_L0_ACTIVE + 1) * sizeof(dpbPicture_t*)) );
dpb->numOut = dpb->outIndex = 0;
return(HANTRO_OK);
}
| 173,546
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev,
struct ib_udata *udata)
{
int ret = 0;
struct hns_roce_ucontext *context;
struct hns_roce_ib_alloc_ucontext_resp resp;
struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev);
resp.qp_tab_size = hr_dev->caps.num_qps;
context = kmalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return ERR_PTR(-ENOMEM);
ret = hns_roce_uar_alloc(hr_dev, &context->uar);
if (ret)
goto error_fail_uar_alloc;
if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) {
INIT_LIST_HEAD(&context->page_list);
mutex_init(&context->page_mutex);
}
ret = ib_copy_to_udata(udata, &resp, sizeof(resp));
if (ret)
goto error_fail_copy_to_udata;
return &context->ibucontext;
error_fail_copy_to_udata:
hns_roce_uar_free(hr_dev, &context->uar);
error_fail_uar_alloc:
kfree(context);
return ERR_PTR(ret);
}
Commit Message: RDMA/hns: Fix init resp when alloc ucontext
The data in resp will be copied from kernel to userspace, thus it needs to
be initialized to zeros to avoid copying uninited stack memory.
Reported-by: Dan Carpenter <dan.carpenter@oracle.com>
Fixes: e088a685eae9 ("RDMA/hns: Support rq record doorbell for the user space")
Signed-off-by: Yixian Liu <liuyixian@huawei.com>
Signed-off-by: Jason Gunthorpe <jgg@mellanox.com>
CWE ID: CWE-665
|
static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev,
struct ib_udata *udata)
{
int ret = 0;
struct hns_roce_ucontext *context;
struct hns_roce_ib_alloc_ucontext_resp resp = {};
struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev);
resp.qp_tab_size = hr_dev->caps.num_qps;
context = kmalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return ERR_PTR(-ENOMEM);
ret = hns_roce_uar_alloc(hr_dev, &context->uar);
if (ret)
goto error_fail_uar_alloc;
if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) {
INIT_LIST_HEAD(&context->page_list);
mutex_init(&context->page_mutex);
}
ret = ib_copy_to_udata(udata, &resp, sizeof(resp));
if (ret)
goto error_fail_copy_to_udata;
return &context->ibucontext;
error_fail_copy_to_udata:
hns_roce_uar_free(hr_dev, &context->uar);
error_fail_uar_alloc:
kfree(context);
return ERR_PTR(ret);
}
| 169,504
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg)
{
__be32 *p;
RESERVE_SPACE(4+NFS4_STATEID_SIZE+4);
WRITE32(OP_OPEN_DOWNGRADE);
WRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE);
WRITE32(arg->seqid->sequence->counter);
encode_share_access(xdr, arg->open_flags);
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg)
{
__be32 *p;
RESERVE_SPACE(4+NFS4_STATEID_SIZE+4);
WRITE32(OP_OPEN_DOWNGRADE);
WRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE);
WRITE32(arg->seqid->sequence->counter);
encode_share_access(xdr, arg->fmode);
return 0;
}
| 165,713
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftRaw::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.raw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mChannelCount = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftRaw::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.raw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mChannelCount = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,219
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memcpy(&p->id, &x->id, sizeof(p->id));
memcpy(&p->sel, &x->sel, sizeof(p->sel));
memcpy(&p->lft, &x->lft, sizeof(p->lft));
memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
memcpy(&p->stats, &x->stats, sizeof(p->stats));
memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
p->mode = x->props.mode;
p->replay_window = x->props.replay_window;
p->reqid = x->props.reqid;
p->family = x->props.family;
p->flags = x->props.flags;
p->seq = x->km.seq;
}
Commit Message: xfrm_user: fix info leak in copy_to_user_state()
The memory reserved to dump the xfrm state includes the padding bytes of
struct xfrm_usersa_info added by the compiler for alignment (7 for
amd64, 3 for i386). Add an explicit memset(0) before filling the buffer
to avoid the info leak.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Acked-by: Steffen Klassert <steffen.klassert@secunet.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memset(p, 0, sizeof(*p));
memcpy(&p->id, &x->id, sizeof(p->id));
memcpy(&p->sel, &x->sel, sizeof(p->sel));
memcpy(&p->lft, &x->lft, sizeof(p->lft));
memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
memcpy(&p->stats, &x->stats, sizeof(p->stats));
memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
p->mode = x->props.mode;
p->replay_window = x->props.replay_window;
p->reqid = x->props.reqid;
p->family = x->props.family;
p->flags = x->props.flags;
p->seq = x->km.seq;
}
| 166,189
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 8;
fwd_txfm_ref = fdct8x8_ref;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 8;
fwd_txfm_ref = fdct8x8_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
}
| 174,562
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DocumentLoader::InstallNewDocument(
const KURL& url,
Document* owner_document,
WebGlobalObjectReusePolicy global_object_reuse_policy,
const AtomicString& mime_type,
const AtomicString& encoding,
InstallNewDocumentReason reason,
ParserSynchronizationPolicy parsing_policy,
const KURL& overriding_url) {
DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive());
DCHECK_EQ(frame_->Tree().ChildCount(), 0u);
if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) {
GetFrameLoader().StateMachine()->AdvanceTo(
FrameLoaderStateMachine::kCommittedFirstRealLoad);
}
const SecurityOrigin* previous_security_origin = nullptr;
const ContentSecurityPolicy* previous_csp = nullptr;
if (frame_->GetDocument()) {
previous_security_origin = frame_->GetDocument()->GetSecurityOrigin();
previous_csp = frame_->GetDocument()->GetContentSecurityPolicy();
}
if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting)
frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_));
if (reason == InstallNewDocumentReason::kNavigation)
WillCommitNavigation();
Document* document = frame_->DomWindow()->InstallNewDocument(
mime_type,
DocumentInit::Create()
.WithDocumentLoader(this)
.WithURL(url)
.WithOwnerDocument(owner_document)
.WithNewRegistrationContext()
.WithPreviousDocumentCSP(previous_csp),
false);
if (frame_->IsMainFrame())
frame_->ClearActivation();
if (frame_->HasReceivedUserGestureBeforeNavigation() !=
had_sticky_activation_) {
frame_->SetDocumentHasReceivedUserGestureBeforeNavigation(
had_sticky_activation_);
GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation(
had_sticky_activation_);
}
if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) {
frame_->Tree().ExperimentalSetNulledName();
}
if (!overriding_url.IsEmpty())
document->SetBaseURLOverride(overriding_url);
DidInstallNewDocument(document, previous_csp);
if (reason == InstallNewDocumentReason::kNavigation)
DidCommitNavigation(global_object_reuse_policy);
if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) {
if (document->GetSettings()
->GetForceTouchEventFeatureDetectionForInspector()) {
OriginTrialContext::FromOrCreate(document)->AddFeature(
"ForceTouchEventFeatureDetectionForInspector");
}
OriginTrialContext::AddTokensFromHeader(
document, response_.HttpHeaderField(http_names::kOriginTrial));
}
bool stale_while_revalidate_enabled =
origin_trials::StaleWhileRevalidateEnabled(document);
fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled);
if (stale_while_revalidate_enabled &&
!RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag())
UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled);
parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding);
ScriptableDocumentParser* scriptable_parser =
parser_->AsScriptableDocumentParser();
if (scriptable_parser && GetResource()) {
scriptable_parser->SetInlineScriptCacheHandler(
ToRawResource(GetResource())->InlineScriptCacheHandler());
}
WTF::String feature_policy(
response_.HttpHeaderField(http_names::kFeaturePolicy));
MergeFeaturesFromOriginPolicy(feature_policy, request_.GetOriginPolicy());
document->ApplyFeaturePolicyFromHeader(feature_policy);
GetFrameLoader().DispatchDidClearDocumentOfWindowObject();
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20
|
void DocumentLoader::InstallNewDocument(
const KURL& url,
Document* owner_document,
WebGlobalObjectReusePolicy global_object_reuse_policy,
const AtomicString& mime_type,
const AtomicString& encoding,
InstallNewDocumentReason reason,
ParserSynchronizationPolicy parsing_policy,
const KURL& overriding_url) {
DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive());
DCHECK_EQ(frame_->Tree().ChildCount(), 0u);
if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) {
GetFrameLoader().StateMachine()->AdvanceTo(
FrameLoaderStateMachine::kCommittedFirstRealLoad);
}
const SecurityOrigin* previous_security_origin = nullptr;
if (frame_->GetDocument()) {
previous_security_origin = frame_->GetDocument()->GetSecurityOrigin();
}
if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting)
frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_));
if (reason == InstallNewDocumentReason::kNavigation)
WillCommitNavigation();
Document* document = frame_->DomWindow()->InstallNewDocument(
mime_type,
DocumentInit::Create()
.WithDocumentLoader(this)
.WithURL(url)
.WithOwnerDocument(owner_document)
.WithNewRegistrationContext(),
false);
if (frame_->IsMainFrame())
frame_->ClearActivation();
if (frame_->HasReceivedUserGestureBeforeNavigation() !=
had_sticky_activation_) {
frame_->SetDocumentHasReceivedUserGestureBeforeNavigation(
had_sticky_activation_);
GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation(
had_sticky_activation_);
}
if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) {
frame_->Tree().ExperimentalSetNulledName();
}
if (!overriding_url.IsEmpty())
document->SetBaseURLOverride(overriding_url);
DidInstallNewDocument(document);
if (reason == InstallNewDocumentReason::kNavigation)
DidCommitNavigation(global_object_reuse_policy);
if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) {
if (document->GetSettings()
->GetForceTouchEventFeatureDetectionForInspector()) {
OriginTrialContext::FromOrCreate(document)->AddFeature(
"ForceTouchEventFeatureDetectionForInspector");
}
OriginTrialContext::AddTokensFromHeader(
document, response_.HttpHeaderField(http_names::kOriginTrial));
}
bool stale_while_revalidate_enabled =
origin_trials::StaleWhileRevalidateEnabled(document);
fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled);
if (stale_while_revalidate_enabled &&
!RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag())
UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled);
parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding);
ScriptableDocumentParser* scriptable_parser =
parser_->AsScriptableDocumentParser();
if (scriptable_parser && GetResource()) {
scriptable_parser->SetInlineScriptCacheHandler(
ToRawResource(GetResource())->InlineScriptCacheHandler());
}
WTF::String feature_policy(
response_.HttpHeaderField(http_names::kFeaturePolicy));
MergeFeaturesFromOriginPolicy(feature_policy, request_.GetOriginPolicy());
document->ApplyFeaturePolicyFromHeader(feature_policy);
GetFrameLoader().DispatchDidClearDocumentOfWindowObject();
}
| 173,057
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RunAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs);
for (int j = 0; j < kNumCoeffs; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
const uint32_t diff = dst[j] - src[j];
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1u, max_error)
<< "Error: 4x4 FHT/IHT has an individual round trip error > 1";
EXPECT_GE(count_test_block , total_error)
<< "Error: 4x4 FHT/IHT has average round trip error > 1 per block";
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void RunAccuracyCheck() {
void RunAccuracyCheck(int limit) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED(16, int16_t, test_input_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, test_temp_block[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]);
DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]);
#endif
for (int j = 0; j < kNumCoeffs; ++j) {
if (bit_depth_ == VPX_BITS_8) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src16[j] = rnd.Rand16() & mask_;
dst16[j] = rnd.Rand16() & mask_;
test_input_block[j] = src16[j] - dst16[j];
#endif
}
}
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block,
CONVERT_TO_BYTEPTR(dst16), pitch_));
#endif
}
for (int j = 0; j < kNumCoeffs; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const uint32_t diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
ASSERT_EQ(VPX_BITS_8, bit_depth_);
const uint32_t diff = dst[j] - src[j];
#endif
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(static_cast<uint32_t>(limit), max_error)
<< "Error: 4x4 FHT/IHT has an individual round trip error > "
<< limit;
EXPECT_GE(count_test_block * limit, total_error)
<< "Error: 4x4 FHT/IHT has average round trip error > " << limit
<< " per block";
}
| 174,547
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GetPreviewDataForIndex(int index,
scoped_refptr<base::RefCountedBytes>* data) {
if (index != printing::COMPLETE_PREVIEW_DOCUMENT_INDEX &&
index < printing::FIRST_PAGE_INDEX) {
return;
}
PreviewPageDataMap::iterator it = page_data_map_.find(index);
if (it != page_data_map_.end())
*data = it->second.get();
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void GetPreviewDataForIndex(int index,
scoped_refptr<base::RefCountedBytes>* data) {
if (IsInvalidIndex(index))
return;
PreviewPageDataMap::iterator it = page_data_map_.find(index);
if (it != page_data_map_.end())
*data = it->second.get();
}
| 170,822
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void reds_handle_ticket(void *opaque)
{
RedLinkInfo *link = (RedLinkInfo *)opaque;
char password[SPICE_MAX_PASSWORD_LENGTH];
time_t ltime;
time(<ime);
RSA_private_decrypt(link->tiTicketing.rsa_size,
link->tiTicketing.encrypted_ticket.encrypted_data,
(unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING);
if (ticketing_enabled && !link->skip_auth) {
int expired = taTicket.expiration_time < ltime;
if (strlen(taTicket.password) == 0) {
reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED);
spice_warning("Ticketing is enabled, but no password is set. "
"please set a ticket first");
reds_link_free(link);
return;
}
if (expired || strncmp(password, taTicket.password, SPICE_MAX_PASSWORD_LENGTH) != 0) {
if (expired) {
spice_warning("Ticket has expired");
} else {
spice_warning("Invalid password");
}
reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED);
reds_link_free(link);
return;
}
}
reds_handle_link(link);
}
Commit Message:
CWE ID: CWE-119
|
static void reds_handle_ticket(void *opaque)
{
RedLinkInfo *link = (RedLinkInfo *)opaque;
char *password;
time_t ltime;
int password_size;
time(<ime);
if (RSA_size(link->tiTicketing.rsa) < SPICE_MAX_PASSWORD_LENGTH) {
spice_warning("RSA modulus size is smaller than SPICE_MAX_PASSWORD_LENGTH (%d < %d), "
"SPICE ticket sent from client may be truncated",
RSA_size(link->tiTicketing.rsa), SPICE_MAX_PASSWORD_LENGTH);
}
password = g_malloc0(RSA_size(link->tiTicketing.rsa) + 1);
password_size = RSA_private_decrypt(link->tiTicketing.rsa_size,
link->tiTicketing.encrypted_ticket.encrypted_data,
(unsigned char *)password,
link->tiTicketing.rsa,
RSA_PKCS1_OAEP_PADDING);
if (password_size == -1) {
spice_warning("failed to decrypt RSA encrypted password: %s",
ERR_error_string(ERR_get_error(), NULL));
goto error;
}
password[password_size] = '\0';
if (ticketing_enabled && !link->skip_auth) {
int expired = taTicket.expiration_time < ltime;
if (strlen(taTicket.password) == 0) {
spice_warning("Ticketing is enabled, but no password is set. "
"please set a ticket first");
goto error;
}
if (expired || strcmp(password, taTicket.password) != 0) {
if (expired) {
spice_warning("Ticket has expired");
} else {
spice_warning("Invalid password");
}
goto error;
}
}
reds_handle_link(link);
goto end;
error:
reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED);
reds_link_free(link);
end:
g_free(password);
}
| 164,661
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: DownloadUrlParameters::DownloadUrlParameters(
const GURL& url,
int render_process_host_id,
int render_view_host_routing_id,
int render_frame_host_routing_id,
const net::NetworkTrafficAnnotationTag& traffic_annotation)
: content_initiated_(false),
use_if_range_(true),
method_("GET"),
post_id_(-1),
prefer_cache_(false),
referrer_policy_(
net::URLRequest::
CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
render_process_host_id_(render_process_host_id),
render_view_host_routing_id_(render_view_host_routing_id),
render_frame_host_routing_id_(render_frame_host_routing_id),
url_(url),
do_not_prompt_for_login_(false),
follow_cross_origin_redirects_(true),
fetch_error_body_(false),
transient_(false),
traffic_annotation_(traffic_annotation),
download_source_(DownloadSource::UNKNOWN) {}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <japhet@chromium.org>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <clamy@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
|
DownloadUrlParameters::DownloadUrlParameters(
const GURL& url,
int render_process_host_id,
int render_view_host_routing_id,
int render_frame_host_routing_id,
const net::NetworkTrafficAnnotationTag& traffic_annotation)
: content_initiated_(false),
use_if_range_(true),
method_("GET"),
post_id_(-1),
prefer_cache_(false),
referrer_policy_(
net::URLRequest::
CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
render_process_host_id_(render_process_host_id),
render_view_host_routing_id_(render_view_host_routing_id),
render_frame_host_routing_id_(render_frame_host_routing_id),
frame_tree_node_id_(-1),
url_(url),
do_not_prompt_for_login_(false),
follow_cross_origin_redirects_(true),
fetch_error_body_(false),
transient_(false),
traffic_annotation_(traffic_annotation),
download_source_(DownloadSource::UNKNOWN) {}
| 173,020
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: scoped_ptr<cc::CompositorFrame> TestSynchronousCompositor::DemandDrawHw(
gfx::Size surface_size,
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
return hardware_frame_.Pass();
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
|
scoped_ptr<cc::CompositorFrame> TestSynchronousCompositor::DemandDrawHw(
const gfx::Size& surface_size,
const gfx::Transform& transform,
const gfx::Rect& viewport,
const gfx::Rect& clip,
const gfx::Rect& viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
return hardware_frame_.Pass();
}
| 171,620
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: sf_open (const char *path, int mode, SF_INFO *sfinfo)
{ SF_PRIVATE *psf ;
/* Ultimate sanity check. */
assert (sizeof (sf_count_t) == 8) ;
if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf_log_printf (psf, "File : %s\n", path) ;
if (copy_filename (psf, path) != 0)
{ sf_errno = psf->error ;
return NULL ;
} ;
psf->file.mode = mode ;
if (strcmp (path, "-") == 0)
psf->error = psf_set_stdio (psf) ;
else
psf->error = psf_fopen (psf) ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119
|
sf_open (const char *path, int mode, SF_INFO *sfinfo)
{ SF_PRIVATE *psf ;
/* Ultimate sanity check. */
assert (sizeof (sf_count_t) == 8) ;
if ((psf = psf_allocate ()) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf_log_printf (psf, "File : %s\n", path) ;
if (copy_filename (psf, path) != 0)
{ sf_errno = psf->error ;
return NULL ;
} ;
psf->file.mode = mode ;
if (strcmp (path, "-") == 0)
psf->error = psf_set_stdio (psf) ;
else
psf->error = psf_fopen (psf) ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open */
| 170,067
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DelegatedFrameHost::ClearDelegatedFrame() {
EvictDelegatedFrame();
}
Commit Message: mac: Make RWHVMac::ClearCompositorFrame clear locks
Ensure that the BrowserCompositorMac not hold on to a compositor lock
when requested to clear its compositor frame. This lock may be held
indefinitely (if the renderer hangs) and so the frame will never be
cleared.
Bug: 739621
Change-Id: I15d0e82bdf632f3379a48e959f198afb8a4ac218
Reviewed-on: https://chromium-review.googlesource.com/608239
Commit-Queue: ccameron chromium <ccameron@chromium.org>
Reviewed-by: Ken Buchanan <kenrb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#493563}
CWE ID: CWE-20
|
void DelegatedFrameHost::ClearDelegatedFrame() {
// Ensure that we are able to swap in a new blank frame to replace any old
// content. This will result in a white flash if we switch back to this
// content.
// https://crbug.com/739621
released_front_lock_.reset();
EvictDelegatedFrame();
}
| 172,954
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void SoftAVC::drainAllOutputBuffers(bool eos) {
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
H264SwDecPicture decodedPicture;
if (mHeadersDecoded) {
while (!outQueue.empty()
&& H264SWDEC_PIC_RDY == H264SwDecNextPicture(
mHandle, &decodedPicture, eos /* flush */)) {
int32_t picId = decodedPicture.picId;
uint8_t *data = (uint8_t *) decodedPicture.pOutputPicture;
drainOneOutputBuffer(picId, data);
}
}
if (!eos) {
return;
}
while (!outQueue.empty()) {
BufferInfo *outInfo = *outQueue.begin();
outQueue.erase(outQueue.begin());
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nTimeStamp = 0;
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mEOSStatus = OUTPUT_FRAMES_FLUSHED;
}
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
CWE ID: CWE-20
|
void SoftAVC::drainAllOutputBuffers(bool eos) {
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
H264SwDecPicture decodedPicture;
if (mHeadersDecoded) {
while (!outQueue.empty()
&& H264SWDEC_PIC_RDY == H264SwDecNextPicture(
mHandle, &decodedPicture, eos /* flush */)) {
int32_t picId = decodedPicture.picId;
uint8_t *data = (uint8_t *) decodedPicture.pOutputPicture;
if (!drainOneOutputBuffer(picId, data)) {
ALOGE("Drain failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
}
}
if (!eos) {
return;
}
while (!outQueue.empty()) {
BufferInfo *outInfo = *outQueue.begin();
outQueue.erase(outQueue.begin());
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nTimeStamp = 0;
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mEOSStatus = OUTPUT_FRAMES_FLUSHED;
}
}
| 174,176
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: zrestore(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
alloc_save_t *asave;
bool last;
vm_save_t *vmsave;
int code = restore_check_operand(op, &asave, idmemory);
if (code < 0)
return code;
if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n",
(ulong) alloc_save_client_data(asave),
(ulong) op->value.saveid);
if (I_VALIDATE_BEFORE_RESTORE)
ivalidate_clean_spaces(i_ctx_p);
ivalidate_clean_spaces(i_ctx_p);
/* Check the contents of the stacks. */
{
int code;
if ((code = restore_check_stack(i_ctx_p, &o_stack, asave, false)) < 0 ||
(code = restore_check_stack(i_ctx_p, &e_stack, asave, true)) < 0 ||
(code = restore_check_stack(i_ctx_p, &d_stack, asave, false)) < 0
) {
osp++;
return code;
}
}
/* Reset l_new in all stack entries if the new save level is zero. */
/* Also do some special fixing on the e-stack. */
restore_fix_stack(i_ctx_p, &o_stack, asave, false);
}
Commit Message:
CWE ID: CWE-78
|
zrestore(i_ctx_t *i_ctx_p)
restore_check_save(i_ctx_t *i_ctx_p, alloc_save_t **asave)
{
os_ptr op = osp;
int code = restore_check_operand(op, asave, idmemory);
if (code < 0)
return code;
if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n",
(ulong) alloc_save_client_data(*asave),
(ulong) op->value.saveid);
if (I_VALIDATE_BEFORE_RESTORE)
ivalidate_clean_spaces(i_ctx_p);
ivalidate_clean_spaces(i_ctx_p);
/* Check the contents of the stacks. */
{
int code;
if ((code = restore_check_stack(i_ctx_p, &o_stack, *asave, false)) < 0 ||
(code = restore_check_stack(i_ctx_p, &e_stack, *asave, true)) < 0 ||
(code = restore_check_stack(i_ctx_p, &d_stack, *asave, false)) < 0
) {
osp++;
return code;
}
}
osp++;
return 0;
}
/* the semantics of restore differ slightly between Level 1 and
Level 2 and later - the latter includes restoring the device
state (whilst Level 1 didn't have "page devices" as such).
Hence we have two restore operators - one here (Level 1)
and one in zdevice2.c (Level 2+). For that reason, the
operand checking and guts of the restore operation are
separated so both implementations can use them to best
effect.
*/
int
dorestore(i_ctx_t *i_ctx_p, alloc_save_t *asave)
{
os_ptr op = osp;
bool last;
vm_save_t *vmsave;
int code;
osp--;
/* Reset l_new in all stack entries if the new save level is zero. */
/* Also do some special fixing on the e-stack. */
restore_fix_stack(i_ctx_p, &o_stack, asave, false);
}
| 164,688
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PrintRenderFrameHelper::PrintHeaderAndFooter(
blink::WebCanvas* canvas,
int page_number,
int total_pages,
const blink::WebLocalFrame& source_frame,
float webkit_scale_factor,
const PageSizeMargins& page_layout,
const PrintMsg_Print_Params& params) {
cc::PaintCanvasAutoRestore auto_restore(canvas, true);
canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
page_layout.content_width,
page_layout.margin_top + page_layout.margin_bottom +
page_layout.content_height);
blink::WebView* web_view = blink::WebView::Create(
nullptr, blink::mojom::PageVisibilityState::kVisible);
web_view->GetSettings()->SetJavaScriptEnabled(true);
class HeaderAndFooterClient final : public blink::WebFrameClient {
public:
void BindToFrame(blink::WebLocalFrame* frame) override { frame_ = frame; }
void FrameDetached(DetachType detach_type) override {
frame_->FrameWidget()->Close();
frame_->Close();
frame_ = nullptr;
}
private:
blink::WebLocalFrame* frame_;
};
HeaderAndFooterClient frame_client;
blink::WebLocalFrame* frame = blink::WebLocalFrame::CreateMainFrame(
web_view, &frame_client, nullptr, nullptr);
blink::WebWidgetClient web_widget_client;
blink::WebFrameWidget::Create(&web_widget_client, frame);
base::Value html(base::UTF8ToUTF16(
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_PRINT_PREVIEW_PAGE)));
ExecuteScript(frame, kPageLoadScriptFormat, html);
auto options = base::MakeUnique<base::DictionaryValue>();
options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
options->SetDouble("width", page_size.width);
options->SetDouble("height", page_size.height);
options->SetDouble("topMargin", page_layout.margin_top);
options->SetDouble("bottomMargin", page_layout.margin_bottom);
options->SetInteger("pageNumber", page_number);
options->SetInteger("totalPages", total_pages);
options->SetString("url", params.url);
base::string16 title = source_frame.GetDocument().Title().Utf16();
options->SetString("title", title.empty() ? params.title : title);
ExecuteScript(frame, kPageSetupScriptFormat, *options);
blink::WebPrintParams webkit_params(page_size);
webkit_params.printer_dpi = GetDPI(¶ms);
frame->PrintBegin(webkit_params);
frame->PrintPage(0, canvas);
frame->PrintEnd();
web_view->Close();
}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Reviewed-by: Jianzhou Feng <jzfeng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#523966}
CWE ID: CWE-20
|
void PrintRenderFrameHelper::PrintHeaderAndFooter(
blink::WebCanvas* canvas,
int page_number,
int total_pages,
const blink::WebLocalFrame& source_frame,
float webkit_scale_factor,
const PageSizeMargins& page_layout,
const PrintMsg_Print_Params& params) {
cc::PaintCanvasAutoRestore auto_restore(canvas, true);
canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
page_layout.content_width,
page_layout.margin_top + page_layout.margin_bottom +
page_layout.content_height);
blink::WebView* web_view = blink::WebView::Create(
nullptr, blink::mojom::PageVisibilityState::kVisible);
web_view->GetSettings()->SetJavaScriptEnabled(true);
class HeaderAndFooterClient final : public blink::WebFrameClient {
public:
void BindToFrame(blink::WebLocalFrame* frame) override { frame_ = frame; }
void FrameDetached(DetachType detach_type) override {
frame_->FrameWidget()->Close();
frame_->Close();
frame_ = nullptr;
}
private:
blink::WebLocalFrame* frame_;
};
HeaderAndFooterClient frame_client;
blink::WebLocalFrame* frame = blink::WebLocalFrame::CreateMainFrame(
web_view, &frame_client, nullptr, nullptr);
blink::WebWidgetClient web_widget_client;
blink::WebFrameWidget::Create(&web_widget_client, frame);
base::Value html(base::UTF8ToUTF16(
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_PRINT_PREVIEW_PAGE)));
ExecuteScript(frame, kPageLoadScriptFormat, html);
auto options = base::MakeUnique<base::DictionaryValue>();
options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
options->SetDouble("width", page_size.width);
options->SetDouble("height", page_size.height);
options->SetDouble("topMargin", page_layout.margin_top);
options->SetDouble("bottomMargin", page_layout.margin_bottom);
options->SetInteger("pageNumber", page_number);
options->SetInteger("totalPages", total_pages);
options->SetString("url", params.url);
base::string16 title = source_frame.GetDocument().Title().Utf16();
options->SetString("title", title.empty() ? params.title : title);
options->SetString("headerTemplate", params.header_template);
options->SetString("footerTemplate", params.footer_template);
ExecuteScript(frame, kPageSetupScriptFormat, *options);
blink::WebPrintParams webkit_params(page_size);
webkit_params.printer_dpi = GetDPI(¶ms);
frame->PrintBegin(webkit_params);
frame->PrintPage(0, canvas);
frame->PrintEnd();
web_view->Close();
}
| 172,899
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BluetoothDeviceChromeOS::OnPair(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Paired";
if (!pairing_delegate_used_)
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_NONE,
UMA_PAIRING_METHOD_COUNT);
UnregisterAgent();
SetTrusted();
ConnectInternal(true, callback, error_callback);
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BluetoothDeviceChromeOS::OnPair(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Paired";
pairing_context_.reset();
SetTrusted();
ConnectInternal(true, callback, error_callback);
}
| 171,227
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC)
{
php_stream *tmpstream = NULL;
databuf_t *data = NULL;
char *ptr;
int ch, lastch;
size_t size, rcvd;
size_t lines;
char **ret = NULL;
char **entry;
char *text;
if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory.");
return NULL;
}
if (!ftp_type(ftp, FTPTYPE_ASCII)) {
goto bail;
}
if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) {
goto bail;
}
ftp->data = data;
if (!ftp_putcmd(ftp, cmd, path)) {
goto bail;
}
if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) {
goto bail;
}
/* some servers don't open a ftp-data connection if the directory is empty */
if (ftp->resp == 226) {
ftp->data = data_close(ftp, data);
php_stream_close(tmpstream);
return ecalloc(1, sizeof(char*));
}
/* pull data buffer into tmpfile */
if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) {
goto bail;
}
size = 0;
lines = 0;
lastch = 0;
while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {
if (rcvd == -1 || rcvd > ((size_t)(-1))-size) {
goto bail;
}
php_stream_write(tmpstream, data->buf, rcvd);
size += rcvd;
for (ptr = data->buf; rcvd; rcvd--, ptr++) {
if (*ptr == '\n' && lastch == '\r') {
lines++;
} else {
size++;
}
lastch = *ptr;
}
lastch = *ptr;
}
}
Commit Message:
CWE ID: CWE-119
|
ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC)
{
php_stream *tmpstream = NULL;
databuf_t *data = NULL;
char *ptr;
int ch, lastch;
size_t size, rcvd;
size_t lines;
char **ret = NULL;
char **entry;
char *text;
if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory.");
return NULL;
}
if (!ftp_type(ftp, FTPTYPE_ASCII)) {
goto bail;
}
if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) {
goto bail;
}
ftp->data = data;
if (!ftp_putcmd(ftp, cmd, path)) {
goto bail;
}
if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) {
goto bail;
}
/* some servers don't open a ftp-data connection if the directory is empty */
if (ftp->resp == 226) {
ftp->data = data_close(ftp, data);
php_stream_close(tmpstream);
return ecalloc(1, sizeof(char*));
}
/* pull data buffer into tmpfile */
if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) {
goto bail;
}
size = 0;
lines = 0;
lastch = 0;
while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {
if (rcvd == -1 || rcvd > ((size_t)(-1))-size) {
goto bail;
}
php_stream_write(tmpstream, data->buf, rcvd);
size += rcvd;
for (ptr = data->buf; rcvd; rcvd--, ptr++) {
if (*ptr == '\n' && lastch == '\r') {
lines++;
}
lastch = *ptr;
}
lastch = *ptr;
}
}
| 165,301
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int cypress_generic_port_probe(struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct cypress_private *priv;
priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->comm_is_ok = !0;
spin_lock_init(&priv->lock);
if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) {
kfree(priv);
return -ENOMEM;
}
/* Skip reset for FRWD device. It is a workaound:
device hangs if it receives SET_CONFIGURE in Configured
state. */
if (!is_frwd(serial->dev))
usb_reset_configuration(serial->dev);
priv->cmd_ctrl = 0;
priv->line_control = 0;
priv->termios_initialized = 0;
priv->rx_flags = 0;
/* Default packet format setting is determined by packet size.
Anything with a size larger then 9 must have a separate
count field since the 3 bit count field is otherwise too
small. Otherwise we can use the slightly more compact
format. This is in accordance with the cypress_m8 serial
converter app note. */
if (port->interrupt_out_size > 9)
priv->pkt_fmt = packet_format_1;
else
priv->pkt_fmt = packet_format_2;
if (interval > 0) {
priv->write_urb_interval = interval;
priv->read_urb_interval = interval;
dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n",
__func__, interval);
} else {
priv->write_urb_interval = port->interrupt_out_urb->interval;
priv->read_urb_interval = port->interrupt_in_urb->interval;
dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n",
__func__, priv->read_urb_interval,
priv->write_urb_interval);
}
usb_set_serial_port_data(port, priv);
port->port.drain_delay = 256;
return 0;
}
Commit Message: USB: cypress_m8: add endpoint sanity check
An attack using missing endpoints exists.
CVE-2016-3137
Signed-off-by: Oliver Neukum <ONeukum@suse.com>
CC: stable@vger.kernel.org
Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID:
|
static int cypress_generic_port_probe(struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct cypress_private *priv;
if (!port->interrupt_out_urb || !port->interrupt_in_urb) {
dev_err(&port->dev, "required endpoint is missing\n");
return -ENODEV;
}
priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->comm_is_ok = !0;
spin_lock_init(&priv->lock);
if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) {
kfree(priv);
return -ENOMEM;
}
/* Skip reset for FRWD device. It is a workaound:
device hangs if it receives SET_CONFIGURE in Configured
state. */
if (!is_frwd(serial->dev))
usb_reset_configuration(serial->dev);
priv->cmd_ctrl = 0;
priv->line_control = 0;
priv->termios_initialized = 0;
priv->rx_flags = 0;
/* Default packet format setting is determined by packet size.
Anything with a size larger then 9 must have a separate
count field since the 3 bit count field is otherwise too
small. Otherwise we can use the slightly more compact
format. This is in accordance with the cypress_m8 serial
converter app note. */
if (port->interrupt_out_size > 9)
priv->pkt_fmt = packet_format_1;
else
priv->pkt_fmt = packet_format_2;
if (interval > 0) {
priv->write_urb_interval = interval;
priv->read_urb_interval = interval;
dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n",
__func__, interval);
} else {
priv->write_urb_interval = port->interrupt_out_urb->interval;
priv->read_urb_interval = port->interrupt_in_urb->interval;
dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n",
__func__, priv->read_urb_interval,
priv->write_urb_interval);
}
usb_set_serial_port_data(port, priv);
port->port.drain_delay = 256;
return 0;
}
| 167,359
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void rng_backend_request_entropy(RngBackend *s, size_t size,
EntropyReceiveFunc *receive_entropy,
void *opaque)
{
RngBackendClass *k = RNG_BACKEND_GET_CLASS(s);
if (k->request_entropy) {
k->request_entropy(s, size, receive_entropy, opaque);
}
}
Commit Message:
CWE ID: CWE-119
|
void rng_backend_request_entropy(RngBackend *s, size_t size,
EntropyReceiveFunc *receive_entropy,
void *opaque)
{
RngBackendClass *k = RNG_BACKEND_GET_CLASS(s);
RngRequest *req;
if (k->request_entropy) {
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
k->request_entropy(s, req);
s->requests = g_slist_append(s->requests, req);
}
}
| 165,181
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
unsigned code_point;
ReadUTFChar(spec, &i, end, &code_point);
AppendUTF8Value(code_point, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
Commit Message: Percent-encode UTF8 characters in URL fragment identifiers.
This brings us into line with Firefox, Safari, and the spec.
Bug: 758523
Change-Id: I7e354ab441222d9fd08e45f0e70f91ad4e35fafe
Reviewed-on: https://chromium-review.googlesource.com/668363
Commit-Queue: Mike West <mkwst@chromium.org>
Reviewed-by: Jochen Eisinger <jochen@chromium.org>
Reviewed-by: Andy Paicu <andypaicu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#507481}
CWE ID: CWE-79
|
void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
AppendUTF8EscapedChar(spec, &i, end, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
| 172,903
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void WebContentsImpl::DidFailProvisionalLoadWithError(
RenderViewHost* render_view_host,
const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
<< ", error_code: " << params.error_code
<< ", error_description: " << params.error_description
<< ", is_main_frame: " << params.is_main_frame
<< ", showing_repost_interstitial: " <<
params.showing_repost_interstitial
<< ", frame_id: " << params.frame_id;
GURL validated_url(params.url);
RenderProcessHost* render_process_host =
render_view_host->GetProcess();
RenderViewHost::FilterURL(render_process_host, false, &validated_url);
if (net::ERR_ABORTED == params.error_code) {
if (ShowingInterstitialPage()) {
LOG(WARNING) << "Discarding message during interstitial.";
return;
}
render_manager_.RendererAbortedProvisionalLoad(render_view_host);
}
FOR_EACH_OBSERVER(WebContentsObserver,
observers_,
DidFailProvisionalLoad(params.frame_id,
params.is_main_frame,
validated_url,
params.error_code,
params.error_description,
render_view_host));
}
Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof.
BUG=280512
BUG=278899
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23978003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void WebContentsImpl::DidFailProvisionalLoadWithError(
RenderViewHost* render_view_host,
const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
<< ", error_code: " << params.error_code
<< ", error_description: " << params.error_description
<< ", is_main_frame: " << params.is_main_frame
<< ", showing_repost_interstitial: " <<
params.showing_repost_interstitial
<< ", frame_id: " << params.frame_id;
GURL validated_url(params.url);
RenderProcessHost* render_process_host =
render_view_host->GetProcess();
RenderViewHost::FilterURL(render_process_host, false, &validated_url);
if (net::ERR_ABORTED == params.error_code) {
if (ShowingInterstitialPage()) {
LOG(WARNING) << "Discarding message during interstitial.";
return;
}
render_manager_.RendererAbortedProvisionalLoad(render_view_host);
}
// Do not usually clear the pending entry if one exists, so that the user's
// typed URL is not lost when a navigation fails or is aborted. However, in
// cases that we don't show the pending entry (e.g., renderer-initiated
// navigations in an existing tab), we don't keep it around. That prevents
// spoofs on in-page navigations that don't go through
// DidStartProvisionalLoadForFrame.
// In general, we allow the view to clear the pending entry and typed URL if
// the user requests (e.g., hitting Escape with focus in the address bar).
// Note: don't touch the transient entry, since an interstitial may exist.
if (controller_.GetPendingEntry() != controller_.GetVisibleEntry())
controller_.DiscardPendingEntry();
FOR_EACH_OBSERVER(WebContentsObserver,
observers_,
DidFailProvisionalLoad(params.frame_id,
params.is_main_frame,
validated_url,
params.error_code,
params.error_description,
render_view_host));
}
| 171,189
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int PreProcessingFx_ProcessReverse(effect_handle_t self,
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer)
{
preproc_effect_t * effect = (preproc_effect_t *)self;
int status = 0;
if (effect == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL");
return -EINVAL;
}
preproc_session_t * session = (preproc_session_t *)effect->session;
if (inBuffer == NULL || inBuffer->raw == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer");
return -EINVAL;
}
session->revProcessedMsk |= (1<<effect->procId);
if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) {
effect->session->revProcessedMsk = 0;
if (session->revResampler != NULL) {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
if (session->revBufSize < session->framesRev + fr) {
session->revBufSize = session->framesRev + fr;
session->revBuf = (int16_t *)realloc(session->revBuf,
session->revBufSize * session->inChannelCount * sizeof(int16_t));
}
memcpy(session->revBuf + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
spx_uint32_t frIn = session->framesRev;
spx_uint32_t frOut = session->apmFrameCount;
if (session->inChannelCount == 1) {
speex_resampler_process_int(session->revResampler,
0,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
} else {
speex_resampler_process_interleaved_int(session->revResampler,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
}
memcpy(session->revBuf,
session->revBuf + frIn * session->inChannelCount,
(session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t));
session->framesRev -= frIn;
} else {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
memcpy(session->revFrame->_payloadData + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
session->framesRev = 0;
}
session->revFrame->_payloadDataLengthInSamples =
session->apmFrameCount * session->inChannelCount;
effect->session->apm->AnalyzeReverseStream(session->revFrame);
return 0;
} else {
return -ENODATA;
}
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119
|
int PreProcessingFx_ProcessReverse(effect_handle_t self,
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer __unused)
{
preproc_effect_t * effect = (preproc_effect_t *)self;
int status = 0;
if (effect == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL");
return -EINVAL;
}
preproc_session_t * session = (preproc_session_t *)effect->session;
if (inBuffer == NULL || inBuffer->raw == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer");
return -EINVAL;
}
session->revProcessedMsk |= (1<<effect->procId);
if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) {
effect->session->revProcessedMsk = 0;
if (session->revResampler != NULL) {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
if (session->revBufSize < session->framesRev + fr) {
session->revBufSize = session->framesRev + fr;
session->revBuf = (int16_t *)realloc(session->revBuf,
session->revBufSize * session->inChannelCount * sizeof(int16_t));
}
memcpy(session->revBuf + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
spx_uint32_t frIn = session->framesRev;
spx_uint32_t frOut = session->apmFrameCount;
if (session->inChannelCount == 1) {
speex_resampler_process_int(session->revResampler,
0,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
} else {
speex_resampler_process_interleaved_int(session->revResampler,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
}
memcpy(session->revBuf,
session->revBuf + frIn * session->inChannelCount,
(session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t));
session->framesRev -= frIn;
} else {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
memcpy(session->revFrame->_payloadData + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
session->framesRev = 0;
}
session->revFrame->_payloadDataLengthInSamples =
session->apmFrameCount * session->inChannelCount;
effect->session->apm->AnalyzeReverseStream(session->revFrame);
return 0;
} else {
return -ENODATA;
}
}
| 173,354
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.