instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| 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: static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)
{
struct xenvif *vif;
struct pending_tx_info *pending_tx_info;
pending_ring_idx_t index;
/* Already complete? */
if (netbk->mmap_pages[pending_idx] == NULL)
return;
pending_tx_info = &netbk->pending_tx_info[pending_idx];
vif = pending_tx_info->vif;
make_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY);
index = pending_index(netbk->pending_prod++);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
netbk->mmap_pages[pending_idx]->mapping = 0;
put_page(netbk->mmap_pages[pending_idx]);
netbk->mmap_pages[pending_idx] = NULL;
}
Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop.
Signed-off-by: Matthew Daley <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Ian Campbell <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)
static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx,
u8 status)
{
struct xenvif *vif;
struct pending_tx_info *pending_tx_info;
pending_ring_idx_t index;
/* Already complete? */
if (netbk->mmap_pages[pending_idx] == NULL)
return;
pending_tx_info = &netbk->pending_tx_info[pending_idx];
vif = pending_tx_info->vif;
make_tx_response(vif, &pending_tx_info->req, status);
index = pending_index(netbk->pending_prod++);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
netbk->mmap_pages[pending_idx]->mapping = 0;
put_page(netbk->mmap_pages[pending_idx]);
netbk->mmap_pages[pending_idx] = NULL;
}
| 166,168 |
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 file_sb_list_add(struct file *file, struct super_block *sb)
{
if (likely(!(file->f_mode & FMODE_WRITE)))
return;
if (!S_ISREG(file_inode(file)->i_mode))
return;
lg_local_lock(&files_lglock);
__file_sb_list_add(file, sb);
lg_local_unlock(&files_lglock);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | void file_sb_list_add(struct file *file, struct super_block *sb)
| 166,798 |
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: WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID(
int window_id,
std::string* error) {
Browser* browser = NULL;
if (!GetBrowserFromWindowID(chrome_details_, window_id, &browser, error))
return nullptr;
WebContents* contents = browser->tab_strip_model()->GetActiveWebContents();
if (!contents) {
*error = "No active web contents to capture";
return nullptr;
}
if (!extension()->permissions_data()->CanCaptureVisiblePage(
contents->GetLastCommittedURL(),
SessionTabHelper::IdForTab(contents).id(), error)) {
return nullptr;
}
return contents;
}
Commit Message: Call CanCaptureVisiblePage in page capture API.
Currently the pageCapture permission allows access
to arbitrary local files and chrome:// pages which
can be a security concern. In order to address this,
the page capture API needs to be changed similar to
the captureVisibleTab API. The API will now only allow
extensions to capture otherwise-restricted URLs if the
user has granted activeTab. In addition, file:// URLs are
only capturable with the "Allow on file URLs" option enabled.
Bug: 893087
Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624
Reviewed-on: https://chromium-review.googlesource.com/c/1330689
Commit-Queue: Bettina Dea <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Varun Khaneja <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615248}
CWE ID: CWE-20 | WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID(
int window_id,
std::string* error) {
Browser* browser = NULL;
if (!GetBrowserFromWindowID(chrome_details_, window_id, &browser, error))
return nullptr;
WebContents* contents = browser->tab_strip_model()->GetActiveWebContents();
if (!contents) {
*error = "No active web contents to capture";
return nullptr;
}
if (!extension()->permissions_data()->CanCaptureVisiblePage(
contents->GetLastCommittedURL(),
SessionTabHelper::IdForTab(contents).id(), error,
extensions::CaptureRequirement::kActiveTabOrAllUrls)) {
return nullptr;
}
return contents;
}
| 173,005 |
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 *jas_malloc(size_t size)
{
void *result;
JAS_DBGLOG(101, ("jas_malloc called with %zu\n", size));
result = malloc(size);
JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result));
return result;
}
Commit Message: Fixed an integer overflow problem.
CWE ID: CWE-190 | void *jas_malloc(size_t size)
{
void *result;
JAS_DBGLOG(101, ("jas_malloc(%zu)\n", size));
result = malloc(size);
JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result));
return result;
}
| 168,474 |
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: open_patch_file (char const *filename)
{
file_offset file_pos = 0;
file_offset pos;
struct stat st;
if (!filename || !*filename || strEQ (filename, "-"))
pfp = stdin;
else
{
pfp = fopen (filename, binary_transput ? "rb" : "r");
if (!pfp)
pfatal ("Can't open patch file %s", quotearg (filename));
}
#if HAVE_SETMODE_DOS
if (binary_transput)
{
if (isatty (fileno (pfp)))
fatal ("cannot read binary data from tty on this platform");
setmode (fileno (pfp), O_BINARY);
}
#endif
if (fstat (fileno (pfp), &st) != 0)
pfatal ("fstat");
if (S_ISREG (st.st_mode) && (pos = file_tell (pfp)) != -1)
file_pos = pos;
else
{
size_t charsread;
int fd = make_tempfile (&TMPPATNAME, 'p', NULL, O_RDWR | O_BINARY, 0);
FILE *read_pfp = pfp;
TMPPATNAME_needs_removal = true;
pfp = fdopen (fd, "w+b");
if (! pfp)
pfatal ("Can't open stream for file %s", quotearg (TMPPATNAME));
for (st.st_size = 0;
(charsread = fread (buf, 1, bufsize, read_pfp)) != 0;
st.st_size += charsread)
if (fwrite (buf, 1, charsread, pfp) != charsread)
write_fatal ();
if (ferror (read_pfp) || fclose (read_pfp) != 0)
read_fatal ();
if (fflush (pfp) != 0
|| file_seek (pfp, (file_offset) 0, SEEK_SET) != 0)
write_fatal ();
}
p_filesize = st.st_size;
if (p_filesize != (file_offset) p_filesize)
fatal ("patch file is too long");
next_intuit_at (file_pos, 1);
set_hunkmax();
}
Commit Message:
CWE ID: CWE-399 | open_patch_file (char const *filename)
{
file_offset file_pos = 0;
file_offset pos;
struct stat st;
if (!filename || !*filename || strEQ (filename, "-"))
pfp = stdin;
else
{
pfp = fopen (filename, binary_transput ? "rb" : "r");
if (!pfp)
pfatal ("Can't open patch file %s", quotearg (filename));
}
#if HAVE_SETMODE_DOS
if (binary_transput)
{
if (isatty (fileno (pfp)))
fatal ("cannot read binary data from tty on this platform");
setmode (fileno (pfp), O_BINARY);
}
#endif
if (fstat (fileno (pfp), &st) != 0)
pfatal ("fstat");
if (S_ISREG (st.st_mode) && (pos = file_tell (pfp)) != -1)
file_pos = pos;
else
{
size_t charsread;
int fd = make_tempfile (&TMPPATNAME, 'p', NULL, O_RDWR | O_BINARY, 0);
FILE *read_pfp = pfp;
TMPPATNAME_needs_removal = true;
pfp = fdopen (fd, "w+b");
if (! pfp)
pfatal ("Can't open stream for file %s", quotearg (TMPPATNAME));
for (st.st_size = 0;
(charsread = fread (buf, 1, bufsize, read_pfp)) != 0;
st.st_size += charsread)
if (fwrite (buf, 1, charsread, pfp) != charsread)
write_fatal ();
if (ferror (read_pfp) || fclose (read_pfp) != 0)
read_fatal ();
if (fflush (pfp) != 0
|| file_seek (pfp, (file_offset) 0, SEEK_SET) != 0)
write_fatal ();
}
p_filesize = st.st_size;
if (p_filesize != (file_offset) p_filesize)
fatal ("patch file is too long");
next_intuit_at (file_pos, 1);
}
| 165,400 |
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 pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr)
{
int c;
uchar buf[2];
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
buf[0] = c;
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
buf[1] = c;
hdr->magic = buf[0] << 8 | buf[1];
if (hdr->magic != PGX_MAGIC) {
jas_eprintf("invalid PGX signature\n");
goto error;
}
if ((c = pgx_getc(in)) == EOF || !isspace(c)) {
goto error;
}
if (pgx_getbyteorder(in, &hdr->bigendian)) {
jas_eprintf("cannot get byte order\n");
goto error;
}
if (pgx_getsgnd(in, &hdr->sgnd)) {
jas_eprintf("cannot get signedness\n");
goto error;
}
if (pgx_getuint32(in, &hdr->prec)) {
jas_eprintf("cannot get precision\n");
goto error;
}
if (pgx_getuint32(in, &hdr->width)) {
jas_eprintf("cannot get width\n");
goto error;
}
if (pgx_getuint32(in, &hdr->height)) {
jas_eprintf("cannot get height\n");
goto error;
}
return 0;
error:
return -1;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr)
{
int c;
jas_uchar buf[2];
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
buf[0] = c;
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
buf[1] = c;
hdr->magic = buf[0] << 8 | buf[1];
if (hdr->magic != PGX_MAGIC) {
jas_eprintf("invalid PGX signature\n");
goto error;
}
if ((c = pgx_getc(in)) == EOF || !isspace(c)) {
goto error;
}
if (pgx_getbyteorder(in, &hdr->bigendian)) {
jas_eprintf("cannot get byte order\n");
goto error;
}
if (pgx_getsgnd(in, &hdr->sgnd)) {
jas_eprintf("cannot get signedness\n");
goto error;
}
if (pgx_getuint32(in, &hdr->prec)) {
jas_eprintf("cannot get precision\n");
goto error;
}
if (pgx_getuint32(in, &hdr->width)) {
jas_eprintf("cannot get width\n");
goto error;
}
if (pgx_getuint32(in, &hdr->height)) {
jas_eprintf("cannot get height\n");
goto error;
}
return 0;
error:
return -1;
}
| 168,726 |
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 SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) {
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
notifyEmptyBufferDone(inHeader);
continue;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nOffset == 0) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumSamplesOutput = 0;
}
const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset;
int32_t numBytesRead;
if (mMode == MODE_NARROW) {
if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) {
ALOGE("b/27662364: NB expected output buffer %zu bytes vs %u",
kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "27662364");
notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL);
mSignalledError = true;
return;
}
int16 mode = ((inputPtr[0] >> 3) & 0x0f);
size_t frameSize = WmfDecBytesPerFrame[mode] + 1;
if (inHeader->nFilledLen < frameSize) {
ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL);
mSignalledError = true;
return;
}
numBytesRead =
AMRDecode(mState,
(Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f),
(UWord8 *)&inputPtr[1],
reinterpret_cast<int16_t *>(outHeader->pBuffer),
MIME_IETF);
if (numBytesRead == -1) {
ALOGE("PV AMR decoder AMRDecode() call failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
++numBytesRead; // Include the frame type header byte.
if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
} else {
if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) {
ALOGE("b/27662364: WB expected output buffer %zu bytes vs %u",
kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "27662364");
notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL);
mSignalledError = true;
return;
}
int16 mode = ((inputPtr[0] >> 3) & 0x0f);
if (mode >= 10 && mode <= 13) {
ALOGE("encountered illegal frame type %d in AMR WB content.",
mode);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
size_t frameSize = getFrameSize(mode);
if (inHeader->nFilledLen < frameSize) {
ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL);
mSignalledError = true;
return;
}
int16_t *outPtr = (int16_t *)outHeader->pBuffer;
if (mode >= 9) {
memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t));
} else if (mode < 9) {
int16 frameType;
RX_State_wb rx_state;
mime_unsorting(
const_cast<uint8_t *>(&inputPtr[1]),
mInputSampleBuffer,
&frameType, &mode, 1, &rx_state);
int16_t numSamplesOutput;
pvDecoder_AmrWb(
mode, mInputSampleBuffer,
outPtr,
&numSamplesOutput,
mDecoderBuf, frameType, mDecoderCookie);
CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB);
for (int i = 0; i < kNumSamplesPerFrameWB; ++i) {
/* Delete the 2 LSBs (14-bit output) */
outPtr[i] &= 0xfffC;
}
}
numBytesRead = frameSize;
}
inHeader->nOffset += numBytesRead;
inHeader->nFilledLen -= numBytesRead;
outHeader->nFlags = 0;
outHeader->nOffset = 0;
if (mMode == MODE_NARROW) {
outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateNB;
mNumSamplesOutput += kNumSamplesPerFrameNB;
} else {
outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateWB;
mNumSamplesOutput += kNumSamplesPerFrameWB;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mInputBufferCount;
}
}
Commit Message: Fix AMR decoder
Previous change caused EOS to be ignored.
Bug: 27843673
Related-to-bug: 27662364
Change-Id: Ia148a88abc861a9b393f42bc7cd63d8d3ae349bc
CWE ID: CWE-264 | void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) {
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
notifyEmptyBufferDone(inHeader);
continue;
}
if (inHeader->nOffset == 0) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumSamplesOutput = 0;
}
const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset;
int32_t numBytesRead;
if (mMode == MODE_NARROW) {
if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) {
ALOGE("b/27662364: NB expected output buffer %zu bytes vs %u",
kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "27662364");
notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL);
mSignalledError = true;
return;
}
int16 mode = ((inputPtr[0] >> 3) & 0x0f);
size_t frameSize = WmfDecBytesPerFrame[mode] + 1;
if (inHeader->nFilledLen < frameSize) {
ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL);
mSignalledError = true;
return;
}
numBytesRead =
AMRDecode(mState,
(Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f),
(UWord8 *)&inputPtr[1],
reinterpret_cast<int16_t *>(outHeader->pBuffer),
MIME_IETF);
if (numBytesRead == -1) {
ALOGE("PV AMR decoder AMRDecode() call failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
++numBytesRead; // Include the frame type header byte.
if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
} else {
if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) {
ALOGE("b/27662364: WB expected output buffer %zu bytes vs %u",
kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "27662364");
notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL);
mSignalledError = true;
return;
}
int16 mode = ((inputPtr[0] >> 3) & 0x0f);
if (mode >= 10 && mode <= 13) {
ALOGE("encountered illegal frame type %d in AMR WB content.",
mode);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
size_t frameSize = getFrameSize(mode);
if (inHeader->nFilledLen < frameSize) {
ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL);
mSignalledError = true;
return;
}
int16_t *outPtr = (int16_t *)outHeader->pBuffer;
if (mode >= 9) {
memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t));
} else if (mode < 9) {
int16 frameType;
RX_State_wb rx_state;
mime_unsorting(
const_cast<uint8_t *>(&inputPtr[1]),
mInputSampleBuffer,
&frameType, &mode, 1, &rx_state);
int16_t numSamplesOutput;
pvDecoder_AmrWb(
mode, mInputSampleBuffer,
outPtr,
&numSamplesOutput,
mDecoderBuf, frameType, mDecoderCookie);
CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB);
for (int i = 0; i < kNumSamplesPerFrameWB; ++i) {
/* Delete the 2 LSBs (14-bit output) */
outPtr[i] &= 0xfffC;
}
}
numBytesRead = frameSize;
}
inHeader->nOffset += numBytesRead;
inHeader->nFilledLen -= numBytesRead;
outHeader->nFlags = 0;
outHeader->nOffset = 0;
if (mMode == MODE_NARROW) {
outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateNB;
mNumSamplesOutput += kNumSamplesPerFrameNB;
} else {
outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateWB;
mNumSamplesOutput += kNumSamplesPerFrameWB;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mInputBufferCount;
}
}
| 174,230 |
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 GpuProcessHost::DidFailInitialize() {
UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", false);
status_ = FAILURE;
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
gpu_data_manager->FallBackToNextGpuMode();
RunRequestGPUInfoCallbacks(gpu_data_manager->GetGPUInfo());
}
Commit Message: Fix GPU process fallback logic.
1. In GpuProcessHost::OnProcessCrashed() record the process crash first.
This means the GPU mode fallback will happen before a new GPU process
is started.
2. Don't call FallBackToNextGpuMode() if GPU process initialization
fails for an unsandboxed GPU process. The unsandboxed GPU is only
used for collect information and it's failure doesn't indicate a need
to change GPU modes.
Bug: 869419
Change-Id: I8bd0a03268f0ea8809f3df8458d4e6a92db9391f
Reviewed-on: https://chromium-review.googlesource.com/1157164
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: kylechar <[email protected]>
Cr-Commit-Position: refs/heads/master@{#579625}
CWE ID: | void GpuProcessHost::DidFailInitialize() {
UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", false);
status_ = FAILURE;
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
if (kind_ == GPU_PROCESS_KIND_SANDBOXED)
gpu_data_manager->FallBackToNextGpuMode();
RunRequestGPUInfoCallbacks(gpu_data_manager->GetGPUInfo());
}
| 172,241 |
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: buffer_add_range(int fd, struct evbuffer *evb, struct range *range)
{
char buf[BUFSIZ];
size_t n, range_sz;
ssize_t nread;
if (lseek(fd, range->start, SEEK_SET) == -1)
return (0);
range_sz = range->end - range->start + 1;
while (range_sz) {
n = MINIMUM(range_sz, sizeof(buf));
if ((nread = read(fd, buf, n)) == -1)
return (0);
evbuffer_add(evb, buf, nread);
range_sz -= nread;
}
return (1);
}
Commit Message: Reimplement httpd's support for byte ranges.
The previous implementation loaded all the output into a single output
buffer and used its size to determine the Content-Length of the body.
The new implementation calculates the body length first and writes the
individual ranges in an async way using the bufferevent mechanism.
This prevents httpd from using too much memory and applies the
watermark and throttling mechanisms to range requests.
Problem reported by Pierre Kim (pierre.kim.sec at gmail.com)
OK benno@ sunil@
CWE ID: CWE-770 | buffer_add_range(int fd, struct evbuffer *evb, struct range *range)
| 168,375 |
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: content::DownloadFile* MockDownloadFileFactory::CreateFile(
DownloadCreateInfo* info,
scoped_ptr<content::ByteStreamReader> stream,
content::DownloadManager* download_manager,
bool calculate_hash,
const net::BoundNetLog& bound_net_log) {
DCHECK(files_.end() == files_.find(info->download_id));
MockDownloadFile* created_file = new MockDownloadFile();
files_[info->download_id] = created_file;
ON_CALL(*created_file, GetDownloadManager())
.WillByDefault(Return(download_manager));
EXPECT_CALL(*created_file, Initialize());
return created_file;
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | content::DownloadFile* MockDownloadFileFactory::CreateFile(
DownloadCreateInfo* info,
scoped_ptr<content::ByteStreamReader> stream,
content::DownloadManager* download_manager,
bool calculate_hash,
const net::BoundNetLog& bound_net_log) {
DCHECK(files_.end() == files_.find(info->download_id));
MockDownloadFile* created_file = new StrictMock<MockDownloadFile>();
files_[info->download_id] = created_file;
ON_CALL(*created_file, GetDownloadManager())
.WillByDefault(Return(download_manager));
EXPECT_CALL(*created_file, Initialize());
return created_file;
}
| 170,880 |
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: parse_field(netdissect_options *ndo, const char **pptr, int *len)
{
const char *s;
if (*len <= 0 || !pptr || !*pptr)
return NULL;
if (*pptr > (const char *) ndo->ndo_snapend)
return NULL;
s = *pptr;
while (*pptr <= (const char *) ndo->ndo_snapend && *len >= 0 && **pptr) {
(*pptr)++;
(*len)--;
}
(*pptr)++;
(*len)--;
if (*len < 0 || *pptr > (const char *) ndo->ndo_snapend)
return NULL;
return s;
}
Commit Message: CVE-2017-12902/Zephyr: Fix bounds checking.
Use ND_TTEST() rather than comparing against ndo->ndo_snapend ourselves;
it's easy to get the tests wrong.
Check for running out of packet data before checking for running out of
captured data, and distinguish between running out of packet data (which
might just mean "no more strings") and running out of captured data
(which means "truncated").
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | parse_field(netdissect_options *ndo, const char **pptr, int *len)
parse_field(netdissect_options *ndo, const char **pptr, int *len, int *truncated)
{
const char *s;
/* Start of string */
s = *pptr;
/* Scan for the NUL terminator */
for (;;) {
if (*len == 0) {
/* Ran out of packet data without finding it */
return NULL;
}
if (!ND_TTEST(**pptr)) {
/* Ran out of captured data without finding it */
*truncated = 1;
return NULL;
}
if (**pptr == '\0') {
/* Found it */
break;
}
/* Keep scanning */
(*pptr)++;
(*len)--;
}
/* Skip the NUL terminator */
(*pptr)++;
(*len)--;
return s;
}
| 167,935 |
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: cisco_autorp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int type;
int numrps;
int hold;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " auto-rp "));
type = bp[0];
switch (type) {
case 0x11:
ND_PRINT((ndo, "candidate-advert"));
break;
case 0x12:
ND_PRINT((ndo, "mapping"));
break;
default:
ND_PRINT((ndo, "type-0x%02x", type));
break;
}
ND_TCHECK(bp[1]);
numrps = bp[1];
ND_TCHECK2(bp[2], 2);
ND_PRINT((ndo, " Hold "));
hold = EXTRACT_16BITS(&bp[2]);
if (hold)
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
else
ND_PRINT((ndo, "FOREVER"));
/* Next 4 bytes are reserved. */
bp += 8; len -= 8;
/*XXX skip unless -v? */
/*
* Rest of packet:
* numrps entries of the form:
* 32 bits: RP
* 6 bits: reserved
* 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2".
* 8 bits: # of entries for this RP
* each entry: 7 bits: reserved, 1 bit: negative,
* 8 bits: mask 32 bits: source
* lather, rinse, repeat.
*/
while (numrps--) {
int nentries;
char s;
ND_TCHECK2(bp[0], 4);
ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp)));
ND_TCHECK(bp[4]);
switch (bp[4] & 0x3) {
case 0: ND_PRINT((ndo, " PIMv?"));
break;
case 1: ND_PRINT((ndo, " PIMv1"));
break;
case 2: ND_PRINT((ndo, " PIMv2"));
break;
case 3: ND_PRINT((ndo, " PIMv1+2"));
break;
}
if (bp[4] & 0xfc)
ND_PRINT((ndo, " [rsvd=0x%02x]", bp[4] & 0xfc));
ND_TCHECK(bp[5]);
nentries = bp[5];
bp += 6; len -= 6;
s = ' ';
for (; nentries; nentries--) {
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "",
ipaddr_string(ndo, &bp[2]), bp[1]));
if (bp[0] & 0x02) {
ND_PRINT((ndo, " bidir"));
}
if (bp[0] & 0xfc) {
ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc));
}
s = ',';
bp += 6; len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|autorp]"));
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
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), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125 | cisco_autorp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int type;
int numrps;
int hold;
if (len < 8)
goto trunc;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " auto-rp "));
type = bp[0];
switch (type) {
case 0x11:
ND_PRINT((ndo, "candidate-advert"));
break;
case 0x12:
ND_PRINT((ndo, "mapping"));
break;
default:
ND_PRINT((ndo, "type-0x%02x", type));
break;
}
ND_TCHECK(bp[1]);
numrps = bp[1];
ND_TCHECK2(bp[2], 2);
ND_PRINT((ndo, " Hold "));
hold = EXTRACT_16BITS(&bp[2]);
if (hold)
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
else
ND_PRINT((ndo, "FOREVER"));
/* Next 4 bytes are reserved. */
bp += 8; len -= 8;
/*XXX skip unless -v? */
/*
* Rest of packet:
* numrps entries of the form:
* 32 bits: RP
* 6 bits: reserved
* 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2".
* 8 bits: # of entries for this RP
* each entry: 7 bits: reserved, 1 bit: negative,
* 8 bits: mask 32 bits: source
* lather, rinse, repeat.
*/
while (numrps--) {
int nentries;
char s;
if (len < 4)
goto trunc;
ND_TCHECK2(bp[0], 4);
ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp)));
bp += 4;
len -= 4;
if (len < 1)
goto trunc;
ND_TCHECK(bp[0]);
switch (bp[0] & 0x3) {
case 0: ND_PRINT((ndo, " PIMv?"));
break;
case 1: ND_PRINT((ndo, " PIMv1"));
break;
case 2: ND_PRINT((ndo, " PIMv2"));
break;
case 3: ND_PRINT((ndo, " PIMv1+2"));
break;
}
if (bp[0] & 0xfc)
ND_PRINT((ndo, " [rsvd=0x%02x]", bp[0] & 0xfc));
bp += 1;
len -= 1;
if (len < 1)
goto trunc;
ND_TCHECK(bp[0]);
nentries = bp[0];
bp += 1;
len -= 1;
s = ' ';
for (; nentries; nentries--) {
if (len < 6)
goto trunc;
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "",
ipaddr_string(ndo, &bp[2]), bp[1]));
if (bp[0] & 0x02) {
ND_PRINT((ndo, " bidir"));
}
if (bp[0] & 0xfc) {
ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc));
}
s = ',';
bp += 6; len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|autorp]"));
return;
}
| 167,853 |
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 phy *serdes_simple_xlate(struct device *dev,
struct of_phandle_args *args)
{
struct serdes_ctrl *ctrl = dev_get_drvdata(dev);
unsigned int port, idx, i;
if (args->args_count != 2)
return ERR_PTR(-EINVAL);
port = args->args[0];
idx = args->args[1];
for (i = 0; i <= SERDES_MAX; i++) {
struct serdes_macro *macro = phy_get_drvdata(ctrl->phys[i]);
if (idx != macro->idx)
continue;
/* SERDES6G(0) is the only SerDes capable of QSGMII */
if (idx != SERDES6G(0) && macro->port >= 0)
return ERR_PTR(-EBUSY);
macro->port = port;
return ctrl->phys[i];
}
return ERR_PTR(-ENODEV);
}
Commit Message: phy: ocelot-serdes: fix out-of-bounds read
Currently, there is an out-of-bounds read on array ctrl->phys,
once variable i reaches the maximum array size of SERDES_MAX
in the for loop.
Fix this by changing the condition in the for loop from
i <= SERDES_MAX to i < SERDES_MAX.
Addresses-Coverity-ID: 1473966 ("Out-of-bounds read")
Addresses-Coverity-ID: 1473959 ("Out-of-bounds read")
Fixes: 51f6b410fc22 ("phy: add driver for Microsemi Ocelot SerDes muxing")
Reviewed-by: Quentin Schulz <[email protected]>
Signed-off-by: Gustavo A. R. Silva <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125 | static struct phy *serdes_simple_xlate(struct device *dev,
struct of_phandle_args *args)
{
struct serdes_ctrl *ctrl = dev_get_drvdata(dev);
unsigned int port, idx, i;
if (args->args_count != 2)
return ERR_PTR(-EINVAL);
port = args->args[0];
idx = args->args[1];
for (i = 0; i < SERDES_MAX; i++) {
struct serdes_macro *macro = phy_get_drvdata(ctrl->phys[i]);
if (idx != macro->idx)
continue;
/* SERDES6G(0) is the only SerDes capable of QSGMII */
if (idx != SERDES6G(0) && macro->port >= 0)
return ERR_PTR(-EBUSY);
macro->port = port;
return ctrl->phys[i];
}
return ERR_PTR(-ENODEV);
}
| 169,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: char *FLTGetIsLikeComparisonExpression(FilterEncodingNode *psFilterNode)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char szTmp[256];
char *pszValue = NULL;
const char *pszWild = NULL;
const char *pszSingle = NULL;
const char *pszEscape = NULL;
int bCaseInsensitive = 0;
int nLength=0, i=0, iTmp=0;
FEPropertyIsLike* propIsLike;
if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
!psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
return NULL;
propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;
pszWild = propIsLike->pszWildCard;
pszSingle = propIsLike->pszSingleChar;
pszEscape = propIsLike->pszEscapeChar;
bCaseInsensitive = propIsLike->bCaseInsensitive;
if (!pszWild || strlen(pszWild) == 0 ||
!pszSingle || strlen(pszSingle) == 0 ||
!pszEscape || strlen(pszEscape) == 0)
return NULL;
/* -------------------------------------------------------------------- */
/* Use operand with regular expressions. */
/* -------------------------------------------------------------------- */
szBuffer[0] = '\0';
sprintf(szTmp, "%s", " (\"[");
szTmp[4] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
szBuffer[strlen(szBuffer)] = '\0';
/*#3521 */
if(bCaseInsensitive == 1)
sprintf(szTmp, "%s", "]\" ~* /");
else
sprintf(szTmp, "%s", "]\" =~ /");
szTmp[7] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
szBuffer[strlen(szBuffer)] = '\0';
pszValue = psFilterNode->psRightNode->pszValue;
nLength = strlen(pszValue);
iTmp =0;
if (nLength > 0 && pszValue[0] != pszWild[0] &&
pszValue[0] != pszSingle[0] &&
pszValue[0] != pszEscape[0]) {
szTmp[iTmp]= '^';
iTmp++;
}
for (i=0; i<nLength; i++) {
if (pszValue[i] != pszWild[0] &&
pszValue[i] != pszSingle[0] &&
pszValue[i] != pszEscape[0]) {
szTmp[iTmp] = pszValue[i];
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszSingle[0]) {
szTmp[iTmp] = '.';
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszEscape[0]) {
szTmp[iTmp] = '\\';
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszWild[0]) {
/* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */
/* iBuffer+=17; */
szTmp[iTmp++] = '.';
szTmp[iTmp++] = '*';
szTmp[iTmp] = '\0';
}
}
szTmp[iTmp] = '/';
szTmp[++iTmp] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
strlcat(szBuffer, ")", bufferSize);
return msStrdup(szBuffer);
}
Commit Message: security fix (patch by EvenR)
CWE ID: CWE-119 | char *FLTGetIsLikeComparisonExpression(FilterEncodingNode *psFilterNode)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char szTmp[256];
char *pszValue = NULL;
const char *pszWild = NULL;
const char *pszSingle = NULL;
const char *pszEscape = NULL;
int bCaseInsensitive = 0;
int nLength=0, i=0, iTmp=0;
FEPropertyIsLike* propIsLike;
if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
!psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
return NULL;
propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;
pszWild = propIsLike->pszWildCard;
pszSingle = propIsLike->pszSingleChar;
pszEscape = propIsLike->pszEscapeChar;
bCaseInsensitive = propIsLike->bCaseInsensitive;
if (!pszWild || strlen(pszWild) == 0 ||
!pszSingle || strlen(pszSingle) == 0 ||
!pszEscape || strlen(pszEscape) == 0)
return NULL;
/* -------------------------------------------------------------------- */
/* Use operand with regular expressions. */
/* -------------------------------------------------------------------- */
szBuffer[0] = '\0';
sprintf(szTmp, "%s", " (\"[");
szTmp[4] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
szBuffer[strlen(szBuffer)] = '\0';
/*#3521 */
if(bCaseInsensitive == 1)
sprintf(szTmp, "%s", "]\" ~* /");
else
sprintf(szTmp, "%s", "]\" =~ /");
szTmp[7] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
szBuffer[strlen(szBuffer)] = '\0';
pszValue = psFilterNode->psRightNode->pszValue;
nLength = strlen(pszValue);
if( 1 + 2 * nLength + 1 + 1 >= sizeof(szTmp) )
return NULL;
iTmp =0;
if (nLength > 0 && pszValue[0] != pszWild[0] &&
pszValue[0] != pszSingle[0] &&
pszValue[0] != pszEscape[0]) {
szTmp[iTmp]= '^';
iTmp++;
}
for (i=0; i<nLength; i++) {
if (pszValue[i] != pszWild[0] &&
pszValue[i] != pszSingle[0] &&
pszValue[i] != pszEscape[0]) {
szTmp[iTmp] = pszValue[i];
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszSingle[0]) {
szTmp[iTmp] = '.';
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszEscape[0]) {
szTmp[iTmp] = '\\';
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszWild[0]) {
/* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */
/* iBuffer+=17; */
szTmp[iTmp++] = '.';
szTmp[iTmp++] = '*';
szTmp[iTmp] = '\0';
}
}
szTmp[iTmp] = '/';
szTmp[++iTmp] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
strlcat(szBuffer, ")", bufferSize);
return msStrdup(szBuffer);
}
| 168,399 |
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_encrypt)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_string_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_encrypt)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_string_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC);
}
| 167,106 |
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 ip_options_get_from_user(struct net *net, struct ip_options **optp,
unsigned char __user *data, int optlen)
{
struct ip_options *opt = ip_options_get_alloc(optlen);
if (!opt)
return -ENOMEM;
if (optlen && copy_from_user(opt->__data, data, optlen)) {
kfree(opt);
return -EFAULT;
}
return ip_options_get_finish(net, optp, opt, optlen);
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | int ip_options_get_from_user(struct net *net, struct ip_options **optp,
int ip_options_get_from_user(struct net *net, struct ip_options_rcu **optp,
unsigned char __user *data, int optlen)
{
struct ip_options_rcu *opt = ip_options_get_alloc(optlen);
if (!opt)
return -ENOMEM;
if (optlen && copy_from_user(opt->opt.__data, data, optlen)) {
kfree(opt);
return -EFAULT;
}
return ip_options_get_finish(net, optp, opt, optlen);
}
| 165,561 |
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: MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((MemoryInfo *) NULL);
memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
sizeof(*memory_info)));
if (memory_info == (MemoryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
extent=count*quantum;
memory_info->length=extent;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,extent) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,extent);
if (memory_info->blob != NULL)
{
memory_info->type=AlignedVirtualMemory;
return(memory_info);
}
}
RelinquishMagickResource(MemoryResource,extent);
if (AcquireMagickResource(MapResource,extent) != MagickFalse)
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,extent);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
return(memory_info);
}
if (AcquireMagickResource(DiskResource,extent) != MagickFalse)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
If the MapResource request failed, there is no point in trying
file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
MagickOffsetType
offset;
offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET);
if ((offset == (MagickOffsetType) (extent-1)) &&
(write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,extent);
if (memory_info->blob != NULL)
{
(void) close(file);
memory_info->type=MapVirtualMemory;
return(memory_info);
}
}
/*
File-backed memory mapping failed, delete the temporary file.
*/
(void) close(file);
(void) RelinquishUniqueFileResource(memory_info->filename);
*memory_info->filename='\0';
}
}
RelinquishMagickResource(DiskResource,extent);
}
RelinquishMagickResource(MapResource,extent);
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(extent);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119 | MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
extent;
if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
return((MemoryInfo *) NULL);
memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
sizeof(*memory_info)));
if (memory_info == (MemoryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
extent=count*quantum;
memory_info->length=extent;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,extent) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,extent);
if (memory_info->blob != NULL)
{
memory_info->type=AlignedVirtualMemory;
return(memory_info);
}
}
RelinquishMagickResource(MemoryResource,extent);
if (AcquireMagickResource(MapResource,extent) != MagickFalse)
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,extent);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
return(memory_info);
}
if (AcquireMagickResource(DiskResource,extent) != MagickFalse)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
If the MapResource request failed, there is no point in trying
file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
MagickOffsetType
offset;
offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET);
if ((offset == (MagickOffsetType) (extent-1)) &&
(write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,extent);
if (memory_info->blob != NULL)
{
(void) close(file);
memory_info->type=MapVirtualMemory;
return(memory_info);
}
}
/*
File-backed memory mapping failed, delete the temporary file.
*/
(void) close(file);
(void) RelinquishUniqueFileResource(memory_info->filename);
*memory_info->filename='\0';
}
}
RelinquishMagickResource(DiskResource,extent);
}
RelinquishMagickResource(MapResource,extent);
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(extent);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
| 168,544 |
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 FrameworkListener::init(const char *socketName UNUSED, bool withSeq) {
mCommands = new FrameworkCommandCollection();
errorRate = 0;
mCommandCount = 0;
mWithSeq = withSeq;
}
Commit Message: Fix vold vulnerability in FrameworkListener
Modify FrameworkListener to ignore commands that exceed the maximum
buffer length and send an error message.
Bug: 29831647
Change-Id: I9e57d1648d55af2ca0191bb47868e375ecc26950
Signed-off-by: Connor O'Brien <[email protected]>
(cherry picked from commit baa126dc158a40bc83c17c6d428c760e5b93fb1a)
(cherry picked from commit 470484d2a25ad432190a01d1c763b4b36db33c7e)
CWE ID: CWE-264 | void FrameworkListener::init(const char *socketName UNUSED, bool withSeq) {
mCommands = new FrameworkCommandCollection();
errorRate = 0;
mCommandCount = 0;
mWithSeq = withSeq;
mSkipToNextNullByte = false;
}
| 173,390 |
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 jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
{
ulonglong tmp;
if (jas_iccgetuint(in, 8, &tmp))
return -1;
*val = tmp;
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 8, &tmp))
return -1;
*val = tmp;
return 0;
}
| 168,687 |
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: header_put_le_3byte (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3)
{ psf->header [psf->headindex++] = x ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = (x >> 16) ;
} ;
} /* header_put_le_3byte */
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 | header_put_le_3byte (SF_PRIVATE *psf, int x)
{ psf->header.ptr [psf->header.indx++] = x ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
psf->header.ptr [psf->header.indx++] = (x >> 16) ;
} /* header_put_le_3byte */
| 170,054 |
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 StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
Commit Message: stream: support RST getting lost/ignored
In case of a valid RST on a SYN, the state is switched to 'TCP_CLOSED'.
However, the target of the RST may not have received it, or may not
have accepted it. Also, the RST may have been injected, so the supposed
sender may not actually be aware of the RST that was sent in it's name.
In this case the previous behavior was to switch the state to CLOSED and
accept no further TCP updates or stream reassembly.
This patch changes this. It still switches the state to CLOSED, as this
is by far the most likely to be correct. However, it will reconsider
the state if the receiver continues to talk.
To do this on each state change the previous state will be recorded in
TcpSession::pstate. If a non-RST packet is received after a RST, this
TcpSession::pstate is used to try to continue the conversation.
If the (supposed) sender of the RST is also continueing the conversation
as normal, it's highly likely it didn't send the RST. In this case
a stream event is generated.
Ticket: #2501
Reported-By: Kirill Shipulin
CWE ID: | static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
| 169,115 |
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: rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg1,
*prime_arg2;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
size_t tlen1, tlen2, clen, slen;
char *tdots1, *tdots2, *cdots, *sdots;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) ||
krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
tlen1 = strlen(prime_arg1);
trunc_name(&tlen1, &tdots1);
tlen2 = strlen(prime_arg2);
trunc_name(&tlen2, &tdots2);
clen = client_name.length;
trunc_name(&clen, &cdots);
slen = service_name.length;
trunc_name(&slen, &sdots);
ret.code = KADM5_OK;
if (! CHANGEPW_SERVICE(rqstp)) {
if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_DELETE, arg->src, NULL))
ret.code = KADM5_AUTH_DELETE;
/* any restrictions at all on the ADD kills the RENAME */
if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_ADD, arg->dest, &rp) || rp) {
if (ret.code == KADM5_AUTH_DELETE)
ret.code = KADM5_AUTH_INSUFFICIENT;
else
ret.code = KADM5_AUTH_ADD;
}
} else
ret.code = KADM5_AUTH_INSUFFICIENT;
if (ret.code != KADM5_OK) {
/* okay to cast lengths to int because trunc_name limits max value */
krb5_klog_syslog(LOG_NOTICE,
_("Unauthorized request: kadm5_rename_principal, "
"%.*s%s to %.*s%s, "
"client=%.*s%s, service=%.*s%s, addr=%s"),
(int)tlen1, prime_arg1, tdots1,
(int)tlen2, prime_arg2, tdots2,
(int)clen, (char *)client_name.value, cdots,
(int)slen, (char *)service_name.value, sdots,
client_addr(rqstp->rq_xprt));
} else {
ret.code = kadm5_rename_principal((void *)handle, arg->src,
arg->dest);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
/* okay to cast lengths to int because trunc_name limits max value */
krb5_klog_syslog(LOG_NOTICE,
_("Request: kadm5_rename_principal, "
"%.*s%s to %.*s%s, %s, "
"client=%.*s%s, service=%.*s%s, addr=%s"),
(int)tlen1, prime_arg1, tdots1,
(int)tlen2, prime_arg2, tdots2,
errmsg ? errmsg : _("success"),
(int)clen, (char *)client_name.value, cdots,
(int)slen, (char *)service_name.value, sdots,
client_addr(rqstp->rq_xprt));
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg1);
free(prime_arg2);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg1 = NULL, *prime_arg2 = NULL;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
size_t tlen1, tlen2, clen, slen;
char *tdots1, *tdots2, *cdots, *sdots;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) ||
krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
tlen1 = strlen(prime_arg1);
trunc_name(&tlen1, &tdots1);
tlen2 = strlen(prime_arg2);
trunc_name(&tlen2, &tdots2);
clen = client_name.length;
trunc_name(&clen, &cdots);
slen = service_name.length;
trunc_name(&slen, &sdots);
ret.code = KADM5_OK;
if (! CHANGEPW_SERVICE(rqstp)) {
if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_DELETE, arg->src, NULL))
ret.code = KADM5_AUTH_DELETE;
/* any restrictions at all on the ADD kills the RENAME */
if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_ADD, arg->dest, &rp) || rp) {
if (ret.code == KADM5_AUTH_DELETE)
ret.code = KADM5_AUTH_INSUFFICIENT;
else
ret.code = KADM5_AUTH_ADD;
}
} else
ret.code = KADM5_AUTH_INSUFFICIENT;
if (ret.code != KADM5_OK) {
/* okay to cast lengths to int because trunc_name limits max value */
krb5_klog_syslog(LOG_NOTICE,
_("Unauthorized request: kadm5_rename_principal, "
"%.*s%s to %.*s%s, "
"client=%.*s%s, service=%.*s%s, addr=%s"),
(int)tlen1, prime_arg1, tdots1,
(int)tlen2, prime_arg2, tdots2,
(int)clen, (char *)client_name.value, cdots,
(int)slen, (char *)service_name.value, sdots,
client_addr(rqstp->rq_xprt));
} else {
ret.code = kadm5_rename_principal((void *)handle, arg->src,
arg->dest);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
/* okay to cast lengths to int because trunc_name limits max value */
krb5_klog_syslog(LOG_NOTICE,
_("Request: kadm5_rename_principal, "
"%.*s%s to %.*s%s, %s, "
"client=%.*s%s, service=%.*s%s, addr=%s"),
(int)tlen1, prime_arg1, tdots1,
(int)tlen2, prime_arg2, tdots2,
errmsg ? errmsg : _("success"),
(int)clen, (char *)client_name.value, cdots,
(int)slen, (char *)service_name.value, sdots,
client_addr(rqstp->rq_xprt));
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
exit_func:
free(prime_arg1);
free(prime_arg2);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,523 |
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 CoordinatorImpl::GetVmRegionsForHeapProfiler(
const GetVmRegionsForHeapProfilerCallback& callback) {
RequestGlobalMemoryDump(
MemoryDumpType::EXPLICITLY_TRIGGERED,
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {}, callback);
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269 | void CoordinatorImpl::GetVmRegionsForHeapProfiler(
const GetVmRegionsForHeapProfilerCallback& callback) {
// This merely strips out the |dump_guid| argument.
auto adapter = [](const RequestGlobalMemoryDumpCallback& callback,
bool success, uint64_t dump_guid,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(
MemoryDumpType::EXPLICITLY_TRIGGERED,
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {},
false /* add_to_trace */, base::kNullProcessId);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
| 172,914 |
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* _single_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 )
{
len ++;
}
chr = malloc( len + 1 );
len = 0;
while ( in[ len ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
return chr;
}
Commit Message: New Pre Source
CWE ID: CWE-119 | char* _single_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return NULL;
}
while ( in[ len ] != 0 )
{
len ++;
}
chr = malloc( len + 1 );
len = 0;
while ( in[ len ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
return chr;
}
| 169,315 |
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: spnego_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t qop_req, gss_iov_buffer_desc *iov,
int iov_count)
{
return gss_get_mic_iov(minor_status, context_handle, qop_req, iov,
iov_count);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t qop_req, gss_iov_buffer_desc *iov,
int iov_count)
{
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
return gss_get_mic_iov(minor_status, sc->ctx_handle, qop_req, iov,
iov_count);
}
| 166,657 |
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: smtp_log_to_file(smtp_t *smtp)
{
FILE *fp = fopen("/tmp/smtp-alert.log", "a");
time_t now;
struct tm tm;
char time_buf[25];
int time_buf_len;
time(&now);
localtime_r(&now, &tm);
time_buf_len = strftime(time_buf, sizeof time_buf, "%a %b %e %X %Y", &tm);
fprintf(fp, "%s: %s -> %s\n"
"%*sSubject: %s\n"
"%*sBody: %s\n\n",
time_buf, global_data->email_from, smtp->email_to,
time_buf_len - 7, "", smtp->subject,
time_buf_len - 7, "", smtp->body);
fclose(fp);
free_smtp_all(smtp);
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | smtp_log_to_file(smtp_t *smtp)
{
FILE *fp = fopen_safe("/tmp/smtp-alert.log", "a");
time_t now;
struct tm tm;
char time_buf[25];
int time_buf_len;
time(&now);
localtime_r(&now, &tm);
time_buf_len = strftime(time_buf, sizeof time_buf, "%a %b %e %X %Y", &tm);
fprintf(fp, "%s: %s -> %s\n"
"%*sSubject: %s\n"
"%*sBody: %s\n\n",
time_buf, global_data->email_from, smtp->email_to,
time_buf_len - 7, "", smtp->subject,
time_buf_len - 7, "", smtp->body);
fclose(fp);
free_smtp_all(smtp);
}
| 168,987 |
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 PermissionUtil::GetPermissionType(ContentSettingsType type,
PermissionType* out) {
if (type == CONTENT_SETTINGS_TYPE_GEOLOCATION) {
*out = PermissionType::GEOLOCATION;
} else if (type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS) {
*out = PermissionType::NOTIFICATIONS;
} else if (type == CONTENT_SETTINGS_TYPE_PUSH_MESSAGING) {
*out = PermissionType::PUSH_MESSAGING;
} else if (type == CONTENT_SETTINGS_TYPE_MIDI_SYSEX) {
*out = PermissionType::MIDI_SYSEX;
} else if (type == CONTENT_SETTINGS_TYPE_DURABLE_STORAGE) {
*out = PermissionType::DURABLE_STORAGE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) {
*out = PermissionType::VIDEO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC) {
*out = PermissionType::AUDIO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC) {
*out = PermissionType::BACKGROUND_SYNC;
} else if (type == CONTENT_SETTINGS_TYPE_PLUGINS) {
*out = PermissionType::FLASH;
#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
} else if (type == CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER) {
*out = PermissionType::PROTECTED_MEDIA_IDENTIFIER;
#endif
} else {
return false;
}
return true;
}
Commit Message: PermissionUtil::GetPermissionType needs to handle MIDI
After the recent PermissionManager's change, it calls
GetPermissionType even for CONTENT_SETTING_TYPE_MIDI.
BUG=697771
Review-Url: https://codereview.chromium.org/2730693002
Cr-Commit-Position: refs/heads/master@{#454231}
CWE ID: | bool PermissionUtil::GetPermissionType(ContentSettingsType type,
PermissionType* out) {
if (type == CONTENT_SETTINGS_TYPE_GEOLOCATION) {
*out = PermissionType::GEOLOCATION;
} else if (type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS) {
*out = PermissionType::NOTIFICATIONS;
} else if (type == CONTENT_SETTINGS_TYPE_PUSH_MESSAGING) {
*out = PermissionType::PUSH_MESSAGING;
} else if (type == CONTENT_SETTINGS_TYPE_MIDI) {
*out = PermissionType::MIDI;
} else if (type == CONTENT_SETTINGS_TYPE_MIDI_SYSEX) {
*out = PermissionType::MIDI_SYSEX;
} else if (type == CONTENT_SETTINGS_TYPE_DURABLE_STORAGE) {
*out = PermissionType::DURABLE_STORAGE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) {
*out = PermissionType::VIDEO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC) {
*out = PermissionType::AUDIO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC) {
*out = PermissionType::BACKGROUND_SYNC;
} else if (type == CONTENT_SETTINGS_TYPE_PLUGINS) {
*out = PermissionType::FLASH;
#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
} else if (type == CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER) {
*out = PermissionType::PROTECTED_MEDIA_IDENTIFIER;
#endif
} else {
return false;
}
return true;
}
| 172,033 |
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 MakeCacheAndGroup(const GURL& manifest_url,
int64_t group_id,
int64_t cache_id,
bool add_to_database) {
AppCacheEntry default_entry(AppCacheEntry::EXPLICIT,
cache_id + kDefaultEntryIdOffset,
kDefaultEntrySize);
group_ = new AppCacheGroup(storage(), manifest_url, group_id);
cache_ = new AppCache(storage(), cache_id);
cache_->AddEntry(kDefaultEntryUrl, default_entry);
cache_->set_complete(true);
group_->AddCache(cache_.get());
url::Origin manifest_origin(url::Origin::Create(manifest_url));
if (add_to_database) {
AppCacheDatabase::GroupRecord group_record;
group_record.group_id = group_id;
group_record.manifest_url = manifest_url;
group_record.origin = manifest_origin;
EXPECT_TRUE(database()->InsertGroup(&group_record));
AppCacheDatabase::CacheRecord cache_record;
cache_record.cache_id = cache_id;
cache_record.group_id = group_id;
cache_record.online_wildcard = false;
cache_record.update_time = kZeroTime;
cache_record.cache_size = kDefaultEntrySize;
EXPECT_TRUE(database()->InsertCache(&cache_record));
AppCacheDatabase::EntryRecord entry_record;
entry_record.cache_id = cache_id;
entry_record.url = kDefaultEntryUrl;
entry_record.flags = default_entry.types();
entry_record.response_id = default_entry.response_id();
entry_record.response_size = default_entry.response_size();
EXPECT_TRUE(database()->InsertEntry(&entry_record));
storage()->usage_map_[manifest_origin] = default_entry.response_size();
}
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void MakeCacheAndGroup(const GURL& manifest_url,
int64_t group_id,
int64_t cache_id,
bool add_to_database) {
AppCacheEntry default_entry(AppCacheEntry::EXPLICIT,
cache_id + kDefaultEntryIdOffset,
kDefaultEntrySize, kDefaultEntryPadding);
group_ = new AppCacheGroup(storage(), manifest_url, group_id);
cache_ = new AppCache(storage(), cache_id);
cache_->AddEntry(kDefaultEntryUrl, default_entry);
cache_->set_complete(true);
group_->AddCache(cache_.get());
url::Origin manifest_origin(url::Origin::Create(manifest_url));
if (add_to_database) {
AppCacheDatabase::GroupRecord group_record;
group_record.group_id = group_id;
group_record.manifest_url = manifest_url;
group_record.origin = manifest_origin;
EXPECT_TRUE(database()->InsertGroup(&group_record));
AppCacheDatabase::CacheRecord cache_record;
cache_record.cache_id = cache_id;
cache_record.group_id = group_id;
cache_record.online_wildcard = false;
cache_record.update_time = kZeroTime;
cache_record.cache_size = kDefaultEntrySize;
cache_record.padding_size = kDefaultEntryPadding;
EXPECT_TRUE(database()->InsertCache(&cache_record));
AppCacheDatabase::EntryRecord entry_record;
entry_record.cache_id = cache_id;
entry_record.url = kDefaultEntryUrl;
entry_record.flags = default_entry.types();
entry_record.response_id = default_entry.response_id();
entry_record.response_size = default_entry.response_size();
entry_record.padding_size = default_entry.padding_size();
EXPECT_TRUE(database()->InsertEntry(&entry_record));
storage()->usage_map_[manifest_origin] =
default_entry.response_size() + default_entry.padding_size();
}
}
| 172,986 |
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 ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc,
struct pluto_crypto_req *r,
err_t ugh)
{
struct ke_continuation *ke = (struct ke_continuation *)pcrc;
struct msg_digest *md = ke->md;
struct state *const st = md->st;
stf_status e;
DBG(DBG_CONTROLMORE,
DBG_log("ikev2 parent outI1: calculated ke+nonce, sending I1"));
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"%s: Request was disconnected from state",
__FUNCTION__);
if (ke->md)
release_md(ke->md);
return;
}
/* XXX should check out ugh */
passert(ugh == NULL);
passert(cur_state == NULL);
passert(st != NULL);
passert(st->st_suspended_md == ke->md);
set_suspended(st, NULL); /* no longer connected or suspended */
set_cur_state(st);
st->st_calculating = FALSE;
e = ikev2_parent_outI1_tail(pcrc, r);
if (ke->md != NULL) {
complete_v2_state_transition(&ke->md, e);
if (ke->md)
release_md(ke->md);
}
reset_cur_state();
reset_globals();
passert(GLOBALS_ARE_RESET());
}
Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload
CWE ID: CWE-20 | static void ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc,
struct pluto_crypto_req *r,
err_t ugh)
{
struct ke_continuation *ke = (struct ke_continuation *)pcrc;
struct msg_digest *md = ke->md;
struct state *const st = md->st;
stf_status e;
DBG(DBG_CONTROLMORE,
DBG_log("ikev2 parent outI1: calculated ke+nonce, sending I1"));
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"%s: Request was disconnected from state",
__FUNCTION__);
if (ke->md)
release_md(ke->md);
return;
}
/* XXX should check out ugh */
passert(ugh == NULL);
passert(cur_state == NULL);
passert(st != NULL);
passert(st->st_suspended_md == ke->md);
set_suspended(st, NULL); /* no longer connected or suspended */
set_cur_state(st);
st->st_calculating = FALSE;
e = ikev2_parent_outI1_tail(pcrc, r);
if (ke->md != NULL) {
complete_v2_state_transition(&ke->md, e);
if (ke->md)
release_md(ke->md);
}
reset_cur_state();
reset_globals();
}
| 166,473 |
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: ContentEncoding::~ContentEncoding() {
ContentCompression** comp_i = compression_entries_;
ContentCompression** const comp_j = compression_entries_end_;
while (comp_i != comp_j) {
ContentCompression* const comp = *comp_i++;
delete comp;
}
delete [] compression_entries_;
ContentEncryption** enc_i = encryption_entries_;
ContentEncryption** const enc_j = encryption_entries_end_;
while (enc_i != enc_j) {
ContentEncryption* const enc = *enc_i++;
delete enc;
}
delete [] encryption_entries_;
}
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 | ContentEncoding::~ContentEncoding() {
ContentCompression** comp_i = compression_entries_;
ContentCompression** const comp_j = compression_entries_end_;
while (comp_i != comp_j) {
ContentCompression* const comp = *comp_i++;
delete comp;
}
delete[] compression_entries_;
ContentEncryption** enc_i = encryption_entries_;
ContentEncryption** const enc_j = encryption_entries_end_;
while (enc_i != enc_j) {
ContentEncryption* const enc = *enc_i++;
delete enc;
}
delete[] encryption_entries_;
}
| 174,460 |
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 GaiaOAuthClient::Core::FetchUserInfoAndInvokeCallback() {
request_.reset(new UrlFetcher(
GURL(provider_info_.user_info_url), UrlFetcher::GET));
request_->SetRequestContext(request_context_getter_);
request_->SetHeader("Authorization", "Bearer " + access_token_);
request_->Start(
base::Bind(&GaiaOAuthClient::Core::OnUserInfoFetchComplete, this));
}
Commit Message: Remove UrlFetcher from remoting and use the one in net instead.
BUG=133790
TEST=Stop and restart the Me2Me host. It should still work.
Review URL: https://chromiumcodereview.appspot.com/10637008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void GaiaOAuthClient::Core::FetchUserInfoAndInvokeCallback() {
request_.reset(net::URLFetcher::Create(
GURL(provider_info_.user_info_url), net::URLFetcher::GET, this));
request_->SetRequestContext(request_context_getter_);
request_->AddExtraRequestHeader("Authorization: Bearer " + access_token_);
url_fetcher_type_ = URL_FETCHER_GET_USER_INFO;
request_->Start();
}
| 170,806 |
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 jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
{
ulonglong tmp;
if (jas_iccgetuint(in, 2, &tmp))
return -1;
*val = tmp;
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 2, &tmp))
return -1;
*val = tmp;
return 0;
}
| 168,685 |
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 FrameSelection::DocumentAttached(Document* document) {
DCHECK(document);
use_secure_keyboard_entry_when_active_ = false;
selection_editor_->DocumentAttached(document);
SetContext(document);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID: | void FrameSelection::DocumentAttached(Document* document) {
DCHECK(document);
selection_editor_->DocumentAttached(document);
SetContext(document);
}
| 171,853 |
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 sgi_timer_get(struct k_itimer *timr, struct itimerspec *cur_setting)
{
if (timr->it.mmtimer.clock == TIMER_OFF) {
cur_setting->it_interval.tv_nsec = 0;
cur_setting->it_interval.tv_sec = 0;
cur_setting->it_value.tv_nsec = 0;
cur_setting->it_value.tv_sec =0;
return;
}
ns_to_timespec(cur_setting->it_interval, timr->it.mmtimer.incr * sgi_clock_period);
ns_to_timespec(cur_setting->it_value, (timr->it.mmtimer.expires - rtc_time())* sgi_clock_period);
return;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static void sgi_timer_get(struct k_itimer *timr, struct itimerspec *cur_setting)
{
if (timr->it.mmtimer.clock == TIMER_OFF) {
cur_setting->it_interval.tv_nsec = 0;
cur_setting->it_interval.tv_sec = 0;
cur_setting->it_value.tv_nsec = 0;
cur_setting->it_value.tv_sec =0;
return;
}
cur_setting->it_interval = ns_to_timespec(timr->it.mmtimer.incr * sgi_clock_period);
cur_setting->it_value = ns_to_timespec((timr->it.mmtimer.expires - rtc_time()) * sgi_clock_period);
}
| 165,751 |
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: nautilus_file_mark_desktop_file_trusted (GFile *file,
GtkWindow *parent_window,
gboolean interactive,
NautilusOpCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
MarkTrustedJob *job;
job = op_job_new (MarkTrustedJob, parent_window);
job->file = g_object_ref (file);
job->interactive = interactive;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
task = g_task_new (NULL, NULL, mark_trusted_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, mark_trusted_task_thread_func);
g_object_unref (task);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | nautilus_file_mark_desktop_file_trusted (GFile *file,
nautilus_file_mark_desktop_file_executable (GFile *file,
GtkWindow *parent_window,
gboolean interactive,
NautilusOpCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
MarkTrustedJob *job;
job = op_job_new (MarkTrustedJob, parent_window);
job->file = g_object_ref (file);
job->interactive = interactive;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
task = g_task_new (NULL, NULL, mark_desktop_file_executable_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, mark_desktop_file_executable_task_thread_func);
g_object_unref (task);
}
| 167,751 |
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 opj_get_encoding_parameters(const opj_image_t *p_image,
const opj_cp_t *p_cp,
OPJ_UINT32 p_tileno,
OPJ_INT32 * p_tx0,
OPJ_INT32 * p_tx1,
OPJ_INT32 * p_ty0,
OPJ_INT32 * p_ty1,
OPJ_UINT32 * p_dx_min,
OPJ_UINT32 * p_dy_min,
OPJ_UINT32 * p_max_prec,
OPJ_UINT32 * p_max_res)
{
/* loop */
OPJ_UINT32 compno, resno;
/* pointers */
const opj_tcp_t *l_tcp = 00;
const opj_tccp_t * l_tccp = 00;
const opj_image_comp_t * l_img_comp = 00;
/* position in x and y of tile */
OPJ_UINT32 p, q;
/* preconditions */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tileno < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps [p_tileno];
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
/* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */
p = p_tileno % p_cp->tw;
q = p_tileno / p_cp->tw;
/* find extent of tile */
*p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx),
(OPJ_INT32)p_image->x0);
*p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx),
(OPJ_INT32)p_image->x1);
*p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy),
(OPJ_INT32)p_image->y0);
*p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy),
(OPJ_INT32)p_image->y1);
/* max precision is 0 (can only grow) */
*p_max_prec = 0;
*p_max_res = 0;
/* take the largest value for dx_min and dy_min */
*p_dx_min = 0x7fffffff;
*p_dy_min = 0x7fffffff;
for (compno = 0; compno < p_image->numcomps; ++compno) {
/* arithmetic variables to calculate */
OPJ_UINT32 l_level_no;
OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
OPJ_INT32 l_px0, l_py0, l_px1, py1;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_pw, l_ph;
OPJ_UINT32 l_product;
OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);
if (l_tccp->numresolutions > *p_max_res) {
*p_max_res = l_tccp->numresolutions;
}
/* use custom size for precincts */
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
/* precinct width and height */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno));
l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno));
/* take the minimum size for dx for each comp and resolution */
*p_dx_min = opj_uint_min(*p_dx_min, l_dx);
*p_dy_min = opj_uint_min(*p_dy_min, l_dy);
/* various calculations of extents */
l_level_no = l_tccp->numresolutions - 1 - resno;
l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);
l_product = l_pw * l_ph;
/* update precision */
if (l_product > *p_max_prec) {
*p_max_prec = l_product;
}
}
++l_img_comp;
++l_tccp;
}
}
Commit Message: [OPENJP2] change the way to compute *p_tx0, *p_tx1, *p_ty0, *p_ty1 in function
opj_get_encoding_parameters
Signed-off-by: Young_X <[email protected]>
CWE ID: CWE-190 | static void opj_get_encoding_parameters(const opj_image_t *p_image,
const opj_cp_t *p_cp,
OPJ_UINT32 p_tileno,
OPJ_INT32 * p_tx0,
OPJ_INT32 * p_tx1,
OPJ_INT32 * p_ty0,
OPJ_INT32 * p_ty1,
OPJ_UINT32 * p_dx_min,
OPJ_UINT32 * p_dy_min,
OPJ_UINT32 * p_max_prec,
OPJ_UINT32 * p_max_res)
{
/* loop */
OPJ_UINT32 compno, resno;
/* pointers */
const opj_tcp_t *l_tcp = 00;
const opj_tccp_t * l_tccp = 00;
const opj_image_comp_t * l_img_comp = 00;
/* position in x and y of tile */
OPJ_UINT32 p, q;
/* non-corrected (in regard to image offset) tile offset */
OPJ_UINT32 l_tx0, l_ty0;
/* preconditions */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tileno < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps [p_tileno];
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
/* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */
p = p_tileno % p_cp->tw;
q = p_tileno / p_cp->tw;
/* find extent of tile */
l_tx0 = p_cp->tx0 + p *
p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */
*p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0);
*p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1);
l_ty0 = p_cp->ty0 + q *
p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */
*p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0);
*p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1);
/* max precision is 0 (can only grow) */
*p_max_prec = 0;
*p_max_res = 0;
/* take the largest value for dx_min and dy_min */
*p_dx_min = 0x7fffffff;
*p_dy_min = 0x7fffffff;
for (compno = 0; compno < p_image->numcomps; ++compno) {
/* arithmetic variables to calculate */
OPJ_UINT32 l_level_no;
OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
OPJ_INT32 l_px0, l_py0, l_px1, py1;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_pw, l_ph;
OPJ_UINT32 l_product;
OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);
if (l_tccp->numresolutions > *p_max_res) {
*p_max_res = l_tccp->numresolutions;
}
/* use custom size for precincts */
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
/* precinct width and height */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno));
l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno));
/* take the minimum size for dx for each comp and resolution */
*p_dx_min = opj_uint_min(*p_dx_min, l_dx);
*p_dy_min = opj_uint_min(*p_dy_min, l_dy);
/* various calculations of extents */
l_level_no = l_tccp->numresolutions - 1 - resno;
l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);
l_product = l_pw * l_ph;
/* update precision */
if (l_product > *p_max_prec) {
*p_max_prec = l_product;
}
}
++l_img_comp;
++l_tccp;
}
}
| 169,766 |
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: init_global_keywords(bool global_active)
{
/* global definitions mapping */
install_keyword_root("linkbeat_use_polling", use_polling_handler, global_active);
#if HAVE_DECL_CLONE_NEWNET
install_keyword_root("net_namespace", &net_namespace_handler, global_active);
install_keyword_root("namespace_with_ipsets", &namespace_ipsets_handler, global_active);
#endif
install_keyword_root("use_pid_dir", &use_pid_dir_handler, global_active);
install_keyword_root("instance", &instance_handler, global_active);
install_keyword_root("child_wait_time", &child_wait_handler, global_active);
install_keyword_root("global_defs", NULL, global_active);
install_keyword("router_id", &routerid_handler);
install_keyword("notification_email_from", &emailfrom_handler);
install_keyword("smtp_server", &smtpserver_handler);
install_keyword("smtp_helo_name", &smtphelo_handler);
install_keyword("smtp_connect_timeout", &smtpto_handler);
install_keyword("notification_email", &email_handler);
install_keyword("smtp_alert", &smtp_alert_handler);
#ifdef _WITH_VRRP_
install_keyword("smtp_alert_vrrp", &smtp_alert_vrrp_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("smtp_alert_checker", &smtp_alert_checker_handler);
#endif
#ifdef _WITH_VRRP_
install_keyword("dynamic_interfaces", &dynamic_interfaces_handler);
install_keyword("no_email_faults", &no_email_faults_handler);
install_keyword("default_interface", &default_interface_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_timeouts", &lvs_timeouts);
install_keyword("lvs_flush", &lvs_flush_handler);
#ifdef _WITH_VRRP_
install_keyword("lvs_sync_daemon", &lvs_syncd_handler);
#endif
#endif
#ifdef _WITH_VRRP_
install_keyword("vrrp_mcast_group4", &vrrp_mcast_group4_handler);
install_keyword("vrrp_mcast_group6", &vrrp_mcast_group6_handler);
install_keyword("vrrp_garp_master_delay", &vrrp_garp_delay_handler);
install_keyword("vrrp_garp_master_repeat", &vrrp_garp_rep_handler);
install_keyword("vrrp_garp_master_refresh", &vrrp_garp_refresh_handler);
install_keyword("vrrp_garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler);
install_keyword("vrrp_garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler);
install_keyword("vrrp_garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler);
install_keyword("vrrp_garp_interval", &vrrp_garp_interval_handler);
install_keyword("vrrp_gna_interval", &vrrp_gna_interval_handler);
install_keyword("vrrp_lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler);
install_keyword("vrrp_higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler);
install_keyword("vrrp_version", &vrrp_version_handler);
install_keyword("vrrp_iptables", &vrrp_iptables_handler);
#ifdef _HAVE_LIBIPSET_
install_keyword("vrrp_ipsets", &vrrp_ipsets_handler);
#endif
install_keyword("vrrp_check_unicast_src", &vrrp_check_unicast_src_handler);
install_keyword("vrrp_skip_check_adv_addr", &vrrp_check_adv_addr_handler);
install_keyword("vrrp_strict", &vrrp_strict_handler);
install_keyword("vrrp_priority", &vrrp_prio_handler);
install_keyword("vrrp_no_swap", &vrrp_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("vrrp_rt_priority", &vrrp_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("vrrp_rlimit_rtime", &vrrp_rt_rlimit_handler);
#endif
#endif
#endif
install_keyword("notify_fifo", &global_notify_fifo);
install_keyword("notify_fifo_script", &global_notify_fifo_script);
#ifdef _WITH_VRRP_
install_keyword("vrrp_notify_fifo", &vrrp_notify_fifo);
install_keyword("vrrp_notify_fifo_script", &vrrp_notify_fifo_script);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_notify_fifo", &lvs_notify_fifo);
install_keyword("lvs_notify_fifo_script", &lvs_notify_fifo_script);
install_keyword("checker_priority", &checker_prio_handler);
install_keyword("checker_no_swap", &checker_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("checker_rt_priority", &checker_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("checker_rlimit_rtime", &checker_rt_rlimit_handler);
#endif
#endif
#endif
#ifdef _WITH_BFD_
install_keyword("bfd_priority", &bfd_prio_handler);
install_keyword("bfd_no_swap", &bfd_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("bfd_rt_priority", &bfd_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("bfd_rlimit_rtime", &bfd_rt_rlimit_handler);
#endif
#endif
#endif
#ifdef _WITH_SNMP_
install_keyword("snmp_socket", &snmp_socket_handler);
install_keyword("enable_traps", &trap_handler);
#ifdef _WITH_SNMP_VRRP_
install_keyword("enable_snmp_vrrp", &snmp_vrrp_handler);
install_keyword("enable_snmp_keepalived", &snmp_vrrp_handler); /* Deprecated v2.0.0 */
#endif
#ifdef _WITH_SNMP_RFC_
install_keyword("enable_snmp_rfc", &snmp_rfc_handler);
#endif
#ifdef _WITH_SNMP_RFCV2_
install_keyword("enable_snmp_rfcv2", &snmp_rfcv2_handler);
#endif
#ifdef _WITH_SNMP_RFCV3_
install_keyword("enable_snmp_rfcv3", &snmp_rfcv3_handler);
#endif
#ifdef _WITH_SNMP_CHECKER_
install_keyword("enable_snmp_checker", &snmp_checker_handler);
#endif
#endif
#ifdef _WITH_DBUS_
install_keyword("enable_dbus", &enable_dbus_handler);
install_keyword("dbus_service_name", &dbus_service_name_handler);
#endif
install_keyword("script_user", &script_user_handler);
install_keyword("enable_script_security", &script_security_handler);
#ifdef _WITH_VRRP_
install_keyword("vrrp_netlink_cmd_rcv_bufs", &vrrp_netlink_cmd_rcv_bufs_handler);
install_keyword("vrrp_netlink_cmd_rcv_bufs_force", &vrrp_netlink_cmd_rcv_bufs_force_handler);
install_keyword("vrrp_netlink_monitor_rcv_bufs", &vrrp_netlink_monitor_rcv_bufs_handler);
install_keyword("vrrp_netlink_monitor_rcv_bufs_force", &vrrp_netlink_monitor_rcv_bufs_force_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_netlink_cmd_rcv_bufs", &lvs_netlink_cmd_rcv_bufs_handler);
install_keyword("lvs_netlink_cmd_rcv_bufs_force", &lvs_netlink_cmd_rcv_bufs_force_handler);
install_keyword("lvs_netlink_monitor_rcv_bufs", &lvs_netlink_monitor_rcv_bufs_handler);
install_keyword("lvs_netlink_monitor_rcv_bufs_force", &lvs_netlink_monitor_rcv_bufs_force_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("rs_init_notifies", &rs_init_notifies_handler);
install_keyword("no_checker_emails", &no_checker_emails_handler);
#endif
#ifdef _WITH_VRRP_
install_keyword("vrrp_rx_bufs_policy", &vrrp_rx_bufs_policy_handler);
install_keyword("vrrp_rx_bufs_multiplier", &vrrp_rx_bufs_multiplier_handler);
#endif
}
Commit Message: Add command line and configuration option to set umask
Issue #1048 identified that files created by keepalived are created
with mode 0666. This commit changes the default to 0644, and also
allows the umask to be specified in the configuration or as a command
line option.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-200 | init_global_keywords(bool global_active)
{
/* global definitions mapping */
install_keyword_root("linkbeat_use_polling", use_polling_handler, global_active);
#if HAVE_DECL_CLONE_NEWNET
install_keyword_root("net_namespace", &net_namespace_handler, global_active);
install_keyword_root("namespace_with_ipsets", &namespace_ipsets_handler, global_active);
#endif
install_keyword_root("use_pid_dir", &use_pid_dir_handler, global_active);
install_keyword_root("instance", &instance_handler, global_active);
install_keyword_root("child_wait_time", &child_wait_handler, global_active);
install_keyword_root("global_defs", NULL, global_active);
install_keyword("router_id", &routerid_handler);
install_keyword("notification_email_from", &emailfrom_handler);
install_keyword("smtp_server", &smtpserver_handler);
install_keyword("smtp_helo_name", &smtphelo_handler);
install_keyword("smtp_connect_timeout", &smtpto_handler);
install_keyword("notification_email", &email_handler);
install_keyword("smtp_alert", &smtp_alert_handler);
#ifdef _WITH_VRRP_
install_keyword("smtp_alert_vrrp", &smtp_alert_vrrp_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("smtp_alert_checker", &smtp_alert_checker_handler);
#endif
#ifdef _WITH_VRRP_
install_keyword("dynamic_interfaces", &dynamic_interfaces_handler);
install_keyword("no_email_faults", &no_email_faults_handler);
install_keyword("default_interface", &default_interface_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_timeouts", &lvs_timeouts);
install_keyword("lvs_flush", &lvs_flush_handler);
#ifdef _WITH_VRRP_
install_keyword("lvs_sync_daemon", &lvs_syncd_handler);
#endif
#endif
#ifdef _WITH_VRRP_
install_keyword("vrrp_mcast_group4", &vrrp_mcast_group4_handler);
install_keyword("vrrp_mcast_group6", &vrrp_mcast_group6_handler);
install_keyword("vrrp_garp_master_delay", &vrrp_garp_delay_handler);
install_keyword("vrrp_garp_master_repeat", &vrrp_garp_rep_handler);
install_keyword("vrrp_garp_master_refresh", &vrrp_garp_refresh_handler);
install_keyword("vrrp_garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler);
install_keyword("vrrp_garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler);
install_keyword("vrrp_garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler);
install_keyword("vrrp_garp_interval", &vrrp_garp_interval_handler);
install_keyword("vrrp_gna_interval", &vrrp_gna_interval_handler);
install_keyword("vrrp_lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler);
install_keyword("vrrp_higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler);
install_keyword("vrrp_version", &vrrp_version_handler);
install_keyword("vrrp_iptables", &vrrp_iptables_handler);
#ifdef _HAVE_LIBIPSET_
install_keyword("vrrp_ipsets", &vrrp_ipsets_handler);
#endif
install_keyword("vrrp_check_unicast_src", &vrrp_check_unicast_src_handler);
install_keyword("vrrp_skip_check_adv_addr", &vrrp_check_adv_addr_handler);
install_keyword("vrrp_strict", &vrrp_strict_handler);
install_keyword("vrrp_priority", &vrrp_prio_handler);
install_keyword("vrrp_no_swap", &vrrp_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("vrrp_rt_priority", &vrrp_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("vrrp_rlimit_rtime", &vrrp_rt_rlimit_handler);
#endif
#endif
#endif
install_keyword("notify_fifo", &global_notify_fifo);
install_keyword("notify_fifo_script", &global_notify_fifo_script);
#ifdef _WITH_VRRP_
install_keyword("vrrp_notify_fifo", &vrrp_notify_fifo);
install_keyword("vrrp_notify_fifo_script", &vrrp_notify_fifo_script);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_notify_fifo", &lvs_notify_fifo);
install_keyword("lvs_notify_fifo_script", &lvs_notify_fifo_script);
install_keyword("checker_priority", &checker_prio_handler);
install_keyword("checker_no_swap", &checker_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("checker_rt_priority", &checker_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("checker_rlimit_rtime", &checker_rt_rlimit_handler);
#endif
#endif
#endif
#ifdef _WITH_BFD_
install_keyword("bfd_priority", &bfd_prio_handler);
install_keyword("bfd_no_swap", &bfd_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("bfd_rt_priority", &bfd_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("bfd_rlimit_rtime", &bfd_rt_rlimit_handler);
#endif
#endif
#endif
#ifdef _WITH_SNMP_
install_keyword("snmp_socket", &snmp_socket_handler);
install_keyword("enable_traps", &trap_handler);
#ifdef _WITH_SNMP_VRRP_
install_keyword("enable_snmp_vrrp", &snmp_vrrp_handler);
install_keyword("enable_snmp_keepalived", &snmp_vrrp_handler); /* Deprecated v2.0.0 */
#endif
#ifdef _WITH_SNMP_RFC_
install_keyword("enable_snmp_rfc", &snmp_rfc_handler);
#endif
#ifdef _WITH_SNMP_RFCV2_
install_keyword("enable_snmp_rfcv2", &snmp_rfcv2_handler);
#endif
#ifdef _WITH_SNMP_RFCV3_
install_keyword("enable_snmp_rfcv3", &snmp_rfcv3_handler);
#endif
#ifdef _WITH_SNMP_CHECKER_
install_keyword("enable_snmp_checker", &snmp_checker_handler);
#endif
#endif
#ifdef _WITH_DBUS_
install_keyword("enable_dbus", &enable_dbus_handler);
install_keyword("dbus_service_name", &dbus_service_name_handler);
#endif
install_keyword("script_user", &script_user_handler);
install_keyword("enable_script_security", &script_security_handler);
#ifdef _WITH_VRRP_
install_keyword("vrrp_netlink_cmd_rcv_bufs", &vrrp_netlink_cmd_rcv_bufs_handler);
install_keyword("vrrp_netlink_cmd_rcv_bufs_force", &vrrp_netlink_cmd_rcv_bufs_force_handler);
install_keyword("vrrp_netlink_monitor_rcv_bufs", &vrrp_netlink_monitor_rcv_bufs_handler);
install_keyword("vrrp_netlink_monitor_rcv_bufs_force", &vrrp_netlink_monitor_rcv_bufs_force_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_netlink_cmd_rcv_bufs", &lvs_netlink_cmd_rcv_bufs_handler);
install_keyword("lvs_netlink_cmd_rcv_bufs_force", &lvs_netlink_cmd_rcv_bufs_force_handler);
install_keyword("lvs_netlink_monitor_rcv_bufs", &lvs_netlink_monitor_rcv_bufs_handler);
install_keyword("lvs_netlink_monitor_rcv_bufs_force", &lvs_netlink_monitor_rcv_bufs_force_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("rs_init_notifies", &rs_init_notifies_handler);
install_keyword("no_checker_emails", &no_checker_emails_handler);
#endif
#ifdef _WITH_VRRP_
install_keyword("vrrp_rx_bufs_policy", &vrrp_rx_bufs_policy_handler);
install_keyword("vrrp_rx_bufs_multiplier", &vrrp_rx_bufs_multiplier_handler);
#endif
install_keyword("umask", &umask_handler);
}
| 168,981 |
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 ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) {
visitor->Trace(factory_);
visitor->Trace(resolver_);
visitor->Trace(options_);
}
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616342}
CWE ID: CWE-416 | void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) {
ContextLifecycleObserver::Trace(visitor);
visitor->Trace(factory_);
visitor->Trace(resolver_);
visitor->Trace(options_);
}
| 173,071 |
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 CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
int len;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
imapc->mailbox = curl_easy_unescape(data, path, 0, &len);
if(!imapc->mailbox)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
Commit Message: URL sanitize: reject URLs containing bad data
Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a
decoded manner now use the new Curl_urldecode() function to reject URLs
with embedded control codes (anything that is or decodes to a byte value
less than 32).
URLs containing such codes could easily otherwise be used to do harm and
allow users to do unintended actions with otherwise innocent tools and
applications. Like for example using a URL like
pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get
a mail and instead this would delete one.
This flaw is considered a security vulnerability: CVE-2012-0036
Security advisory at: http://curl.haxx.se/docs/adv_20120124.html
Reported by: Dan Fandrich
CWE ID: CWE-89 | static CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
return Curl_urldecode(data, path, 0, &imapc->mailbox, NULL, TRUE);
}
| 165,666 |
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: mpls_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
const u_char *p;
uint32_t label_entry;
uint16_t label_stack_depth = 0;
enum mpls_packet_type pt = PT_UNKNOWN;
p = bp;
ND_PRINT((ndo, "MPLS"));
do {
ND_TCHECK2(*p, sizeof(label_entry));
if (length < sizeof(label_entry)) {
ND_PRINT((ndo, "[|MPLS], length %u", length));
return;
}
label_entry = EXTRACT_32BITS(p);
ND_PRINT((ndo, "%s(label %u",
(label_stack_depth && ndo->ndo_vflag) ? "\n\t" : " ",
MPLS_LABEL(label_entry)));
label_stack_depth++;
if (ndo->ndo_vflag &&
MPLS_LABEL(label_entry) < sizeof(mpls_labelname) / sizeof(mpls_labelname[0]))
ND_PRINT((ndo, " (%s)", mpls_labelname[MPLS_LABEL(label_entry)]));
ND_PRINT((ndo, ", exp %u", MPLS_EXP(label_entry)));
if (MPLS_STACK(label_entry))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u)", MPLS_TTL(label_entry)));
p += sizeof(label_entry);
length -= sizeof(label_entry);
} while (!MPLS_STACK(label_entry));
/*
* Try to figure out the packet type.
*/
switch (MPLS_LABEL(label_entry)) {
case 0: /* IPv4 explicit NULL label */
case 3: /* IPv4 implicit NULL label */
pt = PT_IPV4;
break;
case 2: /* IPv6 explicit NULL label */
pt = PT_IPV6;
break;
default:
/*
* Generally there's no indication of protocol in MPLS label
* encoding.
*
* However, draft-hsmit-isis-aal5mux-00.txt describes a
* technique for encapsulating IS-IS and IP traffic on the
* same ATM virtual circuit; you look at the first payload
* byte to determine the network layer protocol, based on
* the fact that
*
* 1) the first byte of an IP header is 0x45-0x4f
* for IPv4 and 0x60-0x6f for IPv6;
*
* 2) the first byte of an OSI CLNP packet is 0x81,
* the first byte of an OSI ES-IS packet is 0x82,
* and the first byte of an OSI IS-IS packet is
* 0x83;
*
* so the network layer protocol can be inferred from the
* first byte of the packet, if the protocol is one of the
* ones listed above.
*
* Cisco sends control-plane traffic MPLS-encapsulated in
* this fashion.
*/
ND_TCHECK(*p);
if (length < 1) {
/* nothing to print */
return;
}
switch(*p) {
case 0x45:
case 0x46:
case 0x47:
case 0x48:
case 0x49:
case 0x4a:
case 0x4b:
case 0x4c:
case 0x4d:
case 0x4e:
case 0x4f:
pt = PT_IPV4;
break;
case 0x60:
case 0x61:
case 0x62:
case 0x63:
case 0x64:
case 0x65:
case 0x66:
case 0x67:
case 0x68:
case 0x69:
case 0x6a:
case 0x6b:
case 0x6c:
case 0x6d:
case 0x6e:
case 0x6f:
pt = PT_IPV6;
break;
case 0x81:
case 0x82:
case 0x83:
pt = PT_OSI;
break;
default:
/* ok bail out - we did not figure out what it is*/
break;
}
}
/*
* Print the payload.
*/
if (pt == PT_UNKNOWN) {
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, length);
return;
}
ND_PRINT((ndo, ndo->ndo_vflag ? "\n\t" : " "));
switch (pt) {
case PT_IPV4:
ip_print(ndo, p, length);
break;
case PT_IPV6:
ip6_print(ndo, p, length);
break;
case PT_OSI:
isoclns_print(ndo, p, length, length);
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|MPLS]"));
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | mpls_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
const u_char *p;
uint32_t label_entry;
uint16_t label_stack_depth = 0;
enum mpls_packet_type pt = PT_UNKNOWN;
p = bp;
ND_PRINT((ndo, "MPLS"));
do {
ND_TCHECK2(*p, sizeof(label_entry));
if (length < sizeof(label_entry)) {
ND_PRINT((ndo, "[|MPLS], length %u", length));
return;
}
label_entry = EXTRACT_32BITS(p);
ND_PRINT((ndo, "%s(label %u",
(label_stack_depth && ndo->ndo_vflag) ? "\n\t" : " ",
MPLS_LABEL(label_entry)));
label_stack_depth++;
if (ndo->ndo_vflag &&
MPLS_LABEL(label_entry) < sizeof(mpls_labelname) / sizeof(mpls_labelname[0]))
ND_PRINT((ndo, " (%s)", mpls_labelname[MPLS_LABEL(label_entry)]));
ND_PRINT((ndo, ", exp %u", MPLS_EXP(label_entry)));
if (MPLS_STACK(label_entry))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u)", MPLS_TTL(label_entry)));
p += sizeof(label_entry);
length -= sizeof(label_entry);
} while (!MPLS_STACK(label_entry));
/*
* Try to figure out the packet type.
*/
switch (MPLS_LABEL(label_entry)) {
case 0: /* IPv4 explicit NULL label */
case 3: /* IPv4 implicit NULL label */
pt = PT_IPV4;
break;
case 2: /* IPv6 explicit NULL label */
pt = PT_IPV6;
break;
default:
/*
* Generally there's no indication of protocol in MPLS label
* encoding.
*
* However, draft-hsmit-isis-aal5mux-00.txt describes a
* technique for encapsulating IS-IS and IP traffic on the
* same ATM virtual circuit; you look at the first payload
* byte to determine the network layer protocol, based on
* the fact that
*
* 1) the first byte of an IP header is 0x45-0x4f
* for IPv4 and 0x60-0x6f for IPv6;
*
* 2) the first byte of an OSI CLNP packet is 0x81,
* the first byte of an OSI ES-IS packet is 0x82,
* and the first byte of an OSI IS-IS packet is
* 0x83;
*
* so the network layer protocol can be inferred from the
* first byte of the packet, if the protocol is one of the
* ones listed above.
*
* Cisco sends control-plane traffic MPLS-encapsulated in
* this fashion.
*/
ND_TCHECK(*p);
if (length < 1) {
/* nothing to print */
return;
}
switch(*p) {
case 0x45:
case 0x46:
case 0x47:
case 0x48:
case 0x49:
case 0x4a:
case 0x4b:
case 0x4c:
case 0x4d:
case 0x4e:
case 0x4f:
pt = PT_IPV4;
break;
case 0x60:
case 0x61:
case 0x62:
case 0x63:
case 0x64:
case 0x65:
case 0x66:
case 0x67:
case 0x68:
case 0x69:
case 0x6a:
case 0x6b:
case 0x6c:
case 0x6d:
case 0x6e:
case 0x6f:
pt = PT_IPV6;
break;
case 0x81:
case 0x82:
case 0x83:
pt = PT_OSI;
break;
default:
/* ok bail out - we did not figure out what it is*/
break;
}
}
/*
* Print the payload.
*/
if (pt == PT_UNKNOWN) {
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, length);
return;
}
ND_PRINT((ndo, ndo->ndo_vflag ? "\n\t" : " "));
switch (pt) {
case PT_IPV4:
ip_print(ndo, p, length);
break;
case PT_IPV6:
ip6_print(ndo, p, length);
break;
case PT_OSI:
isoclns_print(ndo, p, length);
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|MPLS]"));
}
| 167,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 EncoderTest::MismatchHook(const vpx_image_t *img1,
const vpx_image_t *img2) {
ASSERT_TRUE(0) << "Encode/Decode mismatch found";
}
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 EncoderTest::MismatchHook(const vpx_image_t *img1,
void EncoderTest::MismatchHook(const vpx_image_t* /*img1*/,
const vpx_image_t* /*img2*/) {
ASSERT_TRUE(0) << "Encode/Decode mismatch found";
}
| 174,539 |
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 PlatformFontSkia::InitDefaultFont() {
if (g_default_font.Get())
return true;
bool success = false;
std::string family = kFallbackFontFamilyName;
int size_pixels = 12;
int style = Font::NORMAL;
Font::Weight weight = Font::Weight::NORMAL;
FontRenderParams params;
const SkiaFontDelegate* delegate = SkiaFontDelegate::instance();
if (delegate) {
delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight,
¶ms);
} else if (default_font_description_) {
#if defined(OS_CHROMEOS)
FontRenderParamsQuery query;
CHECK(FontList::ParseDescription(*default_font_description_,
&query.families, &query.style,
&query.pixel_size, &query.weight))
<< "Failed to parse font description " << *default_font_description_;
params = gfx::GetFontRenderParams(query, &family);
size_pixels = query.pixel_size;
style = query.style;
weight = query.weight;
#else
NOTREACHED();
#endif
}
sk_sp<SkTypeface> typeface =
CreateSkTypeface(style & Font::ITALIC, weight, &family, &success);
if (!success)
return false;
g_default_font.Get() = new PlatformFontSkia(
std::move(typeface), family, size_pixels, style, weight, params);
return true;
}
Commit Message: Take default system font size from PlatformFont
The default font returned by Skia should take the initial size from the
default value kDefaultBaseFontSize specified in PlatformFont.
[email protected], [email protected]
[email protected]
Bug: 944227
Change-Id: I6b230b80c349abbe5968edb3cebdd6e89db4c4a6
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1642738
Reviewed-by: Robert Liao <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Commit-Queue: Etienne Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#666299}
CWE ID: CWE-862 | bool PlatformFontSkia::InitDefaultFont() {
if (g_default_font.Get())
return true;
bool success = false;
std::string family = kFallbackFontFamilyName;
int size_pixels = PlatformFont::kDefaultBaseFontSize;
int style = Font::NORMAL;
Font::Weight weight = Font::Weight::NORMAL;
FontRenderParams params;
const SkiaFontDelegate* delegate = SkiaFontDelegate::instance();
if (delegate) {
delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight,
¶ms);
} else if (default_font_description_) {
#if defined(OS_CHROMEOS)
FontRenderParamsQuery query;
CHECK(FontList::ParseDescription(*default_font_description_,
&query.families, &query.style,
&query.pixel_size, &query.weight))
<< "Failed to parse font description " << *default_font_description_;
params = gfx::GetFontRenderParams(query, &family);
size_pixels = query.pixel_size;
style = query.style;
weight = query.weight;
#else
NOTREACHED();
#endif
}
sk_sp<SkTypeface> typeface =
CreateSkTypeface(style & Font::ITALIC, weight, &family, &success);
if (!success)
return false;
g_default_font.Get() = new PlatformFontSkia(
std::move(typeface), family, size_pixels, style, weight, params);
return true;
}
| 173,209 |
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: PlatformFileForTransit GetFileHandleForProcess(base::PlatformFile handle,
base::ProcessHandle process,
bool close_source_handle) {
IPC::PlatformFileForTransit out_handle;
#if defined(OS_WIN)
DWORD options = DUPLICATE_SAME_ACCESS;
if (close_source_handle)
options |= DUPLICATE_CLOSE_SOURCE;
if (!::DuplicateHandle(::GetCurrentProcess(),
handle,
process,
&out_handle,
0,
FALSE,
options)) {
out_handle = IPC::InvalidPlatformFileForTransit();
}
#elif defined(OS_POSIX)
int fd = close_source_handle ? handle : ::dup(handle);
out_handle = base::FileDescriptor(fd, true);
#else
#error Not implemented.
#endif
return out_handle;
}
Commit Message: GetFileHandleForProcess should check for INVALID_HANDLE_VALUE
BUG=243339
[email protected]
Review URL: https://codereview.chromium.org/16020004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202207 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | PlatformFileForTransit GetFileHandleForProcess(base::PlatformFile handle,
base::ProcessHandle process,
bool close_source_handle) {
IPC::PlatformFileForTransit out_handle;
#if defined(OS_WIN)
DWORD options = DUPLICATE_SAME_ACCESS;
if (close_source_handle)
options |= DUPLICATE_CLOSE_SOURCE;
if (handle == INVALID_HANDLE_VALUE ||
!::DuplicateHandle(::GetCurrentProcess(),
handle,
process,
&out_handle,
0,
FALSE,
options)) {
out_handle = IPC::InvalidPlatformFileForTransit();
}
#elif defined(OS_POSIX)
int fd = close_source_handle ? handle : ::dup(handle);
out_handle = base::FileDescriptor(fd, true);
#else
#error Not implemented.
#endif
return out_handle;
}
| 171,314 |
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_module_is_block_mode)
{
MCRYPT_GET_MODE_DIR_ARGS(modes_dir)
if (mcrypt_module_is_block_mode(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_module_is_block_mode)
{
MCRYPT_GET_MODE_DIR_ARGS(modes_dir)
if (mcrypt_module_is_block_mode(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
| 167,098 |
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: uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return NULL;
uint32_t *MP4buffer = NULL;
if (index < mp4->indexcount && mp4->mediafp)
{
MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]);
if (MP4buffer)
{
LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET);
fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp);
return MP4buffer;
}
}
return NULL;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787 | uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return NULL;
uint32_t *MP4buffer = NULL;
if (index < mp4->indexcount && mp4->mediafp)
{
MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]);
if (MP4buffer)
{
if (mp4->filesize > mp4->metaoffsets[index]+mp4->metasizes[index])
{
LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET);
fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp);
mp4->filepos = mp4->metaoffsets[index] + mp4->metasizes[index];
return MP4buffer;
}
}
}
return NULL;
}
| 169,548 |
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: xfs_acl_from_disk(struct xfs_acl *aclp)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
struct xfs_acl_entry *ace;
int count, i;
count = be32_to_cpu(aclp->acl_cnt);
if (count > XFS_ACL_MAX_ENTRIES)
return ERR_PTR(-EFSCORRUPTED);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
case ACL_GROUP:
acl_e->e_id = be32_to_cpu(ace->ae_id);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
acl_e->e_id = ACL_UNDEFINED_ID;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
Commit Message: xfs: fix acl count validation in xfs_acl_from_disk()
Commit fa8b18ed didn't prevent the integer overflow and possible
memory corruption. "count" can go negative and bypass the check.
Signed-off-by: Xi Wang <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Signed-off-by: Ben Myers <[email protected]>
CWE ID: CWE-189 | xfs_acl_from_disk(struct xfs_acl *aclp)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
struct xfs_acl_entry *ace;
unsigned int count, i;
count = be32_to_cpu(aclp->acl_cnt);
if (count > XFS_ACL_MAX_ENTRIES)
return ERR_PTR(-EFSCORRUPTED);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
case ACL_GROUP:
acl_e->e_id = be32_to_cpu(ace->ae_id);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
acl_e->e_id = ACL_UNDEFINED_ID;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
| 169,888 |
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 OMXNodeInstance::handleMessage(omx_message &msg) {
const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource());
if (msg.type == omx_message::FILL_BUFFER_DONE) {
OMX_BUFFERHEADERTYPE *buffer =
findBufferHeader(msg.u.extended_buffer_data.buffer);
{
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.remove(buffer);
CLOG_BUMPED_BUFFER(
FBD, WITH_STATS(FULL_BUFFER(
msg.u.extended_buffer_data.buffer, buffer, msg.fenceFd)));
unbumpDebugLevel_l(kPortIndexOutput);
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(buffer->pAppPrivate);
if (buffer->nOffset + buffer->nFilledLen < buffer->nOffset
|| buffer->nOffset + buffer->nFilledLen > buffer->nAllocLen) {
CLOG_ERROR(onFillBufferDone, OMX_ErrorBadParameter,
FULL_BUFFER(NULL, buffer, msg.fenceFd));
}
buffer_meta->CopyFromOMX(buffer);
if (bufferSource != NULL) {
bufferSource->codecBufferFilled(buffer);
msg.u.extended_buffer_data.timestamp = buffer->nTimeStamp;
}
} else if (msg.type == omx_message::EMPTY_BUFFER_DONE) {
OMX_BUFFERHEADERTYPE *buffer =
findBufferHeader(msg.u.buffer_data.buffer);
{
Mutex::Autolock _l(mDebugLock);
mInputBuffersWithCodec.remove(buffer);
CLOG_BUMPED_BUFFER(
EBD, WITH_STATS(EMPTY_BUFFER(msg.u.buffer_data.buffer, buffer, msg.fenceFd)));
}
if (bufferSource != NULL) {
bufferSource->codecBufferEmptied(buffer, msg.fenceFd);
return true;
}
}
return false;
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | bool OMXNodeInstance::handleMessage(omx_message &msg) {
const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource());
if (msg.type == omx_message::FILL_BUFFER_DONE) {
OMX_BUFFERHEADERTYPE *buffer =
findBufferHeader(msg.u.extended_buffer_data.buffer, kPortIndexOutput);
if (buffer == NULL) {
return false;
}
{
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.remove(buffer);
CLOG_BUMPED_BUFFER(
FBD, WITH_STATS(FULL_BUFFER(
msg.u.extended_buffer_data.buffer, buffer, msg.fenceFd)));
unbumpDebugLevel_l(kPortIndexOutput);
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(buffer->pAppPrivate);
if (buffer->nOffset + buffer->nFilledLen < buffer->nOffset
|| buffer->nOffset + buffer->nFilledLen > buffer->nAllocLen) {
CLOG_ERROR(onFillBufferDone, OMX_ErrorBadParameter,
FULL_BUFFER(NULL, buffer, msg.fenceFd));
}
buffer_meta->CopyFromOMX(buffer);
if (bufferSource != NULL) {
bufferSource->codecBufferFilled(buffer);
msg.u.extended_buffer_data.timestamp = buffer->nTimeStamp;
}
} else if (msg.type == omx_message::EMPTY_BUFFER_DONE) {
OMX_BUFFERHEADERTYPE *buffer =
findBufferHeader(msg.u.buffer_data.buffer, kPortIndexInput);
if (buffer == NULL) {
return false;
}
{
Mutex::Autolock _l(mDebugLock);
mInputBuffersWithCodec.remove(buffer);
CLOG_BUMPED_BUFFER(
EBD, WITH_STATS(EMPTY_BUFFER(msg.u.buffer_data.buffer, buffer, msg.fenceFd)));
}
if (bufferSource != NULL) {
bufferSource->codecBufferEmptied(buffer, msg.fenceFd);
return true;
}
}
return false;
}
| 173,530 |
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 StopCast() {
CastConfigDelegate* cast_config =
Shell::GetInstance()->system_tray_delegate()->GetCastConfigDelegate();
if (cast_config && cast_config->HasCastExtension()) {
cast_config->GetReceiversAndActivities(
base::Bind(&StopCastCallback, cast_config));
}
}
Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods.
BUG=489445
Review URL: https://codereview.chromium.org/1145833003
Cr-Commit-Position: refs/heads/master@{#330663}
CWE ID: CWE-79 | void StopCast() {
| 171,625 |
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 ff_h264_free_tables(H264Context *h, int free_rbsp)
{
int i;
H264Context *hx;
av_freep(&h->intra4x4_pred_mode);
av_freep(&h->chroma_pred_mode_table);
av_freep(&h->cbp_table);
av_freep(&h->mvd_table[0]);
av_freep(&h->mvd_table[1]);
av_freep(&h->direct_table);
av_freep(&h->non_zero_count);
av_freep(&h->slice_table_base);
h->slice_table = NULL;
av_freep(&h->list_counts);
av_freep(&h->mb2b_xy);
av_freep(&h->mb2br_xy);
av_buffer_pool_uninit(&h->qscale_table_pool);
av_buffer_pool_uninit(&h->mb_type_pool);
av_buffer_pool_uninit(&h->motion_val_pool);
av_buffer_pool_uninit(&h->ref_index_pool);
if (free_rbsp && h->DPB) {
for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
ff_h264_unref_picture(h, &h->DPB[i]);
av_freep(&h->DPB);
} else if (h->DPB) {
for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
h->DPB[i].needs_realloc = 1;
}
h->cur_pic_ptr = NULL;
for (i = 0; i < H264_MAX_THREADS; i++) {
hx = h->thread_context[i];
if (!hx)
continue;
av_freep(&hx->top_borders[1]);
av_freep(&hx->top_borders[0]);
av_freep(&hx->bipred_scratchpad);
av_freep(&hx->edge_emu_buffer);
av_freep(&hx->dc_val_base);
av_freep(&hx->er.mb_index2xy);
av_freep(&hx->er.error_status_table);
av_freep(&hx->er.er_temp_buffer);
av_freep(&hx->er.mbintra_table);
av_freep(&hx->er.mbskip_table);
if (free_rbsp) {
av_freep(&hx->rbsp_buffer[1]);
av_freep(&hx->rbsp_buffer[0]);
hx->rbsp_buffer_size[0] = 0;
hx->rbsp_buffer_size[1] = 0;
}
if (i)
av_freep(&h->thread_context[i]);
}
}
Commit Message: avcodec/h264: Clear delayed_pic on deallocation
Fixes use of freed memory
Fixes: case5_av_frame_copy_props.mp4
Found-by: Michal Zalewski <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: | void ff_h264_free_tables(H264Context *h, int free_rbsp)
{
int i;
H264Context *hx;
av_freep(&h->intra4x4_pred_mode);
av_freep(&h->chroma_pred_mode_table);
av_freep(&h->cbp_table);
av_freep(&h->mvd_table[0]);
av_freep(&h->mvd_table[1]);
av_freep(&h->direct_table);
av_freep(&h->non_zero_count);
av_freep(&h->slice_table_base);
h->slice_table = NULL;
av_freep(&h->list_counts);
av_freep(&h->mb2b_xy);
av_freep(&h->mb2br_xy);
av_buffer_pool_uninit(&h->qscale_table_pool);
av_buffer_pool_uninit(&h->mb_type_pool);
av_buffer_pool_uninit(&h->motion_val_pool);
av_buffer_pool_uninit(&h->ref_index_pool);
if (free_rbsp && h->DPB) {
for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
ff_h264_unref_picture(h, &h->DPB[i]);
memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
av_freep(&h->DPB);
} else if (h->DPB) {
for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
h->DPB[i].needs_realloc = 1;
}
h->cur_pic_ptr = NULL;
for (i = 0; i < H264_MAX_THREADS; i++) {
hx = h->thread_context[i];
if (!hx)
continue;
av_freep(&hx->top_borders[1]);
av_freep(&hx->top_borders[0]);
av_freep(&hx->bipred_scratchpad);
av_freep(&hx->edge_emu_buffer);
av_freep(&hx->dc_val_base);
av_freep(&hx->er.mb_index2xy);
av_freep(&hx->er.error_status_table);
av_freep(&hx->er.er_temp_buffer);
av_freep(&hx->er.mbintra_table);
av_freep(&hx->er.mbskip_table);
if (free_rbsp) {
av_freep(&hx->rbsp_buffer[1]);
av_freep(&hx->rbsp_buffer[0]);
hx->rbsp_buffer_size[0] = 0;
hx->rbsp_buffer_size[1] = 0;
}
if (i)
av_freep(&h->thread_context[i]);
}
}
| 166,624 |
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_write_destroy(png_structp png_ptr)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* Save jump buffer */
#endif
png_error_ptr error_fn;
png_error_ptr warning_fn;
png_voidp error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_free_ptr free_fn;
#endif
png_debug(1, "in png_write_destroy");
/* Free any memory zlib uses */
deflateEnd(&png_ptr->zstream);
/* Free our memory. png_free checks NULL for us. */
png_free(png_ptr, png_ptr->zbuf);
png_free(png_ptr, png_ptr->row_buf);
#ifdef PNG_WRITE_FILTER_SUPPORTED
png_free(png_ptr, png_ptr->prev_row);
png_free(png_ptr, png_ptr->sub_row);
png_free(png_ptr, png_ptr->up_row);
png_free(png_ptr, png_ptr->avg_row);
png_free(png_ptr, png_ptr->paeth_row);
#endif
#ifdef PNG_TIME_RFC1123_SUPPORTED
png_free(png_ptr, png_ptr->time_buffer);
#endif
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
png_free(png_ptr, png_ptr->prev_filters);
png_free(png_ptr, png_ptr->filter_weights);
png_free(png_ptr, png_ptr->inv_filter_weights);
png_free(png_ptr, png_ptr->filter_costs);
png_free(png_ptr, png_ptr->inv_filter_costs);
#endif
#ifdef PNG_SETJMP_SUPPORTED
/* Reset structure */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
error_fn = png_ptr->error_fn;
warning_fn = png_ptr->warning_fn;
error_ptr = png_ptr->error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
free_fn = png_ptr->free_fn;
#endif
png_memset(png_ptr, 0, png_sizeof(png_struct));
png_ptr->error_fn = error_fn;
png_ptr->warning_fn = warning_fn;
png_ptr->error_ptr = error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_ptr->free_fn = free_fn;
#endif
#ifdef PNG_SETJMP_SUPPORTED
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_write_destroy(png_structp png_ptr)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* Save jump buffer */
#endif
png_error_ptr error_fn;
png_error_ptr warning_fn;
png_voidp error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_free_ptr free_fn;
#endif
png_debug(1, "in png_write_destroy");
/* Free any memory zlib uses */
deflateEnd(&png_ptr->zstream);
/* Free our memory. png_free checks NULL for us. */
png_free(png_ptr, png_ptr->zbuf);
png_free(png_ptr, png_ptr->row_buf);
#ifdef PNG_WRITE_FILTER_SUPPORTED
png_free(png_ptr, png_ptr->prev_row);
png_free(png_ptr, png_ptr->sub_row);
png_free(png_ptr, png_ptr->up_row);
png_free(png_ptr, png_ptr->avg_row);
png_free(png_ptr, png_ptr->paeth_row);
#endif
#ifdef PNG_TIME_RFC1123_SUPPORTED
png_free(png_ptr, png_ptr->time_buffer);
#endif
#ifdef PNG_SETJMP_SUPPORTED
/* Reset structure */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
error_fn = png_ptr->error_fn;
warning_fn = png_ptr->warning_fn;
error_ptr = png_ptr->error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
free_fn = png_ptr->free_fn;
#endif
png_memset(png_ptr, 0, png_sizeof(png_struct));
png_ptr->error_fn = error_fn;
png_ptr->warning_fn = warning_fn;
png_ptr->error_ptr = error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_ptr->free_fn = free_fn;
#endif
#ifdef PNG_SETJMP_SUPPORTED
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
}
| 172,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: grub_fshelp_read_file (grub_disk_t disk, grub_fshelp_node_t node,
void (*read_hook) (grub_disk_addr_t sector,
unsigned offset,
unsigned length,
void *closure),
void *closure, int flags,
grub_off_t pos, grub_size_t len, char *buf,
grub_disk_addr_t (*get_block) (grub_fshelp_node_t node,
grub_disk_addr_t block),
grub_off_t filesize, int log2blocksize)
{
grub_disk_addr_t i, blockcnt;
int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS);
/* Adjust LEN so it we can't read past the end of the file. */
if (pos + len > filesize)
len = filesize - pos;
blockcnt = ((len + pos) + blocksize - 1) >>
(log2blocksize + GRUB_DISK_SECTOR_BITS);
for (i = pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS); i < blockcnt; i++)
{
grub_disk_addr_t blknr;
int blockoff = pos & (blocksize - 1);
int blockend = blocksize;
int skipfirst = 0;
blknr = get_block (node, i);
if (grub_errno)
return -1;
blknr = blknr << log2blocksize;
/* Last block. */
if (i == blockcnt - 1)
{
blockend = (len + pos) & (blocksize - 1);
/* The last portion is exactly blocksize. */
if (! blockend)
blockend = blocksize;
}
/* First block. */
if (i == (pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS)))
{
skipfirst = blockoff;
blockend -= skipfirst;
}
/* If the block number is 0 this block is not stored on disk but
is zero filled instead. */
if (blknr)
{
disk->read_hook = read_hook;
disk->closure = closure;
grub_hack_lastoff = blknr * 512;
grub_disk_read_ex (disk, blknr, skipfirst, blockend, buf, flags);
disk->read_hook = 0;
if (grub_errno)
return -1;
}
else if (buf)
grub_memset (buf, 0, blockend);
if (buf)
buf += blocksize - skipfirst;
}
return len;
}
Commit Message: Fix ext2 buffer overflow in r2_sbu_grub_memmove
CWE ID: CWE-787 | grub_fshelp_read_file (grub_disk_t disk, grub_fshelp_node_t node,
void (*read_hook) (grub_disk_addr_t sector,
unsigned offset,
unsigned length,
void *closure),
void *closure, int flags,
grub_off_t pos, grub_size_t len, char *buf,
grub_disk_addr_t (*get_block) (grub_fshelp_node_t node,
grub_disk_addr_t block),
grub_off_t filesize, int log2blocksize)
{
grub_disk_addr_t i, blockcnt;
int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS);
/* Adjust LEN so it we can't read past the end of the file. */
if (pos + len > filesize)
len = filesize - pos;
if (len < 1 || len == 0xffffffff) {
return -1;
}
blockcnt = ((len + pos) + blocksize - 1) >>
(log2blocksize + GRUB_DISK_SECTOR_BITS);
for (i = pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS); i < blockcnt; i++)
{
grub_disk_addr_t blknr;
int blockoff = pos & (blocksize - 1);
int blockend = blocksize;
int skipfirst = 0;
blknr = get_block (node, i);
if (grub_errno)
return -1;
blknr = blknr << log2blocksize;
/* Last block. */
if (i == blockcnt - 1)
{
blockend = (len + pos) & (blocksize - 1);
/* The last portion is exactly blocksize. */
if (! blockend)
blockend = blocksize;
}
/* First block. */
if (i == (pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS)))
{
skipfirst = blockoff;
blockend -= skipfirst;
}
/* If the block number is 0 this block is not stored on disk but
is zero filled instead. */
if (blknr)
{
disk->read_hook = read_hook;
disk->closure = closure;
grub_hack_lastoff = blknr * 512;
grub_disk_read_ex (disk, blknr, skipfirst, blockend, buf, flags);
disk->read_hook = 0;
if (grub_errno)
return -1;
}
else if (buf)
grub_memset (buf, 0, blockend);
if (buf)
buf += blocksize - skipfirst;
}
return len;
}
| 168,084 |
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(locale_compose)
{
smart_str loc_name_s = {0};
smart_str *loc_name = &loc_name_s;
zval* arr = NULL;
HashTable* hash_arr = NULL;
int result = 0;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a",
&arr) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
hash_arr = HASH_OF( arr );
if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 )
RETURN_FALSE;
/* Check for grandfathered first */
result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG);
if( result == SUCCESS){
RETURN_SMART_STR(loc_name);
}
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Not grandfathered */
result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG);
if( result == LOC_NOT_FOUND ){
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC );
smart_str_free(loc_name);
RETURN_FALSE;
}
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Extlang */
result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Script */
result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Region */
result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Variant */
result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Private */
result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
RETURN_SMART_STR(loc_name);
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION(locale_compose)
{
smart_str loc_name_s = {0};
smart_str *loc_name = &loc_name_s;
zval* arr = NULL;
HashTable* hash_arr = NULL;
int result = 0;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a",
&arr) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
hash_arr = HASH_OF( arr );
if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 )
RETURN_FALSE;
/* Check for grandfathered first */
result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG);
if( result == SUCCESS){
RETURN_SMART_STR(loc_name);
}
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Not grandfathered */
result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG);
if( result == LOC_NOT_FOUND ){
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC );
smart_str_free(loc_name);
RETURN_FALSE;
}
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Extlang */
result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Script */
result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Region */
result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Variant */
result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Private */
result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
RETURN_SMART_STR(loc_name);
}
| 167,191 |
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 iov_iter_pipe(struct iov_iter *i, int direction,
struct pipe_inode_info *pipe,
size_t count)
{
BUG_ON(direction != ITER_PIPE);
i->type = direction;
i->pipe = pipe;
i->idx = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
i->iov_offset = 0;
i->count = count;
}
Commit Message: fix a fencepost error in pipe_advance()
The logics in pipe_advance() used to release all buffers past the new
position failed in cases when the number of buffers to release was equal
to pipe->buffers. If that happened, none of them had been released,
leaving pipe full. Worse, it was trivial to trigger and we end up with
pipe full of uninitialized pages. IOW, it's an infoleak.
Cc: [email protected] # v4.9
Reported-by: "Alan J. Wylie" <[email protected]>
Tested-by: "Alan J. Wylie" <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-200 | void iov_iter_pipe(struct iov_iter *i, int direction,
struct pipe_inode_info *pipe,
size_t count)
{
BUG_ON(direction != ITER_PIPE);
WARN_ON(pipe->nrbufs == pipe->buffers);
i->type = direction;
i->pipe = pipe;
i->idx = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
i->iov_offset = 0;
i->count = count;
}
| 168,387 |
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: UrlData::UrlData(const GURL& url, CORSMode cors_mode, UrlIndex* url_index)
: url_(url),
have_data_origin_(false),
cors_mode_(cors_mode),
url_index_(url_index),
length_(kPositionNotSpecified),
range_supported_(false),
cacheable_(false),
has_opaque_data_(false),
last_used_(),
multibuffer_(this, url_index_->block_shift_) {}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | UrlData::UrlData(const GURL& url, CORSMode cors_mode, UrlIndex* url_index)
: url_(url),
have_data_origin_(false),
cors_mode_(cors_mode),
url_index_(url_index),
length_(kPositionNotSpecified),
range_supported_(false),
cacheable_(false),
last_used_(),
multibuffer_(this, url_index_->block_shift_) {}
| 172,628 |
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: WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
const gfx::Rect& bounds) {
return WindowOpenDisposition::NEW_POPUP;
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20 | WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
| 173,207 |
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_arpt_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_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_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_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!arp_checkentry(&e->arp))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e, e->target_offset,
e->next_offset);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, 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 out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_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;
release_target:
module_put(t->u.kernel.target->me);
out:
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 <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-264 | check_compat_entry_size_and_hooks(struct compat_arpt_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_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_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_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!arp_checkentry(&e->arp))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e, e->elems, e->target_offset,
e->next_offset);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, 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 out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_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;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
| 167,215 |
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: const char *string_of_NPPVariable(int variable)
{
const char *str;
switch (variable) {
#define _(VAL) case VAL: str = #VAL; break;
_(NPPVpluginNameString);
_(NPPVpluginDescriptionString);
_(NPPVpluginWindowBool);
_(NPPVpluginTransparentBool);
_(NPPVjavaClass);
_(NPPVpluginWindowSize);
_(NPPVpluginTimerInterval);
_(NPPVpluginScriptableInstance);
_(NPPVpluginScriptableIID);
_(NPPVjavascriptPushCallerBool);
_(NPPVpluginKeepLibraryInMemory);
_(NPPVpluginNeedsXEmbed);
_(NPPVpluginScriptableNPObject);
_(NPPVformValue);
#undef _
default:
switch (variable & 0xff) {
#define _(VAL, VAR) case VAL: str = #VAR; break
_(10, NPPVpluginScriptableInstance);
#undef _
default:
str = "<unknown variable>";
break;
}
break;
}
return str;
}
Commit Message: Support all the new variables added
CWE ID: CWE-264 | const char *string_of_NPPVariable(int variable)
{
const char *str;
switch (variable) {
#define _(VAL) case VAL: str = #VAL; break;
_(NPPVpluginNameString);
_(NPPVpluginDescriptionString);
_(NPPVpluginWindowBool);
_(NPPVpluginTransparentBool);
_(NPPVjavaClass);
_(NPPVpluginWindowSize);
_(NPPVpluginTimerInterval);
_(NPPVpluginScriptableInstance);
_(NPPVpluginScriptableIID);
_(NPPVjavascriptPushCallerBool);
_(NPPVpluginKeepLibraryInMemory);
_(NPPVpluginNeedsXEmbed);
_(NPPVpluginScriptableNPObject);
_(NPPVformValue);
_(NPPVpluginUrlRequestsDisplayedBool);
_(NPPVpluginWantsAllNetworkStreams);
_(NPPVpluginNativeAccessibleAtkPlugId);
_(NPPVpluginCancelSrcStream);
_(NPPVSupportsAdvancedKeyHandling);
#undef _
default:
switch (variable & 0xff) {
#define _(VAL, VAR) case VAL: str = #VAR; break
_(10, NPPVpluginScriptableInstance);
#undef _
default:
str = "<unknown variable>";
break;
}
break;
}
return str;
}
| 165,866 |
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: ext2_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext2_xattr_put_super(struct super_block *sb)
| 169,982 |
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 BrowserWindowGtk::TabDetachedAt(TabContents* contents, int index) {
if (index == browser_->active_index()) {
infobar_container_->ChangeTabContents(NULL);
UpdateDevToolsForContents(NULL);
}
contents_container_->DetachTab(contents);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void BrowserWindowGtk::TabDetachedAt(TabContents* contents, int index) {
void BrowserWindowGtk::TabDetachedAt(WebContents* contents, int index) {
if (index == browser_->active_index()) {
infobar_container_->ChangeTabContents(NULL);
UpdateDevToolsForContents(NULL);
}
contents_container_->DetachTab(contents);
}
| 171,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: flx_set_palette_vector (FlxColorSpaceConverter * flxpal, guint start, guint num,
guchar * newpal, gint scale)
{
guint grab;
g_return_if_fail (flxpal != NULL);
g_return_if_fail (start < 0x100);
grab = ((start + num) > 0x100 ? 0x100 - start : num);
if (scale) {
gint i = 0;
start *= 3;
while (grab) {
flxpal->palvec[start++] = newpal[i++] << scale;
flxpal->palvec[start++] = newpal[i++] << scale;
flxpal->palvec[start++] = newpal[i++] << scale;
grab--;
}
} else {
memcpy (&flxpal->palvec[start * 3], newpal, grab * 3);
}
}
Commit Message:
CWE ID: CWE-125 | flx_set_palette_vector (FlxColorSpaceConverter * flxpal, guint start, guint num,
guchar * newpal, gint scale)
{
guint grab;
g_return_if_fail (flxpal != NULL);
g_return_if_fail (start < 0x100);
grab = ((start + num) > 0x100 ? 0x100 - start : num);
if (scale) {
gint i = 0;
start *= 3;
while (grab) {
flxpal->palvec[start++] = newpal[i++] << scale;
flxpal->palvec[start++] = newpal[i++] << scale;
flxpal->palvec[start++] = newpal[i++] << scale;
grab--;
}
} else {
memcpy (&flxpal->palvec[start * 3], newpal, grab * 3);
}
}
| 165,245 |
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 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,
__be16 sport, __be16 dport)
{
__u32 seq;
__u32 hash[4];
struct keydata *keyptr = get_keyptr();
/*
* Pick a unique starting offset for each TCP connection endpoints
* (saddr, daddr, sport, dport).
* Note that the words are placed into the starting vector, which is
* then mixed with a partial MD4 over random data.
*/
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
hash[3] = keyptr->secret[11];
seq = half_md4_transform(hash, keyptr->secret) & HASH_MASK;
seq += keyptr->count;
/*
* As close as possible to RFC 793, which
* suggests using a 250 kHz clock.
* Further reading shows this assumes 2 Mb/s networks.
* For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
* For 10 Gb/s Ethernet, a 1 GHz clock should be ok, but
* we also need to limit the resolution so that the u32 seq
* overlaps less than one time per MSL (2 minutes).
* Choosing a clock of 64 ns period is OK. (period of 274 s)
*/
seq += ktime_to_ns(ktime_get_real()) >> 6;
return seq;
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | __u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,
| 165,768 |
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: TEE_Result syscall_asymm_verify(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *data, size_t data_len,
const void *sig, size_t sig_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
size_t hash_size;
int salt_len = 0;
TEE_Attribute *params = NULL;
uint32_t hash_algo;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_VERIFY)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)data, data_len);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)sig, sig_len);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * num_params);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
case TEE_MAIN_ALGO_RSA:
if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) {
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
if (data_len != hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params,
hash_size);
}
res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len,
data, data_len, sig,
sig_len);
break;
case TEE_MAIN_ALGO_DSA:
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
/*
* Depending on the DSA algorithm (NIST), the digital signature
* output size may be truncated to the size of a key pair
* (Q prime size). Q prime size must be less or equal than the
* hash output length of the hash algorithm involved.
*/
if (data_len > hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
res = crypto_acipher_dsa_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
case TEE_MAIN_ALGO_ECDSA:
res = crypto_acipher_ecc_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
default:
res = TEE_ERROR_NOT_SUPPORTED;
}
out:
free(params);
return res;
}
Commit Message: svc: check for allocation overflow in crypto calls part 2
Without checking for overflow there is a risk of allocating a buffer
with size smaller than anticipated and as a consequence of that it might
lead to a heap based overflow with attacker controlled data written
outside the boundaries of the buffer.
Fixes: OP-TEE-2018-0011: "Integer overflow in crypto system calls (x2)"
Signed-off-by: Joakim Bech <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Reviewed-by: Jens Wiklander <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]>
CWE ID: CWE-119 | TEE_Result syscall_asymm_verify(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *data, size_t data_len,
const void *sig, size_t sig_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
size_t hash_size;
int salt_len = 0;
TEE_Attribute *params = NULL;
uint32_t hash_algo;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_VERIFY)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)data, data_len);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)sig, sig_len);
if (res != TEE_SUCCESS)
return res;
size_t alloc_size = 0;
if (MUL_OVERFLOW(sizeof(TEE_Attribute), num_params, &alloc_size))
return TEE_ERROR_OVERFLOW;
params = malloc(alloc_size);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
case TEE_MAIN_ALGO_RSA:
if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) {
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
if (data_len != hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params,
hash_size);
}
res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len,
data, data_len, sig,
sig_len);
break;
case TEE_MAIN_ALGO_DSA:
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
/*
* Depending on the DSA algorithm (NIST), the digital signature
* output size may be truncated to the size of a key pair
* (Q prime size). Q prime size must be less or equal than the
* hash output length of the hash algorithm involved.
*/
if (data_len > hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
res = crypto_acipher_dsa_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
case TEE_MAIN_ALGO_ECDSA:
res = crypto_acipher_ecc_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
default:
res = TEE_ERROR_NOT_SUPPORTED;
}
out:
free(params);
return res;
}
| 169,466 |
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 set_sda(int state)
{
qrio_set_opendrain_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1, state);
}
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 | void set_sda(int state)
| 169,633 |
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 ReturnFrameBuffer(vpx_codec_frame_buffer_t *fb) {
EXPECT_TRUE(fb != NULL);
ExternalFrameBuffer *const ext_fb =
reinterpret_cast<ExternalFrameBuffer*>(fb->priv);
EXPECT_TRUE(ext_fb != NULL);
EXPECT_EQ(1, ext_fb->in_use);
ext_fb->in_use = 0;
return 0;
}
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 ReturnFrameBuffer(vpx_codec_frame_buffer_t *fb) {
if (fb == NULL) {
EXPECT_TRUE(fb != NULL);
return -1;
}
ExternalFrameBuffer *const ext_fb =
reinterpret_cast<ExternalFrameBuffer*>(fb->priv);
if (ext_fb == NULL) {
EXPECT_TRUE(ext_fb != NULL);
return -1;
}
EXPECT_EQ(1, ext_fb->in_use);
ext_fb->in_use = 0;
return 0;
}
| 174,545 |
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 xen_netbk_get_extras(struct xenvif *vif,
struct xen_netif_extra_info *extras,
int work_to_do)
{
struct xen_netif_extra_info extra;
RING_IDX cons = vif->tx.req_cons;
do {
if (unlikely(work_to_do-- <= 0)) {
netdev_dbg(vif->dev, "Missing extra info\n");
return -EBADR;
}
memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons),
sizeof(extra));
if (unlikely(!extra.type ||
extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
vif->tx.req_cons = ++cons;
netdev_dbg(vif->dev,
"Invalid extra type: %d\n", extra.type);
return -EINVAL;
}
memcpy(&extras[extra.type - 1], &extra, sizeof(extra));
vif->tx.req_cons = ++cons;
} while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE);
return work_to_do;
}
Commit Message: xen/netback: shutdown the ring if it contains garbage.
A buggy or malicious frontend should not be able to confuse netback.
If we spot anything which is not as it should be then shutdown the
device and don't try to continue with the ring in a potentially
hostile state. Well behaved and non-hostile frontends will not be
penalised.
As well as making the existing checks for such errors fatal also add a
new check that ensures that there isn't an insane number of requests
on the ring (i.e. more than would fit in the ring). If the ring
contains garbage then previously is was possible to loop over this
insane number, getting an error each time and therefore not generating
any more pending requests and therefore not exiting the loop in
xen_netbk_tx_build_gops for an externded period.
Also turn various netdev_dbg calls which no precipitate a fatal error
into netdev_err, they are rate limited because the device is shutdown
afterwards.
This fixes at least one known DoS/softlockup of the backend domain.
Signed-off-by: Ian Campbell <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int xen_netbk_get_extras(struct xenvif *vif,
struct xen_netif_extra_info *extras,
int work_to_do)
{
struct xen_netif_extra_info extra;
RING_IDX cons = vif->tx.req_cons;
do {
if (unlikely(work_to_do-- <= 0)) {
netdev_err(vif->dev, "Missing extra info\n");
netbk_fatal_tx_err(vif);
return -EBADR;
}
memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons),
sizeof(extra));
if (unlikely(!extra.type ||
extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
vif->tx.req_cons = ++cons;
netdev_err(vif->dev,
"Invalid extra type: %d\n", extra.type);
netbk_fatal_tx_err(vif);
return -EINVAL;
}
memcpy(&extras[extra.type - 1], &extra, sizeof(extra));
vif->tx.req_cons = ++cons;
} while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE);
return work_to_do;
}
| 166,174 |
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: AppResult::AppResult(Profile* profile,
const std::string& app_id,
AppListControllerDelegate* controller,
bool is_recommendation)
: profile_(profile),
app_id_(app_id),
controller_(controller),
extension_registry_(NULL) {
set_id(extensions::Extension::GetBaseURLFromExtensionId(app_id_).spec());
if (app_list::switches::IsExperimentalAppListEnabled())
set_display_type(is_recommendation ? DISPLAY_RECOMMENDATION : DISPLAY_TILE);
const extensions::Extension* extension =
extensions::ExtensionSystem::Get(profile_)->extension_service()
->GetInstalledExtension(app_id_);
DCHECK(extension);
is_platform_app_ = extension->is_platform_app();
icon_.reset(
new extensions::IconImage(profile_,
extension,
extensions::IconsInfo::GetIcons(extension),
GetPreferredIconDimension(),
extensions::util::GetDefaultAppIcon(),
this));
UpdateIcon();
StartObservingExtensionRegistry();
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID: | AppResult::AppResult(Profile* profile,
const std::string& app_id,
AppListControllerDelegate* controller,
bool is_recommendation)
: profile_(profile),
app_id_(app_id),
controller_(controller),
extension_registry_(NULL) {
set_id(extensions::Extension::GetBaseURLFromExtensionId(app_id_).spec());
if (app_list::switches::IsExperimentalAppListEnabled())
set_display_type(is_recommendation ? DISPLAY_RECOMMENDATION : DISPLAY_TILE);
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(profile_)->GetInstalledExtension(
app_id_);
DCHECK(extension);
is_platform_app_ = extension->is_platform_app();
icon_.reset(
new extensions::IconImage(profile_,
extension,
extensions::IconsInfo::GetIcons(extension),
GetPreferredIconDimension(),
extensions::util::GetDefaultAppIcon(),
this));
UpdateIcon();
StartObservingExtensionRegistry();
}
| 171,725 |
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: main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
int pid = 0;
for (i = 1; i < argc; i++)
const char *act;
#endif
gid_t gid, gl[65536], egid;
int pid = 0;
for (i = 1; i < argc; i++)
{
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
Commit Message:
CWE ID: CWE-264 | main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
int pid = 0;
for (i = 1; i < argc; i++)
const char *act;
#endif
gid_t gid, gl[65536], egid;
for (i = 1; i < argc; i++)
{
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
| 165,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 int ecdsa_sign_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret, key_tries, sign_tries;
int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
mbedtls_mpi *pk = &k, *pr = r;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
ECDSA_RS_ENTER( sig );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
{
/* redirect to our context */
p_sign_tries = &rs_ctx->sig->sign_tries;
p_key_tries = &rs_ctx->sig->key_tries;
pk = &rs_ctx->sig->k;
pr = &rs_ctx->sig->r;
/* jump to current step */
if( rs_ctx->sig->state == ecdsa_sig_mul )
goto mul;
if( rs_ctx->sig->state == ecdsa_sig_modn )
goto modn;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
*p_sign_tries = 0;
do
{
if( *p_sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
*p_key_tries = 0;
do
{
if( *p_key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_mul;
mul:
#endif
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G,
f_rng, p_rng, ECDSA_RS_ECP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_modn;
modn:
#endif
/*
* Accounting for everything up to the end of the loop
* (step 6, but checking now avoids saving e and t)
*/
ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng, p_rng ) );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
mbedtls_mpi_copy( r, pr );
#endif
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
ECDSA_RS_LEAVE( sig );
return( ret );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted
CWE ID: CWE-200 | static int ecdsa_sign_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
int (*f_rng_blind)(void *, unsigned char *, size_t),
void *p_rng_blind,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret, key_tries, sign_tries;
int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
mbedtls_mpi *pk = &k, *pr = r;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
ECDSA_RS_ENTER( sig );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
{
/* redirect to our context */
p_sign_tries = &rs_ctx->sig->sign_tries;
p_key_tries = &rs_ctx->sig->key_tries;
pk = &rs_ctx->sig->k;
pr = &rs_ctx->sig->r;
/* jump to current step */
if( rs_ctx->sig->state == ecdsa_sig_mul )
goto mul;
if( rs_ctx->sig->state == ecdsa_sig_modn )
goto modn;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
*p_sign_tries = 0;
do
{
if( *p_sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
*p_key_tries = 0;
do
{
if( *p_key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_mul;
mul:
#endif
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G,
f_rng_blind,
p_rng_blind,
ECDSA_RS_ECP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_modn;
modn:
#endif
/*
* Accounting for everything up to the end of the loop
* (step 6, but checking now avoids saving e and t)
*/
ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng_blind,
p_rng_blind ) );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
mbedtls_mpi_copy( r, pr );
#endif
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
ECDSA_RS_LEAVE( sig );
return( ret );
}
| 169,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 int pcd_detect(void)
{
char id[18];
int k, unit;
struct pcd_unit *cd;
printk("%s: %s version %s, major %d, nice %d\n",
name, name, PCD_VERSION, major, nice);
par_drv = pi_register_driver(name);
if (!par_drv) {
pr_err("failed to register %s driver\n", name);
return -1;
}
k = 0;
if (pcd_drive_count == 0) { /* nothing spec'd - so autoprobe for 1 */
cd = pcd;
if (pi_init(cd->pi, 1, -1, -1, -1, -1, -1, pcd_buffer,
PI_PCD, verbose, cd->name)) {
if (!pcd_probe(cd, -1, id) && cd->disk) {
cd->present = 1;
k++;
} else
pi_release(cd->pi);
}
} else {
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
int *conf = *drives[unit];
if (!conf[D_PRT])
continue;
if (!pi_init(cd->pi, 0, conf[D_PRT], conf[D_MOD],
conf[D_UNI], conf[D_PRO], conf[D_DLY],
pcd_buffer, PI_PCD, verbose, cd->name))
continue;
if (!pcd_probe(cd, conf[D_SLV], id) && cd->disk) {
cd->present = 1;
k++;
} else
pi_release(cd->pi);
}
}
if (k)
return 0;
printk("%s: No CD-ROM drive found\n", name);
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
blk_cleanup_queue(cd->disk->queue);
cd->disk->queue = NULL;
blk_mq_free_tag_set(&cd->tag_set);
put_disk(cd->disk);
}
pi_unregister_driver(par_drv);
return -1;
}
Commit Message: paride/pcd: Fix potential NULL pointer dereference and mem leak
Syzkaller report this:
pcd: pcd version 1.07, major 46, nice 0
pcd0: Autoprobe failed
pcd: No CD-ROM drive found
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pcd_init+0x95c/0x1000 [pcd]
Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2
RSP: 0018:ffff8881e84df880 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935
RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8
R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000
R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003
FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1508000
? 0xffffffffc1508000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd
ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace d873691c3cd69f56 ]---
If alloc_disk fails in pcd_init_units, cd->disk will be
NULL, however in pcd_detect and pcd_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-476 | static int pcd_detect(void)
{
char id[18];
int k, unit;
struct pcd_unit *cd;
printk("%s: %s version %s, major %d, nice %d\n",
name, name, PCD_VERSION, major, nice);
par_drv = pi_register_driver(name);
if (!par_drv) {
pr_err("failed to register %s driver\n", name);
return -1;
}
k = 0;
if (pcd_drive_count == 0) { /* nothing spec'd - so autoprobe for 1 */
cd = pcd;
if (pi_init(cd->pi, 1, -1, -1, -1, -1, -1, pcd_buffer,
PI_PCD, verbose, cd->name)) {
if (!pcd_probe(cd, -1, id) && cd->disk) {
cd->present = 1;
k++;
} else
pi_release(cd->pi);
}
} else {
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
int *conf = *drives[unit];
if (!conf[D_PRT])
continue;
if (!pi_init(cd->pi, 0, conf[D_PRT], conf[D_MOD],
conf[D_UNI], conf[D_PRO], conf[D_DLY],
pcd_buffer, PI_PCD, verbose, cd->name))
continue;
if (!pcd_probe(cd, conf[D_SLV], id) && cd->disk) {
cd->present = 1;
k++;
} else
pi_release(cd->pi);
}
}
if (k)
return 0;
printk("%s: No CD-ROM drive found\n", name);
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
if (!cd->disk)
continue;
blk_cleanup_queue(cd->disk->queue);
cd->disk->queue = NULL;
blk_mq_free_tag_set(&cd->tag_set);
put_disk(cd->disk);
}
pi_unregister_driver(par_drv);
return -1;
}
| 169,517 |
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 UrlFetcherDownloader::StartURLFetch(const GURL& url) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (download_dir_.empty()) {
Result result;
result.error = -1;
DownloadMetrics download_metrics;
download_metrics.url = url;
download_metrics.downloader = DownloadMetrics::kUrlFetcher;
download_metrics.error = -1;
download_metrics.downloaded_bytes = -1;
download_metrics.total_bytes = -1;
download_metrics.download_time_ms = 0;
main_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete,
base::Unretained(this), false, result,
download_metrics));
return;
}
const auto file_path = download_dir_.AppendASCII(url.ExtractFileName());
network_fetcher_ = network_fetcher_factory_->Create();
network_fetcher_->DownloadToFile(
url, file_path,
base::BindOnce(&UrlFetcherDownloader::OnResponseStarted,
base::Unretained(this)),
base::BindRepeating(&UrlFetcherDownloader::OnDownloadProgress,
base::Unretained(this)),
base::BindOnce(&UrlFetcherDownloader::OnNetworkFetcherComplete,
base::Unretained(this), file_path));
download_start_time_ = base::TimeTicks::Now();
}
Commit Message: Fix error handling in the request sender and url fetcher downloader.
That means handling the network errors by primarily looking at net_error.
Bug: 1028369
Change-Id: I8181bced25f8b56144ea336a03883d0dceea5108
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1935428
Reviewed-by: Joshua Pawlicki <[email protected]>
Commit-Queue: Sorin Jianu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#719199}
CWE ID: CWE-20 | void UrlFetcherDownloader::StartURLFetch(const GURL& url) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (download_dir_.empty()) {
Result result;
result.error = -1;
DownloadMetrics download_metrics;
download_metrics.url = url;
download_metrics.downloader = DownloadMetrics::kUrlFetcher;
download_metrics.error = -1;
download_metrics.downloaded_bytes = -1;
download_metrics.total_bytes = -1;
download_metrics.download_time_ms = 0;
main_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete,
base::Unretained(this), false, result,
download_metrics));
return;
}
file_path_ = download_dir_.AppendASCII(url.ExtractFileName());
network_fetcher_ = network_fetcher_factory_->Create();
network_fetcher_->DownloadToFile(
url, file_path_,
base::BindOnce(&UrlFetcherDownloader::OnResponseStarted,
base::Unretained(this)),
base::BindRepeating(&UrlFetcherDownloader::OnDownloadProgress,
base::Unretained(this)),
base::BindOnce(&UrlFetcherDownloader::OnNetworkFetcherComplete,
base::Unretained(this)));
download_start_time_ = base::TimeTicks::Now();
}
| 172,366 |
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[])
{
FILE *iplist = NULL;
plist_t root_node = NULL;
char *plist_out = NULL;
uint32_t size = 0;
int read_size = 0;
char *plist_entire = NULL;
struct stat filestats;
options_t *options = parse_arguments(argc, argv);
if (!options)
{
print_usage(argc, argv);
return 0;
}
iplist = fopen(options->in_file, "rb");
if (!iplist) {
free(options);
return 1;
}
stat(options->in_file, &filestats);
plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1));
read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist);
fclose(iplist);
if (memcmp(plist_entire, "bplist00", 8) == 0)
{
plist_from_bin(plist_entire, read_size, &root_node);
plist_to_xml(root_node, &plist_out, &size);
}
else
{
plist_from_xml(plist_entire, read_size, &root_node);
plist_to_bin(root_node, &plist_out, &size);
}
plist_free(root_node);
free(plist_entire);
if (plist_out)
{
if (options->out_file != NULL)
{
FILE *oplist = fopen(options->out_file, "wb");
if (!oplist) {
free(options);
return 1;
}
fwrite(plist_out, size, sizeof(char), oplist);
fclose(oplist);
}
else
fwrite(plist_out, size, sizeof(char), stdout);
free(plist_out);
}
else
printf("ERROR: Failed to convert input file.\n");
free(options);
return 0;
}
Commit Message: plistutil: Prevent OOB heap buffer read by checking input size
As pointed out in #87 plistutil would do a memcmp with a heap buffer
without checking the size. If the size is less than 8 it would read
beyond the bounds of this heap buffer. This commit prevents that.
CWE ID: CWE-125 | int main(int argc, char *argv[])
{
FILE *iplist = NULL;
plist_t root_node = NULL;
char *plist_out = NULL;
uint32_t size = 0;
int read_size = 0;
char *plist_entire = NULL;
struct stat filestats;
options_t *options = parse_arguments(argc, argv);
if (!options)
{
print_usage(argc, argv);
return 0;
}
iplist = fopen(options->in_file, "rb");
if (!iplist) {
free(options);
return 1;
}
stat(options->in_file, &filestats);
if (filestats.st_size < 8) {
printf("ERROR: Input file is too small to contain valid plist data.\n");
return -1;
}
plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1));
read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist);
fclose(iplist);
if (memcmp(plist_entire, "bplist00", 8) == 0)
{
plist_from_bin(plist_entire, read_size, &root_node);
plist_to_xml(root_node, &plist_out, &size);
}
else
{
plist_from_xml(plist_entire, read_size, &root_node);
plist_to_bin(root_node, &plist_out, &size);
}
plist_free(root_node);
free(plist_entire);
if (plist_out)
{
if (options->out_file != NULL)
{
FILE *oplist = fopen(options->out_file, "wb");
if (!oplist) {
free(options);
return 1;
}
fwrite(plist_out, size, sizeof(char), oplist);
fclose(oplist);
}
else
fwrite(plist_out, size, sizeof(char), stdout);
free(plist_out);
}
else
printf("ERROR: Failed to convert input file.\n");
free(options);
return 0;
}
| 168,398 |
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: BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false)
: mMem(mem),
mIsBackup(is_backup),
mPortIndex(portIndex) {
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false)
BufferMeta(
const sp<IMemory> &mem, OMX_U32 portIndex, bool copyToOmx,
bool copyFromOmx, OMX_U8 *backup)
: mMem(mem),
mCopyFromOmx(copyFromOmx),
mCopyToOmx(copyToOmx),
mPortIndex(portIndex),
mBackup(backup) {
}
| 174,124 |
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 RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
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 RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
| 174,522 |
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: SampleTable::SampleTable(const sp<DataSource> &source)
: mDataSource(source),
mChunkOffsetOffset(-1),
mChunkOffsetType(0),
mNumChunkOffsets(0),
mSampleToChunkOffset(-1),
mNumSampleToChunkOffsets(0),
mSampleSizeOffset(-1),
mSampleSizeFieldSize(0),
mDefaultSampleSize(0),
mNumSampleSizes(0),
mTimeToSampleCount(0),
mTimeToSample(),
mSampleTimeEntries(NULL),
mCompositionTimeDeltaEntries(NULL),
mNumCompositionTimeDeltaEntries(0),
mCompositionDeltaLookup(new CompositionDeltaLookup),
mSyncSampleOffset(-1),
mNumSyncSamples(0),
mSyncSamples(NULL),
mLastSyncSampleIndex(0),
mSampleToChunkEntries(NULL) {
mSampleIterator = new SampleIterator(this);
}
Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug
28076789.
Detail: Before the original fix
(Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the
code allowed a time-to-sample table size to be 0. The change
made in that fix disallowed such situation, which in fact should
be allowed. This current patch allows it again while maintaining
the security of the previous fix.
Bug: 28288202
Bug: 28076789
Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295
CWE ID: CWE-20 | SampleTable::SampleTable(const sp<DataSource> &source)
: mDataSource(source),
mChunkOffsetOffset(-1),
mChunkOffsetType(0),
mNumChunkOffsets(0),
mSampleToChunkOffset(-1),
mNumSampleToChunkOffsets(0),
mSampleSizeOffset(-1),
mSampleSizeFieldSize(0),
mDefaultSampleSize(0),
mNumSampleSizes(0),
mHasTimeToSample(false),
mTimeToSampleCount(0),
mTimeToSample(),
mSampleTimeEntries(NULL),
mCompositionTimeDeltaEntries(NULL),
mNumCompositionTimeDeltaEntries(0),
mCompositionDeltaLookup(new CompositionDeltaLookup),
mSyncSampleOffset(-1),
mNumSyncSamples(0),
mSyncSamples(NULL),
mLastSyncSampleIndex(0),
mSampleToChunkEntries(NULL) {
mSampleIterator = new SampleIterator(this);
}
| 173,771 |
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: print_ipcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 6), 4);
ND_PRINT((ndo, ": src %s, dst %s",
ipaddr_string(ndo, p + 2),
ipaddr_string(ndo, p + 6)));
break;
case IPCPOPT_IPCOMP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
compproto = EXTRACT_16BITS(p+2);
ND_PRINT((ndo, ": %s (0x%02x):",
tok2str(ipcpopt_compproto_values, "Unknown", compproto),
compproto));
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case IPCPOPT_IPCOMP_HDRCOMP:
if (len < IPCPOPT_IPCOMP_MINLEN) {
ND_PRINT((ndo, " (length bogus, should be >= %u)",
IPCPOPT_IPCOMP_MINLEN));
return 0;
}
ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN);
ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12)));
/* suboptions present ? */
if (len > IPCPOPT_IPCOMP_MINLEN) {
ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN;
p += IPCPOPT_IPCOMP_MINLEN;
ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen));
while (ipcomp_subopttotallen >= 2) {
ND_TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u",
tok2str(ipcpopt_compproto_subopt_values,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen));
ipcomp_subopttotallen -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ipcp]"));
return 0;
}
Commit Message: CVE-2017-13029/PPP: Fix a bounds check, and clean up other bounds checks.
For configuration protocol options, use ND_TCHECK() and
ND_TCHECK_nBITS() macros, passing them the appropriate pointer argument.
This fixes one case where the ND_TCHECK2() call they replace was not
checking enough bytes.
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), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | print_ipcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 6), 4);
ND_PRINT((ndo, ": src %s, dst %s",
ipaddr_string(ndo, p + 2),
ipaddr_string(ndo, p + 6)));
break;
case IPCPOPT_IPCOMP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK_16BITS(p+2);
compproto = EXTRACT_16BITS(p+2);
ND_PRINT((ndo, ": %s (0x%02x):",
tok2str(ipcpopt_compproto_values, "Unknown", compproto),
compproto));
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case IPCPOPT_IPCOMP_HDRCOMP:
if (len < IPCPOPT_IPCOMP_MINLEN) {
ND_PRINT((ndo, " (length bogus, should be >= %u)",
IPCPOPT_IPCOMP_MINLEN));
return 0;
}
ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN);
ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12)));
/* suboptions present ? */
if (len > IPCPOPT_IPCOMP_MINLEN) {
ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN;
p += IPCPOPT_IPCOMP_MINLEN;
ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen));
while (ipcomp_subopttotallen >= 2) {
ND_TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u",
tok2str(ipcpopt_compproto_subopt_values,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen));
ipcomp_subopttotallen -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ipcp]"));
return 0;
}
| 167,861 |
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: av_cold void ff_mpv_idct_init(MpegEncContext *s)
{
ff_idctdsp_init(&s->idsp, s->avctx);
/* load & permutate scantables
* note: only wmv uses different ones
*/
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
}
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
Commit Message: avcodec/idctdsp: Transmit studio_profile to init instead of using AVCodecContext profile
These 2 fields are not always the same, it is simpler to always use the same field
for detecting studio profile
Fixes: null pointer dereference
Fixes: ffmpeg_crash_3.avi
Found-by: Thuan Pham <[email protected]>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | av_cold void ff_mpv_idct_init(MpegEncContext *s)
{
if (s->codec_id == AV_CODEC_ID_MPEG4)
s->idsp.mpeg4_studio_profile = s->studio_profile;
ff_idctdsp_init(&s->idsp, s->avctx);
/* load & permutate scantables
* note: only wmv uses different ones
*/
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
}
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
| 169,190 |
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: wiki_handle_rest_call(HttpRequest *req,
HttpResponse *res,
char *func)
{
if (func != NULL && *func != '\0')
{
if (!strcmp(func, "page/get"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && (access(page, R_OK) == 0))
{
http_response_printf(res, "%s", file_read(page));
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/set"))
{
char *wikitext = NULL, *page = NULL;
if( ( (wikitext = http_request_param_get(req, "text")) != NULL)
&& ( (page = http_request_param_get(req, "page")) != NULL))
{
file_write(page, wikitext);
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/delete"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && (unlink(page) > 0))
{
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/exists"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && (access(page, R_OK) == 0))
{
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "pages") || !strcmp(func, "search"))
{
WikiPageList **pages = NULL;
int n_pages, i;
char *expr = http_request_param_get(req, "expr");
if (expr == NULL)
expr = http_request_get_query_string(req);
pages = wiki_get_pages(&n_pages, expr);
if (pages)
{
for (i=0; i<n_pages; i++)
{
struct tm *pTm;
char datebuf[64];
pTm = localtime(&pages[i]->mtime);
strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm);
http_response_printf(res, "%s\t%s\n", pages[i]->name, datebuf);
}
http_response_send(res);
return;
}
}
}
http_response_set_status(res, 500, "Error");
http_response_printf(res, "<html><body>Failed</body></html>\n");
http_response_send(res);
return;
}
Commit Message: page_name_is_good function
CWE ID: CWE-22 | wiki_handle_rest_call(HttpRequest *req,
HttpResponse *res,
char *func)
{
if (func != NULL && *func != '\0')
{
if (!strcmp(func, "page/get"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && page_name_is_good(page) && (access(page, R_OK) == 0))
{
http_response_printf(res, "%s", file_read(page));
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/set"))
{
char *wikitext = NULL, *page = NULL;
if( ( (wikitext = http_request_param_get(req, "text")) != NULL)
&& ( (page = http_request_param_get(req, "page")) != NULL))
{
if (page_name_is_good(page))
{
file_write(page, wikitext);
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
}
else if (!strcmp(func, "page/delete"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && page_name_is_good(page) && (unlink(page) > 0))
{
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/exists"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && page_name_is_good(page) && (access(page, R_OK) == 0))
{
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "pages") || !strcmp(func, "search"))
{
WikiPageList **pages = NULL;
int n_pages, i;
char *expr = http_request_param_get(req, "expr");
if (expr == NULL)
expr = http_request_get_query_string(req);
pages = wiki_get_pages(&n_pages, expr);
if (pages)
{
for (i=0; i<n_pages; i++)
{
struct tm *pTm;
char datebuf[64];
pTm = localtime(&pages[i]->mtime);
strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm);
http_response_printf(res, "%s\t%s\n", pages[i]->name, datebuf);
}
http_response_send(res);
return;
}
}
}
http_response_set_status(res, 500, "Error");
http_response_printf(res, "<html><body>Failed</body></html>\n");
http_response_send(res);
return;
}
| 167,595 |
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: SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr,
unsigned long, data)
{
struct task_struct *child;
long ret;
if (request == PTRACE_TRACEME) {
ret = ptrace_traceme();
if (!ret)
arch_ptrace_attach(current);
goto out;
}
child = ptrace_get_task_struct(pid);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
goto out;
}
if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) {
ret = ptrace_attach(child, request, addr, data);
/*
* Some architectures need to do book-keeping after
* a ptrace attach.
*/
if (!ret)
arch_ptrace_attach(child);
goto out_put_task_struct;
}
ret = ptrace_check_attach(child, request == PTRACE_KILL ||
request == PTRACE_INTERRUPT);
if (ret < 0)
goto out_put_task_struct;
ret = arch_ptrace(child, request, addr, data);
out_put_task_struct:
put_task_struct(child);
out:
return ret;
}
Commit Message: ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL
putreg() assumes that the tracee is not running and pt_regs_access() can
safely play with its stack. However a killed tracee can return from
ptrace_stop() to the low-level asm code and do RESTORE_REST, this means
that debugger can actually read/modify the kernel stack until the tracee
does SAVE_REST again.
set_task_blockstep() can race with SIGKILL too and in some sense this
race is even worse, the very fact the tracee can be woken up breaks the
logic.
As Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace()
call, this ensures that nobody can ever wakeup the tracee while the
debugger looks at it. Not only this fixes the mentioned problems, we
can do some cleanups/simplifications in arch_ptrace() paths.
Probably ptrace_unfreeze_traced() needs more callers, for example it
makes sense to make the tracee killable for oom-killer before
access_process_vm().
While at it, add the comment into may_ptrace_stop() to explain why
ptrace_stop() still can't rely on SIGKILL and signal_pending_state().
Reported-by: Salman Qazi <[email protected]>
Reported-by: Suleiman Souhlal <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr,
unsigned long, data)
{
struct task_struct *child;
long ret;
if (request == PTRACE_TRACEME) {
ret = ptrace_traceme();
if (!ret)
arch_ptrace_attach(current);
goto out;
}
child = ptrace_get_task_struct(pid);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
goto out;
}
if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) {
ret = ptrace_attach(child, request, addr, data);
/*
* Some architectures need to do book-keeping after
* a ptrace attach.
*/
if (!ret)
arch_ptrace_attach(child);
goto out_put_task_struct;
}
ret = ptrace_check_attach(child, request == PTRACE_KILL ||
request == PTRACE_INTERRUPT);
if (ret < 0)
goto out_put_task_struct;
ret = arch_ptrace(child, request, addr, data);
if (ret || request != PTRACE_DETACH)
ptrace_unfreeze_traced(child);
out_put_task_struct:
put_task_struct(child);
out:
return ret;
}
| 166,136 |
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: struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj_t* bin, int idx, int *nlib) {
ut64 liboff, linkedit_offset;
ut64 dyld_vmbase;
ut32 addend = 0;
struct r_bin_dyldcache_lib_t *ret = NULL;
struct dyld_cache_image_info* image_infos = NULL;
struct mach_header *mh;
ut8 *data, *cmdptr;
int cmd, libsz = 0;
RBuffer* dbuf;
char *libname;
if (!bin) {
return NULL;
}
if (bin->size < 1) {
eprintf ("Empty file? (%s)\n", bin->file? bin->file: "(null)");
return NULL;
}
if (bin->nlibs < 0 || idx < 0 || idx >= bin->nlibs) {
return NULL;
}
*nlib = bin->nlibs;
ret = R_NEW0 (struct r_bin_dyldcache_lib_t);
if (!ret) {
perror ("malloc (ret)");
return NULL;
}
if (bin->hdr.startaddr > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
if (bin->hdr.startaddr > bin->size || bin->hdr.baseaddroff > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
image_infos = (struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);
dyld_vmbase = *(ut64 *)(bin->b->buf + bin->hdr.baseaddroff);
liboff = image_infos[idx].address - dyld_vmbase;
if (liboff > bin->size) {
eprintf ("Corrupted file\n");
free (ret);
return NULL;
}
ret->offset = liboff;
if (image_infos[idx].pathFileOffset > bin->size) {
eprintf ("corrupted file\n");
free (ret);
return NULL;
}
libname = (char *)(bin->b->buf + image_infos[idx].pathFileOffset);
/* Locate lib hdr in cache */
data = bin->b->buf + liboff;
mh = (struct mach_header *)data;
/* Check it is mach-o */
if (mh->magic != MH_MAGIC && mh->magic != MH_MAGIC_64) {
if (mh->magic == 0xbebafeca) { //FAT binary
eprintf ("FAT Binary\n");
}
eprintf ("Not mach-o\n");
free (ret);
return NULL;
}
/* Write mach-o hdr */
if (!(dbuf = r_buf_new ())) {
eprintf ("new (dbuf)\n");
free (ret);
return NULL;
}
addend = mh->magic == MH_MAGIC? sizeof (struct mach_header) : sizeof (struct mach_header_64);
r_buf_set_bytes (dbuf, data, addend);
cmdptr = data + addend;
/* Write load commands */
for (cmd = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
r_buf_append_bytes (dbuf, (ut8*)lc, lc->cmdsize);
cmdptr += lc->cmdsize;
}
cmdptr = data + addend;
/* Write segments */
for (cmd = linkedit_offset = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
cmdptr += lc->cmdsize;
switch (lc->cmd) {
case LC_SEGMENT:
{
/* Write segment and patch offset */
struct segment_command *seg = (struct segment_command *)lc;
int t = seg->filesize;
if (seg->fileoff + seg->filesize > bin->size || seg->fileoff > bin->size) {
eprintf ("malformed dyldcache\n");
free (ret);
r_buf_free (dbuf);
return NULL;
}
r_buf_append_bytes (dbuf, bin->b->buf+seg->fileoff, t);
r_bin_dyldcache_apply_patch (dbuf, dbuf->length, (ut64)((size_t)&seg->fileoff - (size_t)data));
/* Patch section offsets */
int sect_offset = seg->fileoff - libsz;
libsz = dbuf->length;
if (!strcmp (seg->segname, "__LINKEDIT")) {
linkedit_offset = sect_offset;
}
if (seg->nsects > 0) {
struct section *sects = (struct section *)((ut8 *)seg + sizeof(struct segment_command));
int nsect;
for (nsect = 0; nsect < seg->nsects; nsect++) {
if (sects[nsect].offset > libsz) {
r_bin_dyldcache_apply_patch (dbuf, sects[nsect].offset - sect_offset,
(ut64)((size_t)§s[nsect].offset - (size_t)data));
}
}
}
}
break;
case LC_SYMTAB:
{
struct symtab_command *st = (struct symtab_command *)lc;
NZ_OFFSET (st->symoff);
NZ_OFFSET (st->stroff);
}
break;
case LC_DYSYMTAB:
{
struct dysymtab_command *st = (struct dysymtab_command *)lc;
NZ_OFFSET (st->tocoff);
NZ_OFFSET (st->modtaboff);
NZ_OFFSET (st->extrefsymoff);
NZ_OFFSET (st->indirectsymoff);
NZ_OFFSET (st->extreloff);
NZ_OFFSET (st->locreloff);
}
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
{
struct dyld_info_command *st = (struct dyld_info_command *)lc;
NZ_OFFSET (st->rebase_off);
NZ_OFFSET (st->bind_off);
NZ_OFFSET (st->weak_bind_off);
NZ_OFFSET (st->lazy_bind_off);
NZ_OFFSET (st->export_off);
}
break;
}
}
/* Fill r_bin_dyldcache_lib_t ret */
ret->b = dbuf;
strncpy (ret->path, libname, sizeof (ret->path) - 1);
ret->size = libsz;
return ret;
}
Commit Message: Fix #12374 - oobread crash in truncated dyldcache ##bin
CWE ID: CWE-125 | struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj_t* bin, int idx, int *nlib) {
ut64 liboff, linkedit_offset;
ut64 dyld_vmbase;
ut32 addend = 0;
struct r_bin_dyldcache_lib_t *ret = NULL;
struct dyld_cache_image_info* image_infos = NULL;
struct mach_header *mh;
ut8 *data, *cmdptr;
int cmd, libsz = 0;
RBuffer* dbuf;
char *libname;
if (!bin) {
return NULL;
}
if (bin->size < 1) {
eprintf ("Empty file? (%s)\n", bin->file? bin->file: "(null)");
return NULL;
}
if (bin->nlibs < 0 || idx < 0 || idx >= bin->nlibs) {
return NULL;
}
*nlib = bin->nlibs;
ret = R_NEW0 (struct r_bin_dyldcache_lib_t);
if (!ret) {
return NULL;
}
if (bin->hdr.startaddr > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
if (bin->hdr.startaddr > bin->size || bin->hdr.baseaddroff > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
int sz = bin->nlibs * sizeof (struct dyld_cache_image_info);
image_infos = malloc (sz); //(struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);
if (!image_infos) {
free (ret);
return NULL;
}
r_buf_read_at (bin->b, bin->hdr.startaddr, (ut8*)image_infos, sz);
dyld_vmbase = r_buf_read64le (bin->b, bin->hdr.baseaddroff);
liboff = image_infos[idx].address - dyld_vmbase;
if (liboff > bin->size) {
eprintf ("Corrupted file\n");
free (ret);
return NULL;
}
ret->offset = liboff;
int pfo = image_infos[idx].pathFileOffset;
if (pfo < 0 || pfo > bin->size) {
eprintf ("corrupted file: pathFileOffset > bin->size (%d)\n", pfo);
free (ret);
return NULL;
}
libname = r_buf_read_string (bin->b, pfo, 64);
/* Locate lib hdr in cache */
data = bin->b->buf + liboff;
mh = (struct mach_header *)data;
/* Check it is mach-o */
if (mh->magic != MH_MAGIC && mh->magic != MH_MAGIC_64) {
if (mh->magic == 0xbebafeca) { //FAT binary
eprintf ("FAT Binary\n");
}
eprintf ("Not mach-o\n");
free (ret);
return NULL;
}
/* Write mach-o hdr */
if (!(dbuf = r_buf_new ())) {
eprintf ("new (dbuf)\n");
free (ret);
return NULL;
}
addend = mh->magic == MH_MAGIC? sizeof (struct mach_header) : sizeof (struct mach_header_64);
r_buf_set_bytes (dbuf, data, addend);
cmdptr = data + addend;
/* Write load commands */
for (cmd = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
r_buf_append_bytes (dbuf, (ut8*)lc, lc->cmdsize);
cmdptr += lc->cmdsize;
}
cmdptr = data + addend;
/* Write segments */
for (cmd = linkedit_offset = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
cmdptr += lc->cmdsize;
switch (lc->cmd) {
case LC_SEGMENT:
{
/* Write segment and patch offset */
struct segment_command *seg = (struct segment_command *)lc;
int t = seg->filesize;
if (seg->fileoff + seg->filesize > bin->size || seg->fileoff > bin->size) {
eprintf ("malformed dyldcache\n");
free (ret);
r_buf_free (dbuf);
return NULL;
}
r_buf_append_bytes (dbuf, bin->b->buf+seg->fileoff, t);
r_bin_dyldcache_apply_patch (dbuf, dbuf->length, (ut64)((size_t)&seg->fileoff - (size_t)data));
/* Patch section offsets */
int sect_offset = seg->fileoff - libsz;
libsz = dbuf->length;
if (!strcmp (seg->segname, "__LINKEDIT")) {
linkedit_offset = sect_offset;
}
if (seg->nsects > 0) {
struct section *sects = (struct section *)((ut8 *)seg + sizeof(struct segment_command));
int nsect;
for (nsect = 0; nsect < seg->nsects; nsect++) {
if (sects[nsect].offset > libsz) {
r_bin_dyldcache_apply_patch (dbuf, sects[nsect].offset - sect_offset,
(ut64)((size_t)§s[nsect].offset - (size_t)data));
}
}
}
}
break;
case LC_SYMTAB:
{
struct symtab_command *st = (struct symtab_command *)lc;
NZ_OFFSET (st->symoff);
NZ_OFFSET (st->stroff);
}
break;
case LC_DYSYMTAB:
{
struct dysymtab_command *st = (struct dysymtab_command *)lc;
NZ_OFFSET (st->tocoff);
NZ_OFFSET (st->modtaboff);
NZ_OFFSET (st->extrefsymoff);
NZ_OFFSET (st->indirectsymoff);
NZ_OFFSET (st->extreloff);
NZ_OFFSET (st->locreloff);
}
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
{
struct dyld_info_command *st = (struct dyld_info_command *)lc;
NZ_OFFSET (st->rebase_off);
NZ_OFFSET (st->bind_off);
NZ_OFFSET (st->weak_bind_off);
NZ_OFFSET (st->lazy_bind_off);
NZ_OFFSET (st->export_off);
}
break;
}
}
/* Fill r_bin_dyldcache_lib_t ret */
ret->b = dbuf;
strncpy (ret->path, libname, sizeof (ret->path) - 1);
ret->size = libsz;
return ret;
}
| 168,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: int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v)
{
int m;
/* We can reliably put at most 31 bits since ISO/IEC 9899 only
guarantees that a long can represent values up to 2^31-1. */
assert(n >= 0 && n < 32);
/* Ensure that only the bits to be output are nonzero. */
assert(!(v & (~JAS_ONES(n))));
/* Put the desired number of bits to the specified bit stream. */
m = n - 1;
while (--n >= 0) {
if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) {
return EOF;
}
v <<= 1;
}
return 0;
}
Commit Message: Changed the JPC bitstream code to more gracefully handle a request
for a larger sized integer than what can be handled (i.e., return
with an error instead of failing an assert).
CWE ID: | int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v)
{
int m;
/* We can reliably put at most 31 bits since ISO/IEC 9899 only
guarantees that a long can represent values up to 2^31-1. */
//assert(n >= 0 && n < 32);
if (n < 0 || n >= 32) {
return EOF;
}
/* Ensure that only the bits to be output are nonzero. */
assert(!(v & (~JAS_ONES(n))));
/* Put the desired number of bits to the specified bit stream. */
m = n - 1;
while (--n >= 0) {
if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) {
return EOF;
}
v <<= 1;
}
return 0;
}
| 168,733 |
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 mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
struct buffer_head *exbh)
{
struct inode *inode = mpd->inode;
struct address_space *mapping = inode->i_mapping;
int blocks = exbh->b_size >> inode->i_blkbits;
sector_t pblock = exbh->b_blocknr, cur_logical;
struct buffer_head *head, *bh;
pgoff_t index, end;
struct pagevec pvec;
int nr_pages, i;
index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
pagevec_init(&pvec, 0);
while (index <= end) {
/* XXX: optimize tail */
nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
if (nr_pages == 0)
break;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
index = page->index;
if (index > end)
break;
index++;
BUG_ON(!PageLocked(page));
BUG_ON(PageWriteback(page));
BUG_ON(!page_has_buffers(page));
bh = page_buffers(page);
head = bh;
/* skip blocks out of the range */
do {
if (cur_logical >= logical)
break;
cur_logical++;
} while ((bh = bh->b_this_page) != head);
do {
if (cur_logical >= logical + blocks)
break;
if (buffer_delay(bh) ||
buffer_unwritten(bh)) {
BUG_ON(bh->b_bdev != inode->i_sb->s_bdev);
if (buffer_delay(bh)) {
clear_buffer_delay(bh);
bh->b_blocknr = pblock;
} else {
/*
* unwritten already should have
* blocknr assigned. Verify that
*/
clear_buffer_unwritten(bh);
BUG_ON(bh->b_blocknr != pblock);
}
} else if (buffer_mapped(bh))
BUG_ON(bh->b_blocknr != pblock);
cur_logical++;
pblock++;
} while ((bh = bh->b_this_page) != head);
}
pagevec_release(&pvec);
}
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
struct buffer_head *exbh)
{
struct inode *inode = mpd->inode;
struct address_space *mapping = inode->i_mapping;
int blocks = exbh->b_size >> inode->i_blkbits;
sector_t pblock = exbh->b_blocknr, cur_logical;
struct buffer_head *head, *bh;
pgoff_t index, end;
struct pagevec pvec;
int nr_pages, i;
index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
pagevec_init(&pvec, 0);
while (index <= end) {
/* XXX: optimize tail */
nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
if (nr_pages == 0)
break;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
index = page->index;
if (index > end)
break;
index++;
BUG_ON(!PageLocked(page));
BUG_ON(PageWriteback(page));
BUG_ON(!page_has_buffers(page));
bh = page_buffers(page);
head = bh;
/* skip blocks out of the range */
do {
if (cur_logical >= logical)
break;
cur_logical++;
} while ((bh = bh->b_this_page) != head);
do {
if (cur_logical >= logical + blocks)
break;
if (buffer_delay(bh) ||
buffer_unwritten(bh)) {
BUG_ON(bh->b_bdev != inode->i_sb->s_bdev);
if (buffer_delay(bh)) {
clear_buffer_delay(bh);
bh->b_blocknr = pblock;
} else {
/*
* unwritten already should have
* blocknr assigned. Verify that
*/
clear_buffer_unwritten(bh);
BUG_ON(bh->b_blocknr != pblock);
}
} else if (buffer_mapped(bh))
BUG_ON(bh->b_blocknr != pblock);
if (buffer_uninit(exbh))
set_buffer_uninit(bh);
cur_logical++;
pblock++;
} while ((bh = bh->b_this_page) != head);
}
pagevec_release(&pvec);
}
}
| 167,552 |
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 PermissionsData::CanCaptureVisiblePage(
const GURL& document_url,
int tab_id,
std::string* error,
CaptureRequirement capture_requirement) const {
bool has_active_tab = false;
bool has_all_urls = false;
bool has_page_capture = false;
url::Origin origin = url::Origin::Create(document_url);
const GURL origin_url = origin.GetURL();
{
base::AutoLock auto_lock(runtime_lock_);
if (location_ != Manifest::COMPONENT &&
IsPolicyBlockedHostUnsafe(origin_url)) {
if (error)
*error = extension_misc::kPolicyBlockedScripting;
return false;
}
const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id);
has_active_tab = tab_permissions &&
tab_permissions->HasAPIPermission(APIPermission::kTab);
const URLPattern all_urls(URLPattern::SCHEME_ALL,
URLPattern::kAllUrlsPattern);
has_all_urls =
active_permissions_unsafe_->explicit_hosts().ContainsPattern(all_urls);
has_page_capture = active_permissions_unsafe_->HasAPIPermission(
APIPermission::kPageCapture);
}
std::string access_error;
if (capture_requirement == CaptureRequirement::kActiveTabOrAllUrls) {
if (!has_active_tab && !has_all_urls) {
if (error)
*error = manifest_errors::kAllURLOrActiveTabNeeded;
return false;
}
if (GetPageAccess(origin_url, tab_id, &access_error) ==
PageAccess::kAllowed)
return true;
} else {
DCHECK_EQ(CaptureRequirement::kPageCapture, capture_requirement);
if (!has_page_capture) {
if (error)
*error = manifest_errors::kPageCaptureNeeded;
}
if ((origin_url.SchemeIs(url::kHttpScheme) ||
origin_url.SchemeIs(url::kHttpsScheme)) &&
!origin.IsSameOriginWith(url::Origin::Create(
ExtensionsClient::Get()->GetWebstoreBaseURL()))) {
return true;
}
}
if (origin_url.host() == extension_id_)
return true;
bool allowed_with_active_tab =
origin_url.SchemeIs(content::kChromeUIScheme) ||
origin_url.SchemeIs(kExtensionScheme) ||
document_url.SchemeIs(url::kDataScheme) ||
origin.IsSameOriginWith(
url::Origin::Create(ExtensionsClient::Get()->GetWebstoreBaseURL()));
if (!allowed_with_active_tab) {
if (error)
*error = access_error;
return false;
}
if (has_active_tab)
return true;
if (error)
*error = manifest_errors::kActiveTabPermissionNotGranted;
return false;
}
Commit Message: [Extensions] Have URLPattern::Contains() properly check schemes
Have URLPattern::Contains() properly check the schemes of the patterns
when evaluating if one pattern contains another. This is important in
order to prevent extensions from requesting chrome:-scheme permissions
via the permissions API when <all_urls> is specified as an optional
permission.
Bug: 859600,918470
Change-Id: If04d945ad0c939e84a80d83502c0f84b6ef0923d
Reviewed-on: https://chromium-review.googlesource.com/c/1396561
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621410}
CWE ID: CWE-79 | bool PermissionsData::CanCaptureVisiblePage(
const GURL& document_url,
int tab_id,
std::string* error,
CaptureRequirement capture_requirement) const {
bool has_active_tab = false;
bool has_all_urls = false;
bool has_page_capture = false;
url::Origin origin = url::Origin::Create(document_url);
const GURL origin_url = origin.GetURL();
{
base::AutoLock auto_lock(runtime_lock_);
if (location_ != Manifest::COMPONENT &&
IsPolicyBlockedHostUnsafe(origin_url)) {
if (error)
*error = extension_misc::kPolicyBlockedScripting;
return false;
}
const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id);
has_active_tab = tab_permissions &&
tab_permissions->HasAPIPermission(APIPermission::kTab);
// Check if any of the host permissions match all urls. We don't use
// URLPatternSet::ContainsPattern() here because a) the schemes may be
// different and b) this is more efficient.
for (const auto& pattern : active_permissions_unsafe_->explicit_hosts()) {
if (pattern.match_all_urls()) {
has_all_urls = true;
break;
}
}
has_page_capture = active_permissions_unsafe_->HasAPIPermission(
APIPermission::kPageCapture);
}
std::string access_error;
if (capture_requirement == CaptureRequirement::kActiveTabOrAllUrls) {
if (!has_active_tab && !has_all_urls) {
if (error)
*error = manifest_errors::kAllURLOrActiveTabNeeded;
return false;
}
if (GetPageAccess(origin_url, tab_id, &access_error) ==
PageAccess::kAllowed)
return true;
} else {
DCHECK_EQ(CaptureRequirement::kPageCapture, capture_requirement);
if (!has_page_capture) {
if (error)
*error = manifest_errors::kPageCaptureNeeded;
}
if ((origin_url.SchemeIs(url::kHttpScheme) ||
origin_url.SchemeIs(url::kHttpsScheme)) &&
!origin.IsSameOriginWith(url::Origin::Create(
ExtensionsClient::Get()->GetWebstoreBaseURL()))) {
return true;
}
}
if (origin_url.host() == extension_id_)
return true;
bool allowed_with_active_tab =
origin_url.SchemeIs(content::kChromeUIScheme) ||
origin_url.SchemeIs(kExtensionScheme) ||
document_url.SchemeIs(url::kDataScheme) ||
origin.IsSameOriginWith(
url::Origin::Create(ExtensionsClient::Get()->GetWebstoreBaseURL()));
if (!allowed_with_active_tab) {
if (error)
*error = access_error;
return false;
}
if (has_active_tab)
return true;
if (error)
*error = manifest_errors::kActiveTabPermissionNotGranted;
return false;
}
| 173,119 |
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 vpx_codec_err_t vp8_decode(vpx_codec_alg_priv_t *ctx,
const uint8_t *data,
unsigned int data_sz,
void *user_priv,
long deadline)
{
vpx_codec_err_t res = VPX_CODEC_OK;
unsigned int resolution_change = 0;
unsigned int w, h;
if (!ctx->fragments.enabled && (data == NULL && data_sz == 0))
{
return 0;
}
/* Update the input fragment data */
if(update_fragments(ctx, data, data_sz, &res) <= 0)
return res;
/* Determine the stream parameters. Note that we rely on peek_si to
* validate that we have a buffer that does not wrap around the top
* of the heap.
*/
w = ctx->si.w;
h = ctx->si.h;
res = vp8_peek_si_internal(ctx->fragments.ptrs[0], ctx->fragments.sizes[0],
&ctx->si, ctx->decrypt_cb, ctx->decrypt_state);
if((res == VPX_CODEC_UNSUP_BITSTREAM) && !ctx->si.is_kf)
{
/* the peek function returns an error for non keyframes, however for
* this case, it is not an error */
res = VPX_CODEC_OK;
}
if(!ctx->decoder_init && !ctx->si.is_kf)
res = VPX_CODEC_UNSUP_BITSTREAM;
if ((ctx->si.h != h) || (ctx->si.w != w))
resolution_change = 1;
/* Initialize the decoder instance on the first frame*/
if (!res && !ctx->decoder_init)
{
VP8D_CONFIG oxcf;
oxcf.Width = ctx->si.w;
oxcf.Height = ctx->si.h;
oxcf.Version = 9;
oxcf.postprocess = 0;
oxcf.max_threads = ctx->cfg.threads;
oxcf.error_concealment =
(ctx->base.init_flags & VPX_CODEC_USE_ERROR_CONCEALMENT);
/* If postprocessing was enabled by the application and a
* configuration has not been provided, default it.
*/
if (!ctx->postproc_cfg_set
&& (ctx->base.init_flags & VPX_CODEC_USE_POSTPROC)) {
ctx->postproc_cfg.post_proc_flag =
VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE;
ctx->postproc_cfg.deblocking_level = 4;
ctx->postproc_cfg.noise_level = 0;
}
res = vp8_create_decoder_instances(&ctx->yv12_frame_buffers, &oxcf);
ctx->decoder_init = 1;
}
/* Set these even if already initialized. The caller may have changed the
* decrypt config between frames.
*/
if (ctx->decoder_init) {
ctx->yv12_frame_buffers.pbi[0]->decrypt_cb = ctx->decrypt_cb;
ctx->yv12_frame_buffers.pbi[0]->decrypt_state = ctx->decrypt_state;
}
if (!res)
{
VP8D_COMP *pbi = ctx->yv12_frame_buffers.pbi[0];
if (resolution_change)
{
VP8_COMMON *const pc = & pbi->common;
MACROBLOCKD *const xd = & pbi->mb;
#if CONFIG_MULTITHREAD
int i;
#endif
pc->Width = ctx->si.w;
pc->Height = ctx->si.h;
{
int prev_mb_rows = pc->mb_rows;
if (setjmp(pbi->common.error.jmp))
{
pbi->common.error.setjmp = 0;
vp8_clear_system_state();
/* same return value as used in vp8dx_receive_compressed_data */
return -1;
}
pbi->common.error.setjmp = 1;
if (pc->Width <= 0)
{
pc->Width = w;
vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
"Invalid frame width");
}
if (pc->Height <= 0)
{
pc->Height = h;
vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
"Invalid frame height");
}
if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height))
vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
"Failed to allocate frame buffers");
xd->pre = pc->yv12_fb[pc->lst_fb_idx];
xd->dst = pc->yv12_fb[pc->new_fb_idx];
#if CONFIG_MULTITHREAD
for (i = 0; i < pbi->allocated_decoding_thread_count; i++)
{
pbi->mb_row_di[i].mbd.dst = pc->yv12_fb[pc->new_fb_idx];
vp8_build_block_doffsets(&pbi->mb_row_di[i].mbd);
}
#endif
vp8_build_block_doffsets(&pbi->mb);
/* allocate memory for last frame MODE_INFO array */
#if CONFIG_ERROR_CONCEALMENT
if (pbi->ec_enabled)
{
/* old prev_mip was released by vp8_de_alloc_frame_buffers()
* called in vp8_alloc_frame_buffers() */
pc->prev_mip = vpx_calloc(
(pc->mb_cols + 1) * (pc->mb_rows + 1),
sizeof(MODE_INFO));
if (!pc->prev_mip)
{
vp8_de_alloc_frame_buffers(pc);
vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
"Failed to allocate"
"last frame MODE_INFO array");
}
pc->prev_mi = pc->prev_mip + pc->mode_info_stride + 1;
if (vp8_alloc_overlap_lists(pbi))
vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
"Failed to allocate overlap lists "
"for error concealment");
}
#endif
#if CONFIG_MULTITHREAD
if (pbi->b_multithreaded_rd)
vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows);
#else
(void)prev_mb_rows;
#endif
}
pbi->common.error.setjmp = 0;
/* required to get past the first get_free_fb() call */
pbi->common.fb_idx_ref_cnt[0] = 0;
}
/* update the pbi fragment data */
pbi->fragments = ctx->fragments;
ctx->user_priv = user_priv;
if (vp8dx_receive_compressed_data(pbi, data_sz, data, deadline))
{
res = update_error_state(ctx, &pbi->common.error);
}
/* get ready for the next series of fragments */
ctx->fragments.count = 0;
}
return res;
}
Commit Message: DO NOT MERGE | libvpx: Cherry-pick 0f42d1f from upstream
Description from upstream:
vp8: fix decoder crash with invalid leading keyframes
decoding the same invalid keyframe twice would result in a crash as the
second time through the decoder would be assumed to have been
initialized as there was no resolution change. in this case the
resolution was itself invalid (0x6), but vp8_peek_si() was only failing
in the case of 0x0.
invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf tests this case by
duplicating the first keyframe and additionally adds a valid one to
ensure decoding can resume without error.
Bug: 30593765
Change-Id: I0de85f5a5eb5c0a5605230faf20c042b69aea507
(cherry picked from commit fc0466b695dce03e10390101844caa374848d903)
(cherry picked from commit 1114575245cb9d2f108749f916c76549524f5136)
CWE ID: CWE-20 | static vpx_codec_err_t vp8_decode(vpx_codec_alg_priv_t *ctx,
const uint8_t *data,
unsigned int data_sz,
void *user_priv,
long deadline)
{
vpx_codec_err_t res = VPX_CODEC_OK;
unsigned int resolution_change = 0;
unsigned int w, h;
if (!ctx->fragments.enabled && (data == NULL && data_sz == 0))
{
return 0;
}
/* Update the input fragment data */
if(update_fragments(ctx, data, data_sz, &res) <= 0)
return res;
/* Determine the stream parameters. Note that we rely on peek_si to
* validate that we have a buffer that does not wrap around the top
* of the heap.
*/
w = ctx->si.w;
h = ctx->si.h;
res = vp8_peek_si_internal(ctx->fragments.ptrs[0], ctx->fragments.sizes[0],
&ctx->si, ctx->decrypt_cb, ctx->decrypt_state);
if((res == VPX_CODEC_UNSUP_BITSTREAM) && !ctx->si.is_kf)
{
/* the peek function returns an error for non keyframes, however for
* this case, it is not an error */
res = VPX_CODEC_OK;
}
if(!ctx->decoder_init && !ctx->si.is_kf)
res = VPX_CODEC_UNSUP_BITSTREAM;
if ((ctx->si.h != h) || (ctx->si.w != w))
resolution_change = 1;
/* Initialize the decoder instance on the first frame*/
if (!res && !ctx->decoder_init)
{
VP8D_CONFIG oxcf;
oxcf.Width = ctx->si.w;
oxcf.Height = ctx->si.h;
oxcf.Version = 9;
oxcf.postprocess = 0;
oxcf.max_threads = ctx->cfg.threads;
oxcf.error_concealment =
(ctx->base.init_flags & VPX_CODEC_USE_ERROR_CONCEALMENT);
/* If postprocessing was enabled by the application and a
* configuration has not been provided, default it.
*/
if (!ctx->postproc_cfg_set
&& (ctx->base.init_flags & VPX_CODEC_USE_POSTPROC)) {
ctx->postproc_cfg.post_proc_flag =
VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE;
ctx->postproc_cfg.deblocking_level = 4;
ctx->postproc_cfg.noise_level = 0;
}
res = vp8_create_decoder_instances(&ctx->yv12_frame_buffers, &oxcf);
ctx->decoder_init = 1;
}
/* Set these even if already initialized. The caller may have changed the
* decrypt config between frames.
*/
if (ctx->decoder_init) {
ctx->yv12_frame_buffers.pbi[0]->decrypt_cb = ctx->decrypt_cb;
ctx->yv12_frame_buffers.pbi[0]->decrypt_state = ctx->decrypt_state;
}
if (!res)
{
VP8D_COMP *pbi = ctx->yv12_frame_buffers.pbi[0];
if (resolution_change)
{
VP8_COMMON *const pc = & pbi->common;
MACROBLOCKD *const xd = & pbi->mb;
#if CONFIG_MULTITHREAD
int i;
#endif
pc->Width = ctx->si.w;
pc->Height = ctx->si.h;
{
int prev_mb_rows = pc->mb_rows;
if (setjmp(pbi->common.error.jmp))
{
pbi->common.error.setjmp = 0;
/* on failure clear the cached resolution to ensure a full
* reallocation is attempted on resync. */
ctx->si.w = 0;
ctx->si.h = 0;
vp8_clear_system_state();
/* same return value as used in vp8dx_receive_compressed_data */
return -1;
}
pbi->common.error.setjmp = 1;
if (pc->Width <= 0)
{
pc->Width = w;
vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
"Invalid frame width");
}
if (pc->Height <= 0)
{
pc->Height = h;
vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
"Invalid frame height");
}
if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height))
vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
"Failed to allocate frame buffers");
xd->pre = pc->yv12_fb[pc->lst_fb_idx];
xd->dst = pc->yv12_fb[pc->new_fb_idx];
#if CONFIG_MULTITHREAD
for (i = 0; i < pbi->allocated_decoding_thread_count; i++)
{
pbi->mb_row_di[i].mbd.dst = pc->yv12_fb[pc->new_fb_idx];
vp8_build_block_doffsets(&pbi->mb_row_di[i].mbd);
}
#endif
vp8_build_block_doffsets(&pbi->mb);
/* allocate memory for last frame MODE_INFO array */
#if CONFIG_ERROR_CONCEALMENT
if (pbi->ec_enabled)
{
/* old prev_mip was released by vp8_de_alloc_frame_buffers()
* called in vp8_alloc_frame_buffers() */
pc->prev_mip = vpx_calloc(
(pc->mb_cols + 1) * (pc->mb_rows + 1),
sizeof(MODE_INFO));
if (!pc->prev_mip)
{
vp8_de_alloc_frame_buffers(pc);
vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
"Failed to allocate"
"last frame MODE_INFO array");
}
pc->prev_mi = pc->prev_mip + pc->mode_info_stride + 1;
if (vp8_alloc_overlap_lists(pbi))
vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
"Failed to allocate overlap lists "
"for error concealment");
}
#endif
#if CONFIG_MULTITHREAD
if (pbi->b_multithreaded_rd)
vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows);
#else
(void)prev_mb_rows;
#endif
}
pbi->common.error.setjmp = 0;
/* required to get past the first get_free_fb() call */
pbi->common.fb_idx_ref_cnt[0] = 0;
}
/* update the pbi fragment data */
pbi->fragments = ctx->fragments;
ctx->user_priv = user_priv;
if (vp8dx_receive_compressed_data(pbi, data_sz, data, deadline))
{
res = update_error_state(ctx, &pbi->common.error);
}
/* get ready for the next series of fragments */
ctx->fragments.count = 0;
}
return res;
}
| 173,382 |
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 CloudPolicySubsystem::StopAutoRetry() {
cloud_policy_controller_->StopAutoRetry();
device_token_fetcher_->StopAutoRetry();
data_store_->Reset();
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void CloudPolicySubsystem::StopAutoRetry() {
void CloudPolicySubsystem::Reset() {
data_store_->Reset();
cloud_policy_cache_->Reset();
cloud_policy_controller_->Reset();
device_token_fetcher_->Reset();
}
| 170,283 |
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 IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) {
size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0);
icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length);
if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) ==
ustr_host.length())
transliterator_.get()->transliterate(ustr_host);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeString ustr_skeleton;
uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton,
&status);
if (U_FAILURE(status))
return false;
std::string skeleton;
ustr_skeleton.toUTF8String(skeleton);
return LookupMatchInTopDomains(skeleton);
}
Commit Message: Add a few more confusable map entries
1. Map Malaylam U+0D1F to 's'.
2. Map 'small-cap-like' Cyrillic letters to "look-alike" Latin lowercase
letters.
The characters in new confusable map entries are replaced by their Latin
"look-alike" characters before the skeleton is calculated to compare with
top domain names.
Bug: 784761,773930
Test: components_unittests --gtest_filter=*IDNToUni*
Change-Id: Ib26664e21ac5eb290e4a2993b01cbf0edaade0ee
Reviewed-on: https://chromium-review.googlesource.com/805214
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Jungshik Shin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#521648}
CWE ID: CWE-20 | bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) {
size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0);
icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length);
if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) ==
ustr_host.length())
diacritic_remover_.get()->transliterate(ustr_host);
extra_confusable_mapper_.get()->transliterate(ustr_host);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeString ustr_skeleton;
uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton,
&status);
if (U_FAILURE(status))
return false;
std::string skeleton;
return LookupMatchInTopDomains(ustr_skeleton.toUTF8String(skeleton));
}
| 172,686 |
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 IOHandler::Read(
const std::string& handle,
Maybe<int> offset,
Maybe<int> max_size,
std::unique_ptr<ReadCallback> callback) {
static const size_t kDefaultChunkSize = 10 * 1024 * 1024;
static const char kBlobPrefix[] = "blob:";
scoped_refptr<DevToolsIOContext::ROStream> stream =
io_context_->GetByHandle(handle);
if (!stream && process_host_ &&
StartsWith(handle, kBlobPrefix, base::CompareCase::SENSITIVE)) {
BrowserContext* browser_context = process_host_->GetBrowserContext();
ChromeBlobStorageContext* blob_context =
ChromeBlobStorageContext::GetFor(browser_context);
StoragePartition* storage_partition = process_host_->GetStoragePartition();
std::string uuid = handle.substr(strlen(kBlobPrefix));
stream =
io_context_->OpenBlob(blob_context, storage_partition, handle, uuid);
}
if (!stream) {
callback->sendFailure(Response::InvalidParams("Invalid stream handle"));
return;
}
stream->Read(
offset.fromMaybe(-1), max_size.fromMaybe(kDefaultChunkSize),
base::BindOnce(&IOHandler::ReadComplete, weak_factory_.GetWeakPtr(),
base::Passed(std::move(callback))));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void IOHandler::Read(
const std::string& handle,
Maybe<int> offset,
Maybe<int> max_size,
std::unique_ptr<ReadCallback> callback) {
static const size_t kDefaultChunkSize = 10 * 1024 * 1024;
static const char kBlobPrefix[] = "blob:";
scoped_refptr<DevToolsIOContext::ROStream> stream =
io_context_->GetByHandle(handle);
if (!stream && browser_context_ &&
StartsWith(handle, kBlobPrefix, base::CompareCase::SENSITIVE)) {
ChromeBlobStorageContext* blob_context =
ChromeBlobStorageContext::GetFor(browser_context_);
std::string uuid = handle.substr(strlen(kBlobPrefix));
stream =
io_context_->OpenBlob(blob_context, storage_partition_, handle, uuid);
}
if (!stream) {
callback->sendFailure(Response::InvalidParams("Invalid stream handle"));
return;
}
stream->Read(
offset.fromMaybe(-1), max_size.fromMaybe(kDefaultChunkSize),
base::BindOnce(&IOHandler::ReadComplete, weak_factory_.GetWeakPtr(),
base::Passed(std::move(callback))));
}
| 172,750 |
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 DevToolsDataSource::StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) {
std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
bundled_path_prefix += "/";
if (base::StartsWith(path, bundled_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
StartBundledDataRequest(path.substr(bundled_path_prefix.length()),
callback);
return;
}
std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath);
if (base::StartsWith(path, empty_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
callback.Run(new base::RefCountedStaticMemory());
return;
}
std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath);
remote_path_prefix += "/";
if (base::StartsWith(path, remote_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length()));
CHECK_EQ(url.host(), kRemoteFrontendDomain);
if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) {
StartRemoteDataRequest(url, callback);
} else {
DLOG(ERROR) << "Refusing to load invalid remote front-end URL";
callback.Run(new base::RefCountedStaticMemory(kHttpNotFound,
strlen(kHttpNotFound)));
}
return;
}
std::string custom_frontend_url =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kCustomDevtoolsFrontend);
if (custom_frontend_url.empty()) {
callback.Run(NULL);
return;
}
std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath);
custom_path_prefix += "/";
if (base::StartsWith(path, custom_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url = GURL(custom_frontend_url +
path.substr(custom_path_prefix.length()));
StartCustomDataRequest(url, callback);
return;
}
callback.Run(NULL);
}
Commit Message: Hide DevTools frontend from webRequest API
Prevent extensions from observing requests for remote DevTools frontends
and add regression tests.
And update ExtensionTestApi to support initializing the embedded test
server and port from SetUpCommandLine (before SetUpOnMainThread).
BUG=797497,797500
TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo
Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735
Reviewed-on: https://chromium-review.googlesource.com/844316
Commit-Queue: Rob Wu <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#528187}
CWE ID: CWE-200 | void DevToolsDataSource::StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) {
std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
bundled_path_prefix += "/";
if (base::StartsWith(path, bundled_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
StartBundledDataRequest(path.substr(bundled_path_prefix.length()),
callback);
return;
}
std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath);
if (base::StartsWith(path, empty_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
callback.Run(new base::RefCountedStaticMemory());
return;
}
std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath);
remote_path_prefix += "/";
if (base::StartsWith(path, remote_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length()));
CHECK_EQ(url.host(), kRemoteFrontendDomain);
if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) {
StartRemoteDataRequest(url, callback);
} else {
DLOG(ERROR) << "Refusing to load invalid remote front-end URL";
callback.Run(new base::RefCountedStaticMemory(kHttpNotFound,
strlen(kHttpNotFound)));
}
return;
}
std::string custom_frontend_url =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kCustomDevtoolsFrontend);
if (custom_frontend_url.empty()) {
callback.Run(NULL);
return;
}
std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath);
custom_path_prefix += "/";
if (base::StartsWith(path, custom_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url = GURL(custom_frontend_url +
path.substr(custom_path_prefix.length()));
DCHECK(url.is_valid());
StartCustomDataRequest(url, callback);
return;
}
callback.Run(NULL);
}
| 172,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: smb2_flush(smb_request_t *sr)
{
smb_ofile_t *of = NULL;
uint16_t StructSize;
uint16_t reserved1;
uint32_t reserved2;
smb2fid_t smb2fid;
uint32_t status;
int rc = 0;
/*
* SMB2 Flush request
*/
rc = smb_mbc_decodef(
&sr->smb_data, "wwlqq",
&StructSize, /* w */
&reserved1, /* w */
&reserved2, /* l */
&smb2fid.persistent, /* q */
&smb2fid.temporal); /* q */
if (rc)
return (SDRC_ERROR);
if (StructSize != 24)
return (SDRC_ERROR);
status = smb2sr_lookup_fid(sr, &smb2fid);
if (status) {
smb2sr_put_error(sr, status);
return (SDRC_SUCCESS);
}
of = sr->fid_ofile;
/*
* XXX - todo:
* Flush named pipe should drain writes.
*/
if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0)
(void) smb_fsop_commit(sr, of->f_cr, of->f_node);
/*
* SMB2 Flush reply
*/
(void) smb_mbc_encodef(
&sr->reply, "wwl",
4, /* StructSize */ /* w */
0); /* reserved */ /* w */
return (SDRC_SUCCESS);
}
Commit Message: 7483 SMB flush on pipe triggers NULL pointer dereference in module smbsrv
Reviewed by: Gordon Ross <[email protected]>
Reviewed by: Matt Barden <[email protected]>
Reviewed by: Evan Layton <[email protected]>
Reviewed by: Dan McDonald <[email protected]>
Approved by: Gordon Ross <[email protected]>
CWE ID: CWE-476 | smb2_flush(smb_request_t *sr)
{
uint16_t StructSize;
uint16_t reserved1;
uint32_t reserved2;
smb2fid_t smb2fid;
uint32_t status;
int rc = 0;
/*
* SMB2 Flush request
*/
rc = smb_mbc_decodef(
&sr->smb_data, "wwlqq",
&StructSize, /* w */
&reserved1, /* w */
&reserved2, /* l */
&smb2fid.persistent, /* q */
&smb2fid.temporal); /* q */
if (rc)
return (SDRC_ERROR);
if (StructSize != 24)
return (SDRC_ERROR);
status = smb2sr_lookup_fid(sr, &smb2fid);
if (status) {
smb2sr_put_error(sr, status);
return (SDRC_SUCCESS);
}
smb_ofile_flush(sr, sr->fid_ofile);
/*
* SMB2 Flush reply
*/
(void) smb_mbc_encodef(
&sr->reply, "wwl",
4, /* StructSize */ /* w */
0); /* reserved */ /* w */
return (SDRC_SUCCESS);
}
| 168,825 |
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 rfcomm_get_dev_list(void __user *arg)
{
struct rfcomm_dev *dev;
struct rfcomm_dev_list_req *dl;
struct rfcomm_dev_info *di;
int n = 0, size, err;
u16 dev_num;
BT_DBG("");
if (get_user(dev_num, (u16 __user *) arg))
return -EFAULT;
if (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di))
return -EINVAL;
size = sizeof(*dl) + dev_num * sizeof(*di);
dl = kmalloc(size, GFP_KERNEL);
if (!dl)
return -ENOMEM;
di = dl->dev_info;
spin_lock(&rfcomm_dev_lock);
list_for_each_entry(dev, &rfcomm_dev_list, list) {
if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags))
continue;
(di + n)->id = dev->id;
(di + n)->flags = dev->flags;
(di + n)->state = dev->dlc->state;
(di + n)->channel = dev->channel;
bacpy(&(di + n)->src, &dev->src);
bacpy(&(di + n)->dst, &dev->dst);
if (++n >= dev_num)
break;
}
spin_unlock(&rfcomm_dev_lock);
dl->dev_num = n;
size = sizeof(*dl) + n * sizeof(*di);
err = copy_to_user(arg, dl, size);
kfree(dl);
return err ? -EFAULT : 0;
}
Commit Message: Bluetooth: RFCOMM - Fix info leak in ioctl(RFCOMMGETDEVLIST)
The RFCOMM code fails to initialize the two padding bytes of struct
rfcomm_dev_list_req inserted for alignment before copying it to
userland. Additionally there are two padding bytes in each instance of
struct rfcomm_dev_info. The ioctl() that for disclosures two bytes plus
dev_num times two bytes uninitialized kernel heap memory.
Allocate the memory using kzalloc() to fix this issue.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Marcel Holtmann <[email protected]>
Cc: Gustavo Padovan <[email protected]>
Cc: Johan Hedberg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int rfcomm_get_dev_list(void __user *arg)
{
struct rfcomm_dev *dev;
struct rfcomm_dev_list_req *dl;
struct rfcomm_dev_info *di;
int n = 0, size, err;
u16 dev_num;
BT_DBG("");
if (get_user(dev_num, (u16 __user *) arg))
return -EFAULT;
if (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di))
return -EINVAL;
size = sizeof(*dl) + dev_num * sizeof(*di);
dl = kzalloc(size, GFP_KERNEL);
if (!dl)
return -ENOMEM;
di = dl->dev_info;
spin_lock(&rfcomm_dev_lock);
list_for_each_entry(dev, &rfcomm_dev_list, list) {
if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags))
continue;
(di + n)->id = dev->id;
(di + n)->flags = dev->flags;
(di + n)->state = dev->dlc->state;
(di + n)->channel = dev->channel;
bacpy(&(di + n)->src, &dev->src);
bacpy(&(di + n)->dst, &dev->dst);
if (++n >= dev_num)
break;
}
spin_unlock(&rfcomm_dev_lock);
dl->dev_num = n;
size = sizeof(*dl) + n * sizeof(*di);
err = copy_to_user(arg, dl, size);
kfree(dl);
return err ? -EFAULT : 0;
}
| 169,898 |
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_module_get_supported_key_sizes)
{
int i, count = 0;
int *key_sizes;
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
array_init(return_value);
key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count);
for (i = 0; i < count; i++) {
add_index_long(return_value, i, key_sizes[i]);
}
mcrypt_free(key_sizes);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_module_get_supported_key_sizes)
{
int i, count = 0;
int *key_sizes;
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
array_init(return_value);
key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count);
for (i = 0; i < count; i++) {
add_index_long(return_value, i, key_sizes[i]);
}
mcrypt_free(key_sizes);
}
| 167,101 |
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::CreateNewWindow(
RenderFrameHost* opener,
int32_t render_view_route_id,
int32_t main_frame_route_id,
int32_t main_frame_widget_route_id,
const mojom::CreateNewWindowParams& params,
SessionStorageNamespace* session_storage_namespace) {
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_route_id == MSG_ROUTING_NONE));
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_widget_route_id == MSG_ROUTING_NONE));
DCHECK(opener);
int render_process_id = opener->GetProcess()->GetID();
SiteInstance* source_site_instance = opener->GetSiteInstance();
DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id));
bool is_guest = BrowserPluginGuest::IsGuest(this);
DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE);
scoped_refptr<SiteInstance> site_instance =
params.opener_suppressed && !is_guest
? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
: source_site_instance;
const std::string& partition_id =
GetContentClient()->browser()->
GetStoragePartitionIdForSite(GetBrowserContext(),
site_instance->GetSiteURL());
StoragePartition* partition = BrowserContext::GetStoragePartition(
GetBrowserContext(), site_instance.get());
DOMStorageContextWrapper* dom_storage_context =
static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
SessionStorageNamespaceImpl* session_storage_namespace_impl =
static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
if (delegate_ &&
!delegate_->ShouldCreateWebContents(
this, opener, source_site_instance, render_view_route_id,
main_frame_route_id, main_frame_widget_route_id,
params.window_container_type, opener->GetLastCommittedURL(),
params.frame_name, params.target_url, partition_id,
session_storage_namespace)) {
RenderFrameHostImpl* rfh =
RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id);
if (rfh) {
DCHECK(rfh->IsRenderFrameLive());
rfh->Init();
}
return;
}
CreateParams create_params(GetBrowserContext(), site_instance.get());
create_params.routing_id = render_view_route_id;
create_params.main_frame_routing_id = main_frame_route_id;
create_params.main_frame_widget_routing_id = main_frame_widget_route_id;
create_params.main_frame_name = params.frame_name;
create_params.opener_render_process_id = render_process_id;
create_params.opener_render_frame_id = opener->GetRoutingID();
create_params.opener_suppressed = params.opener_suppressed;
if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB)
create_params.initially_hidden = true;
create_params.renderer_initiated_creation =
main_frame_route_id != MSG_ROUTING_NONE;
WebContentsImpl* new_contents = NULL;
if (!is_guest) {
create_params.context = view_->GetNativeView();
create_params.initial_size = GetContainerBounds().size();
new_contents = static_cast<WebContentsImpl*>(
WebContents::Create(create_params));
} else {
new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
}
new_contents->GetController().SetSessionStorageNamespace(
partition_id,
session_storage_namespace);
if (!params.frame_name.empty())
new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
if (!params.opener_suppressed) {
if (!is_guest) {
WebContentsView* new_view = new_contents->view_.get();
new_view->CreateViewForWidget(
new_contents->GetRenderViewHost()->GetWidget(), false);
}
DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id);
pending_contents_[std::make_pair(
render_process_id, main_frame_widget_route_id)] = new_contents;
AddDestructionObserver(new_contents);
}
if (delegate_) {
delegate_->WebContentsCreated(this, render_process_id,
opener->GetRoutingID(), params.frame_name,
params.target_url, new_contents);
}
if (opener) {
for (auto& observer : observers_) {
observer.DidOpenRequestedURL(new_contents, opener, params.target_url,
params.referrer, params.disposition,
ui::PAGE_TRANSITION_LINK,
false, // started_from_context_menu
true); // renderer_initiated
}
}
if (params.opener_suppressed) {
bool was_blocked = false;
if (delegate_) {
gfx::Rect initial_rect;
base::WeakPtr<WebContentsImpl> weak_new_contents =
new_contents->weak_factory_.GetWeakPtr();
delegate_->AddNewContents(
this, new_contents, params.disposition, initial_rect,
params.user_gesture, &was_blocked);
if (!weak_new_contents)
return; // The delegate deleted |new_contents| during AddNewContents().
}
if (!was_blocked) {
OpenURLParams open_params(params.target_url, params.referrer,
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_LINK,
true /* is_renderer_initiated */);
open_params.user_gesture = params.user_gesture;
if (delegate_ && !is_guest &&
!delegate_->ShouldResumeRequestsForCreatedWindow()) {
new_contents->delayed_open_url_params_.reset(
new OpenURLParams(open_params));
} else {
new_contents->OpenURL(open_params);
}
}
}
}
Commit Message: If a page shows a popup, end fullscreen.
This was implemented in Blink r159834, but it is susceptible
to a popup/fullscreen race. This CL reverts that implementation
and re-implements it in WebContents.
BUG=752003
TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen
Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f
Reviewed-on: https://chromium-review.googlesource.com/606987
Commit-Queue: Avi Drissman <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498171}
CWE ID: CWE-20 | void WebContentsImpl::CreateNewWindow(
RenderFrameHost* opener,
int32_t render_view_route_id,
int32_t main_frame_route_id,
int32_t main_frame_widget_route_id,
const mojom::CreateNewWindowParams& params,
SessionStorageNamespace* session_storage_namespace) {
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_route_id == MSG_ROUTING_NONE));
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_widget_route_id == MSG_ROUTING_NONE));
DCHECK(opener);
int render_process_id = opener->GetProcess()->GetID();
SiteInstance* source_site_instance = opener->GetSiteInstance();
DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id));
bool is_guest = BrowserPluginGuest::IsGuest(this);
DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE);
scoped_refptr<SiteInstance> site_instance =
params.opener_suppressed && !is_guest
? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
: source_site_instance;
const std::string& partition_id =
GetContentClient()->browser()->
GetStoragePartitionIdForSite(GetBrowserContext(),
site_instance->GetSiteURL());
StoragePartition* partition = BrowserContext::GetStoragePartition(
GetBrowserContext(), site_instance.get());
DOMStorageContextWrapper* dom_storage_context =
static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
SessionStorageNamespaceImpl* session_storage_namespace_impl =
static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
if (delegate_ &&
!delegate_->ShouldCreateWebContents(
this, opener, source_site_instance, render_view_route_id,
main_frame_route_id, main_frame_widget_route_id,
params.window_container_type, opener->GetLastCommittedURL(),
params.frame_name, params.target_url, partition_id,
session_storage_namespace)) {
RenderFrameHostImpl* rfh =
RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id);
if (rfh) {
DCHECK(rfh->IsRenderFrameLive());
rfh->Init();
}
return;
}
CreateParams create_params(GetBrowserContext(), site_instance.get());
create_params.routing_id = render_view_route_id;
create_params.main_frame_routing_id = main_frame_route_id;
create_params.main_frame_widget_routing_id = main_frame_widget_route_id;
create_params.main_frame_name = params.frame_name;
create_params.opener_render_process_id = render_process_id;
create_params.opener_render_frame_id = opener->GetRoutingID();
create_params.opener_suppressed = params.opener_suppressed;
if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB)
create_params.initially_hidden = true;
create_params.renderer_initiated_creation =
main_frame_route_id != MSG_ROUTING_NONE;
WebContentsImpl* new_contents = NULL;
if (!is_guest) {
create_params.context = view_->GetNativeView();
create_params.initial_size = GetContainerBounds().size();
new_contents = static_cast<WebContentsImpl*>(
WebContents::Create(create_params));
} else {
new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
}
new_contents->GetController().SetSessionStorageNamespace(
partition_id,
session_storage_namespace);
if (!params.frame_name.empty())
new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
if (!params.opener_suppressed) {
if (!is_guest) {
WebContentsView* new_view = new_contents->view_.get();
new_view->CreateViewForWidget(
new_contents->GetRenderViewHost()->GetWidget(), false);
}
DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id);
pending_contents_[std::make_pair(
render_process_id, main_frame_widget_route_id)] = new_contents;
AddDestructionObserver(new_contents);
}
if (delegate_) {
delegate_->WebContentsCreated(this, render_process_id,
opener->GetRoutingID(), params.frame_name,
params.target_url, new_contents);
}
if (opener) {
for (auto& observer : observers_) {
observer.DidOpenRequestedURL(new_contents, opener, params.target_url,
params.referrer, params.disposition,
ui::PAGE_TRANSITION_LINK,
false, // started_from_context_menu
true); // renderer_initiated
}
}
// Any new WebContents opened while this WebContents is in fullscreen can be
// used to confuse the user, so drop fullscreen.
if (IsFullscreenForCurrentTab())
ExitFullscreen(true);
if (params.opener_suppressed) {
bool was_blocked = false;
if (delegate_) {
gfx::Rect initial_rect;
base::WeakPtr<WebContentsImpl> weak_new_contents =
new_contents->weak_factory_.GetWeakPtr();
delegate_->AddNewContents(
this, new_contents, params.disposition, initial_rect,
params.user_gesture, &was_blocked);
if (!weak_new_contents)
return; // The delegate deleted |new_contents| during AddNewContents().
}
if (!was_blocked) {
OpenURLParams open_params(params.target_url, params.referrer,
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_LINK,
true /* is_renderer_initiated */);
open_params.user_gesture = params.user_gesture;
if (delegate_ && !is_guest &&
!delegate_->ShouldResumeRequestsForCreatedWindow()) {
new_contents->delayed_open_url_params_.reset(
new OpenURLParams(open_params));
} else {
new_contents->OpenURL(open_params);
}
}
}
}
| 172,950 |
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(DirectoryIterator, isDot)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name));
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(DirectoryIterator, isDot)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name));
}
| 167,037 |
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: M_fs_error_t M_fs_move(const char *path_old, const char *path_new, M_uint32 mode, M_fs_progress_cb_t cb, M_uint32 progress_flags)
{
char *norm_path_old;
char *norm_path_new;
char *resolve_path;
M_fs_info_t *info;
M_fs_progress_t *progress = NULL;
M_uint64 entry_size;
M_fs_error_t res;
if (path_old == NULL || *path_old == '\0' || path_new == NULL || *path_new == '\0') {
return M_FS_ERROR_INVALID;
}
/* It's okay if new path doesn't exist. */
res = M_fs_path_norm(&norm_path_new, path_new, M_FS_PATH_NORM_RESDIR, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
return res;
}
/* If a path is a file and the destination is a directory the file should be moved
* into the directory. E.g. /file.txt -> /dir = /dir/file.txt */
if (M_fs_isfileintodir(path_old, path_new, &norm_path_old)) {
M_free(norm_path_new);
res = M_fs_move(path_old, norm_path_old, mode, cb, progress_flags);
M_free(norm_path_old);
return res;
}
/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path
* existing to rename because any check we perform may not be true when rename is called. */
res = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
progress = M_fs_progress_create();
res = M_fs_info(&info, path_old, (mode & M_FS_FILE_MODE_PRESERVE_PERMS)?M_FS_PATH_INFO_FLAGS_NONE:M_FS_PATH_INFO_FLAGS_BASIC);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
/* There is a race condition where the path could not exist but be created between the exists check and calling
* rename to move the file but there isn't much we can do in this case. copy will delete and the file so this
* situation won't cause an error. */
if (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return M_FS_ERROR_FILE_EXISTS;
}
if (cb) {
entry_size = M_fs_info_get_size(info);
M_fs_progress_set_path(progress, norm_path_new);
M_fs_progress_set_type(progress, M_fs_info_get_type(info));
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total(progress, entry_size);
M_fs_progress_set_size_total_progess(progress, entry_size);
}
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current(progress, entry_size);
M_fs_progress_set_size_current_progress(progress, entry_size);
}
/* Change the progress count to reflect the count. */
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count_total(progress, 1);
M_fs_progress_set_count(progress, 1);
}
}
/* Move the file. */
if (M_fs_info_get_type(info) == M_FS_TYPE_SYMLINK) {
res = M_fs_path_readlink(&resolve_path, norm_path_old);
if (res == M_FS_ERROR_SUCCESS) {
res = M_fs_symlink(norm_path_new, resolve_path);
}
M_free(resolve_path);
} else {
res = M_fs_move_file(norm_path_old, norm_path_new);
}
/* Failure was because we're crossing mount points. */
if (res == M_FS_ERROR_NOT_SAMEDEV) {
/* Can't rename so copy and delete. */
if (M_fs_copy(norm_path_old, norm_path_new, mode, cb, progress_flags) == M_FS_ERROR_SUCCESS) {
/* Success - Delete the original files since this is a move. */
res = M_fs_delete(norm_path_old, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);
} else {
/* Failure - Delete the new files that were copied but only if we are not overwriting. We don't
* want to remove any existing files (especially if the dest is a dir). */
if (!(mode & M_FS_FILE_MODE_OVERWRITE)) {
M_fs_delete(norm_path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);
}
res = M_FS_ERROR_GENERIC;
}
} else {
/* Call the cb with the result of the move whether it was a success for fail. We call the cb only if the
* result of the move is not M_FS_ERROR_NOT_SAMEDEV because the copy operation will call the cb for us. */
if (cb) {
M_fs_progress_set_result(progress, res);
if (!cb(progress)) {
res = M_FS_ERROR_CANCELED;
}
}
}
M_fs_info_destroy(info);
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data.
CWE ID: CWE-732 | M_fs_error_t M_fs_move(const char *path_old, const char *path_new, M_uint32 mode, M_fs_progress_cb_t cb, M_uint32 progress_flags)
{
char *norm_path_old;
char *norm_path_new;
char *resolve_path;
M_fs_info_t *info;
M_fs_progress_t *progress = NULL;
M_uint64 entry_size;
M_fs_error_t res;
if (path_old == NULL || *path_old == '\0' || path_new == NULL || *path_new == '\0') {
return M_FS_ERROR_INVALID;
}
/* It's okay if new path doesn't exist. */
res = M_fs_path_norm(&norm_path_new, path_new, M_FS_PATH_NORM_RESDIR, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
return res;
}
/* If a path is a file and the destination is a directory the file should be moved
* into the directory. E.g. /file.txt -> /dir = /dir/file.txt */
if (M_fs_isfileintodir(path_old, path_new, &norm_path_old)) {
M_free(norm_path_new);
res = M_fs_move(path_old, norm_path_old, mode, cb, progress_flags);
M_free(norm_path_old);
return res;
}
/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path
* existing to rename because any check we perform may not be true when rename is called. */
res = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
progress = M_fs_progress_create();
res = M_fs_info(&info, path_old, (mode & M_FS_FILE_MODE_PRESERVE_PERMS)?M_FS_PATH_INFO_FLAGS_NONE:M_FS_PATH_INFO_FLAGS_BASIC);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
/* There is a race condition where the path could not exist but be created between the exists check and calling
* rename to move the file but there isn't much we can do in this case. copy will delete and the file so this
* situation won't cause an error. */
if (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return M_FS_ERROR_FILE_EXISTS;
}
if (cb) {
entry_size = M_fs_info_get_size(info);
M_fs_progress_set_path(progress, norm_path_new);
M_fs_progress_set_type(progress, M_fs_info_get_type(info));
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total(progress, entry_size);
M_fs_progress_set_size_total_progess(progress, entry_size);
}
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current(progress, entry_size);
M_fs_progress_set_size_current_progress(progress, entry_size);
}
/* Change the progress count to reflect the count. */
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count_total(progress, 1);
M_fs_progress_set_count(progress, 1);
}
}
/* Move the file. */
if (M_fs_info_get_type(info) == M_FS_TYPE_SYMLINK) {
res = M_fs_path_readlink(&resolve_path, norm_path_old);
if (res == M_FS_ERROR_SUCCESS) {
res = M_fs_symlink(norm_path_new, resolve_path);
}
M_free(resolve_path);
} else {
res = M_fs_move_file(norm_path_old, norm_path_new);
}
/* Failure was because we're crossing mount points. */
if (res == M_FS_ERROR_NOT_SAMEDEV) {
/* Can't rename so copy and delete. */
if (M_fs_copy(norm_path_old, norm_path_new, mode, cb, progress_flags) == M_FS_ERROR_SUCCESS) {
/* Success - Delete the original files since this is a move. */
res = M_fs_delete(norm_path_old, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);
} else {
/* Failure - Delete the new files that were copied but only if we are not overwriting. We don't
* want to remove any existing files (especially if the dest is a dir). */
if (!(mode & M_FS_FILE_MODE_OVERWRITE)) {
M_fs_delete(norm_path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);
}
res = M_FS_ERROR_GENERIC;
}
} else {
/* Call the cb with the result of the move whether it was a success for fail. We call the cb only if the
* result of the move is not M_FS_ERROR_NOT_SAMEDEV because the copy operation will call the cb for us. */
if (cb) {
M_fs_progress_set_result(progress, res);
if (!cb(progress)) {
res = M_FS_ERROR_CANCELED;
}
}
}
M_fs_info_destroy(info);
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
| 169,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: virtual void ResetModel() {
last_pts_ = 0;
bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz;
frame_number_ = 0;
tot_frame_number_ = 0;
first_drop_ = 0;
num_drops_ = 0;
for (int i = 0; i < 3; ++i) {
bits_total_[i] = 0;
}
}
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 ResetModel() {
last_pts_ = 0;
bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz;
frame_number_ = 0;
tot_frame_number_ = 0;
first_drop_ = 0;
num_drops_ = 0;
// Denoiser is off by default.
denoiser_on_ = 0;
for (int i = 0; i < 3; ++i) {
bits_total_[i] = 0;
}
denoiser_offon_test_ = 0;
denoiser_offon_period_ = -1;
}
| 174,518 |
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(imageaffine)
{
zval *IM;
gdImagePtr src;
gdImagePtr dst;
gdRect rect;
gdRectPtr pRect = NULL;
zval *z_rect = NULL;
zval *z_affine;
zval **tmp;
double affine[6];
int i, nelems;
zval **zval_affine_elem = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd);
if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements");
RETURN_FALSE;
}
for (i = 0; i < nelems; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) {
switch (Z_TYPE_PP(zval_affine_elem)) {
case IS_LONG:
affine[i] = Z_LVAL_PP(zval_affine_elem);
break;
case IS_DOUBLE:
affine[i] = Z_DVAL_PP(zval_affine_elem);
break;
case IS_STRING:
convert_to_double_ex(zval_affine_elem);
affine[i] = Z_DVAL_PP(zval_affine_elem);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i);
RETURN_FALSE;
}
}
}
if (z_rect != NULL) {
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
convert_to_long_ex(tmp);
rect.x = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
convert_to_long_ex(tmp);
rect.y = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
convert_to_long_ex(tmp);
rect.width = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
convert_to_long_ex(tmp);
rect.height = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
pRect = ▭
} else {
rect.x = -1;
rect.y = -1;
rect.width = gdImageSX(src);
rect.height = gdImageSY(src);
pRect = NULL;
}
if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) {
RETURN_FALSE;
}
if (dst == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, dst, le_gd);
}
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189 | PHP_FUNCTION(imageaffine)
{
zval *IM;
gdImagePtr src;
gdImagePtr dst;
gdRect rect;
gdRectPtr pRect = NULL;
zval *z_rect = NULL;
zval *z_affine;
zval **tmp;
double affine[6];
int i, nelems;
zval **zval_affine_elem = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd);
if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements");
RETURN_FALSE;
}
for (i = 0; i < nelems; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) {
switch (Z_TYPE_PP(zval_affine_elem)) {
case IS_LONG:
affine[i] = Z_LVAL_PP(zval_affine_elem);
break;
case IS_DOUBLE:
affine[i] = Z_DVAL_PP(zval_affine_elem);
break;
case IS_STRING:
{
zval dval;
dval = **zval_affine_elem;
zval_copy_ctor(&dval);
convert_to_double(&dval);
affine[i] = Z_DVAL(dval);
}
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i);
RETURN_FALSE;
}
}
}
if (z_rect != NULL) {
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.x = Z_LVAL(lval);
} else {
rect.x = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.y = Z_LVAL(lval);
} else {
rect.y = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.width = Z_LVAL(lval);
} else {
rect.width = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.height = Z_LVAL(lval);
} else {
rect.height = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
pRect = ▭
} else {
rect.x = -1;
rect.y = -1;
rect.width = gdImageSX(src);
rect.height = gdImageSY(src);
pRect = NULL;
}
if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) {
RETURN_FALSE;
}
if (dst == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, dst, le_gd);
}
}
| 166,428 |
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 SyncTest::AddOptionalTypesToCommandLine(CommandLine* cl) {
if (!cl->HasSwitch(switches::kEnableSyncTabs))
cl->AppendSwitch(switches::kEnableSyncTabs);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void SyncTest::AddOptionalTypesToCommandLine(CommandLine* cl) {
| 170,789 |
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 UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
int value;
UINT error;
UINT32 ChannelId;
wStream* data_out;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"",
Sp,
cbChId, ChannelId);
if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error);
return error;
}
data_out = Stream_New(NULL, 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03);
Stream_Write_UINT8(data_out, value);
drdynvc_write_variable_uint(data_out, ChannelId);
error = drdynvc_send(drdynvc, data_out);
if (error)
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(error), error);
return error;
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID: | static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
int value;
UINT error;
UINT32 ChannelId;
wStream* data_out;
if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId))
return ERROR_INVALID_DATA;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"",
Sp,
cbChId, ChannelId);
if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error);
return error;
}
data_out = Stream_New(NULL, 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03);
Stream_Write_UINT8(data_out, value);
drdynvc_write_variable_uint(data_out, ChannelId);
error = drdynvc_send(drdynvc, data_out);
if (error)
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(error), error);
return error;
}
| 168,935 |
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 inline void VectorClamp(DDSVector4 *value)
{
value->x = MinF(1.0f,MaxF(0.0f,value->x));
value->y = MinF(1.0f,MaxF(0.0f,value->y));
value->z = MinF(1.0f,MaxF(0.0f,value->z));
value->w = MinF(1.0f,MaxF(0.0f,value->w));
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20 | static inline void VectorClamp(DDSVector4 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
value->w = MagickMin(1.0f,MagickMax(0.0f,value->w));
}
| 168,906 |
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 ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac,
struct ceph_authorizer *a, size_t len)
{
struct ceph_x_authorizer *au = (void *)a;
struct ceph_x_ticket_handler *th;
int ret = 0;
struct ceph_x_authorize_reply reply;
void *p = au->reply_buf;
void *end = p + sizeof(au->reply_buf);
th = get_ticket_handler(ac, au->service);
if (IS_ERR(th))
return PTR_ERR(th);
ret = ceph_x_decrypt(&th->session_key, &p, end, &reply, sizeof(reply));
if (ret < 0)
return ret;
if (ret != sizeof(reply))
return -EPERM;
if (au->nonce + 1 != le64_to_cpu(reply.nonce_plus_one))
ret = -EPERM;
else
ret = 0;
dout("verify_authorizer_reply nonce %llx got %llx ret %d\n",
au->nonce, le64_to_cpu(reply.nonce_plus_one), ret);
return ret;
}
Commit Message: libceph: do not hard code max auth ticket len
We hard code cephx auth ticket buffer size to 256 bytes. This isn't
enough for any moderate setups and, in case tickets themselves are not
encrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but
ceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the
buffer is allocated dynamically anyway, allocated it a bit later, at
the point where we know how much is going to be needed.
Fixes: http://tracker.ceph.com/issues/8979
Cc: [email protected]
Signed-off-by: Ilya Dryomov <[email protected]>
Reviewed-by: Sage Weil <[email protected]>
CWE ID: CWE-399 | static int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac,
struct ceph_authorizer *a, size_t len)
{
struct ceph_x_authorizer *au = (void *)a;
struct ceph_x_ticket_handler *th;
int ret = 0;
struct ceph_x_authorize_reply reply;
void *preply = &reply;
void *p = au->reply_buf;
void *end = p + sizeof(au->reply_buf);
th = get_ticket_handler(ac, au->service);
if (IS_ERR(th))
return PTR_ERR(th);
ret = ceph_x_decrypt(&th->session_key, &p, end, &preply, sizeof(reply));
if (ret < 0)
return ret;
if (ret != sizeof(reply))
return -EPERM;
if (au->nonce + 1 != le64_to_cpu(reply.nonce_plus_one))
ret = -EPERM;
else
ret = 0;
dout("verify_authorizer_reply nonce %llx got %llx ret %d\n",
au->nonce, le64_to_cpu(reply.nonce_plus_one), ret);
return ret;
}
| 166,264 |
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 Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/122
CWE ID: CWE-125 | static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
| 168,802 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.