instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
*flags = 0;
if( profile == NULL )
{
ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
goto exit;
}
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
}
exit:
if( ret != 0 )
{
*flags = (uint32_t) -1;
return( ret );
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
Commit Message: Only return VERIFY_FAILED from a single point
Everything else is a fatal error. Also improve documentation about that for
the vrfy callback.
CWE ID: CWE-287 | int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
*flags = 0;
if( profile == NULL )
{
ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
goto exit;
}
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
}
exit:
/* prevent misuse of the vrfy callback */
if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
ret = MBEDTLS_ERR_X509_FATAL_ERROR;
if( ret != 0 )
{
*flags = (uint32_t) -1;
return( ret );
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
| 170,019 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintJobWorker::GetSettingsWithUI(
int document_page_count,
bool has_selection,
bool is_scripted) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
#if defined(OS_ANDROID)
if (is_scripted) {
PrintingContextDelegate* printing_context_delegate =
static_cast<PrintingContextDelegate*>(printing_context_delegate_.get());
content::WebContents* web_contents =
printing_context_delegate->GetWebContents();
TabAndroid* tab =
web_contents ? TabAndroid::FromWebContents(web_contents) : nullptr;
if (tab)
tab->SetPendingPrint();
}
#endif
printing_context_->AskUserForSettings(
document_page_count, has_selection, is_scripted,
base::Bind(&PostOnOwnerThread, make_scoped_refptr(owner_),
base::Bind(&PrintJobWorker::GetSettingsDone,
weak_factory_.GetWeakPtr())));
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20 | void PrintJobWorker::GetSettingsWithUI(
int document_page_count,
bool has_selection,
bool is_scripted) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
PrintingContextDelegate* printing_context_delegate =
static_cast<PrintingContextDelegate*>(printing_context_delegate_.get());
content::WebContents* web_contents =
printing_context_delegate->GetWebContents();
#if defined(OS_ANDROID)
if (is_scripted) {
TabAndroid* tab =
web_contents ? TabAndroid::FromWebContents(web_contents) : nullptr;
if (tab)
tab->SetPendingPrint();
}
#endif
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (web_contents->IsFullscreenForCurrentTab())
web_contents->ExitFullscreen(true);
printing_context_->AskUserForSettings(
document_page_count, has_selection, is_scripted,
base::Bind(&PostOnOwnerThread, make_scoped_refptr(owner_),
base::Bind(&PrintJobWorker::GetSettingsDone,
weak_factory_.GetWeakPtr())));
}
| 172,313 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u", nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
Commit Message: fix build
Change-Id: I9bb8c659d3fc97a8e748451d82d0f3448faa242b
CWE ID: CWE-119 | bool SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u",
(unsigned long long)nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
| 173,414 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HostCache::clear() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
RecordEraseAll(ERASE_CLEAR, base::TimeTicks::Now());
entries_.clear();
}
Commit Message: Add PersistenceDelegate to HostCache
PersistenceDelegate is a new interface for persisting the contents of
the HostCache. This commit includes the interface itself, the logic in
HostCache for interacting with it, and a mock implementation of the
interface for testing. It does not include support for immediate data
removal since that won't be needed for the currently planned use case.
BUG=605149
Review-Url: https://codereview.chromium.org/2943143002
Cr-Commit-Position: refs/heads/master@{#481015}
CWE ID: | void HostCache::clear() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
RecordEraseAll(ERASE_CLEAR, base::TimeTicks::Now());
// Don't bother scheduling a write if there's nothing to clear.
if (size() == 0)
return;
entries_.clear();
if (delegate_)
delegate_->ScheduleWrite();
}
| 172,010 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GesturePoint::IsInsideManhattanSquare(const TouchEvent& event) const {
int manhattanDistance = abs(event.x() - first_touch_position_.x()) +
abs(event.y() - first_touch_position_.y());
return manhattanDistance < kMaximumTouchMoveInPixelsForClick;
}
Commit Message: Add setters for the aura gesture recognizer constants.
BUG=113227
TEST=none
Review URL: http://codereview.chromium.org/9372040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool GesturePoint::IsInsideManhattanSquare(const TouchEvent& event) const {
int manhattanDistance = abs(event.x() - first_touch_position_.x()) +
abs(event.y() - first_touch_position_.y());
return manhattanDistance <
GestureConfiguration::max_touch_move_in_pixels_for_click();
}
| 171,044 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: CompositedLayerRasterInvalidator::ChunkPropertiesChanged(
const RefCountedPropertyTreeState& new_chunk_state,
const PaintChunkInfo& new_chunk,
const PaintChunkInfo& old_chunk,
const PropertyTreeState& layer_state) const {
if (!ApproximatelyEqual(new_chunk.chunk_to_layer_transform,
old_chunk.chunk_to_layer_transform))
return PaintInvalidationReason::kPaintProperty;
if (new_chunk_state.Effect() != old_chunk.effect_state ||
new_chunk_state.Effect()->Changed(*layer_state.Effect()))
return PaintInvalidationReason::kPaintProperty;
if (new_chunk.chunk_to_layer_clip.IsTight() &&
old_chunk.chunk_to_layer_clip.IsTight()) {
if (new_chunk.chunk_to_layer_clip == old_chunk.chunk_to_layer_clip)
return PaintInvalidationReason::kNone;
if (ClipByLayerBounds(new_chunk.chunk_to_layer_clip.Rect()) ==
ClipByLayerBounds(old_chunk.chunk_to_layer_clip.Rect()))
return PaintInvalidationReason::kNone;
return PaintInvalidationReason::kIncremental;
}
if (new_chunk_state.Clip() != old_chunk.clip_state ||
new_chunk_state.Clip()->Changed(*layer_state.Clip()))
return PaintInvalidationReason::kPaintProperty;
return PaintInvalidationReason::kNone;
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | CompositedLayerRasterInvalidator::ChunkPropertiesChanged(
const PropertyTreeState& new_chunk_state,
const PaintChunkInfo& new_chunk,
const PaintChunkInfo& old_chunk,
const PropertyTreeState& layer_state) const {
if (!ApproximatelyEqual(new_chunk.chunk_to_layer_transform,
old_chunk.chunk_to_layer_transform))
return PaintInvalidationReason::kPaintProperty;
if (new_chunk_state.Effect() != old_chunk.effect_state ||
new_chunk_state.Effect()->Changed(*layer_state.Effect()))
return PaintInvalidationReason::kPaintProperty;
if (new_chunk.chunk_to_layer_clip.IsTight() &&
old_chunk.chunk_to_layer_clip.IsTight()) {
if (new_chunk.chunk_to_layer_clip == old_chunk.chunk_to_layer_clip)
return PaintInvalidationReason::kNone;
if (ClipByLayerBounds(new_chunk.chunk_to_layer_clip.Rect()) ==
ClipByLayerBounds(old_chunk.chunk_to_layer_clip.Rect()))
return PaintInvalidationReason::kNone;
return PaintInvalidationReason::kIncremental;
}
if (new_chunk_state.Clip() != old_chunk.clip_state ||
new_chunk_state.Clip()->Changed(*layer_state.Clip()))
return PaintInvalidationReason::kPaintProperty;
return PaintInvalidationReason::kNone;
}
| 171,810 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
void *data, struct drm_file *file_priv)
{
struct drm_clip_rect __user *clips_ptr;
struct drm_clip_rect *clips = NULL;
struct drm_mode_fb_dirty_cmd *r = data;
struct drm_mode_object *obj;
struct drm_framebuffer *fb;
unsigned flags;
int num_clips;
int ret = 0;
if (!drm_core_check_feature(dev, DRIVER_MODESET))
return -EINVAL;
mutex_lock(&dev->mode_config.mutex);
obj = drm_mode_object_find(dev, r->fb_id, DRM_MODE_OBJECT_FB);
if (!obj) {
DRM_ERROR("invalid framebuffer id\n");
ret = -EINVAL;
goto out_err1;
}
fb = obj_to_fb(obj);
num_clips = r->num_clips;
clips_ptr = (struct drm_clip_rect *)(unsigned long)r->clips_ptr;
if (!num_clips != !clips_ptr) {
ret = -EINVAL;
goto out_err1;
}
flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
/* If userspace annotates copy, clips must come in pairs */
if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
ret = -EINVAL;
goto out_err1;
}
if (num_clips && clips_ptr) {
clips = kzalloc(num_clips * sizeof(*clips), GFP_KERNEL);
if (!clips) {
ret = -ENOMEM;
goto out_err1;
}
ret = copy_from_user(clips, clips_ptr,
num_clips * sizeof(*clips));
if (ret) {
ret = -EFAULT;
goto out_err2;
}
}
if (fb->funcs->dirty) {
ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
clips, num_clips);
} else {
ret = -ENOSYS;
goto out_err2;
}
out_err2:
kfree(clips);
out_err1:
mutex_unlock(&dev->mode_config.mutex);
return ret;
}
Commit Message: drm: integer overflow in drm_mode_dirtyfb_ioctl()
There is a potential integer overflow in drm_mode_dirtyfb_ioctl()
if userspace passes in a large num_clips. The call to kmalloc would
allocate a small buffer, and the call to fb->funcs->dirty may result
in a memory corruption.
Reported-by: Haogang Chen <[email protected]>
Signed-off-by: Xi Wang <[email protected]>
Cc: [email protected]
Signed-off-by: Dave Airlie <[email protected]>
CWE ID: CWE-189 | int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
void *data, struct drm_file *file_priv)
{
struct drm_clip_rect __user *clips_ptr;
struct drm_clip_rect *clips = NULL;
struct drm_mode_fb_dirty_cmd *r = data;
struct drm_mode_object *obj;
struct drm_framebuffer *fb;
unsigned flags;
int num_clips;
int ret = 0;
if (!drm_core_check_feature(dev, DRIVER_MODESET))
return -EINVAL;
mutex_lock(&dev->mode_config.mutex);
obj = drm_mode_object_find(dev, r->fb_id, DRM_MODE_OBJECT_FB);
if (!obj) {
DRM_ERROR("invalid framebuffer id\n");
ret = -EINVAL;
goto out_err1;
}
fb = obj_to_fb(obj);
num_clips = r->num_clips;
clips_ptr = (struct drm_clip_rect *)(unsigned long)r->clips_ptr;
if (!num_clips != !clips_ptr) {
ret = -EINVAL;
goto out_err1;
}
flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
/* If userspace annotates copy, clips must come in pairs */
if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
ret = -EINVAL;
goto out_err1;
}
if (num_clips && clips_ptr) {
if (num_clips < 0 || num_clips > DRM_MODE_FB_DIRTY_MAX_CLIPS) {
ret = -EINVAL;
goto out_err1;
}
clips = kzalloc(num_clips * sizeof(*clips), GFP_KERNEL);
if (!clips) {
ret = -ENOMEM;
goto out_err1;
}
ret = copy_from_user(clips, clips_ptr,
num_clips * sizeof(*clips));
if (ret) {
ret = -EFAULT;
goto out_err2;
}
}
if (fb->funcs->dirty) {
ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
clips, num_clips);
} else {
ret = -ENOSYS;
goto out_err2;
}
out_err2:
kfree(clips);
out_err1:
mutex_unlock(&dev->mode_config.mutex);
return ret;
}
| 165,655 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltDocumentFunctionLoadDocument(xmlXPathParserContextPtr ctxt, xmlChar* URI)
{
xsltTransformContextPtr tctxt;
xmlURIPtr uri;
xmlChar *fragment;
xsltDocumentPtr idoc; /* document info */
xmlDocPtr doc;
xmlXPathContextPtr xptrctxt = NULL;
xmlXPathObjectPtr resObj = NULL;
tctxt = xsltXPathGetTransformContext(ctxt);
if (tctxt == NULL) {
xsltTransformError(NULL, NULL, NULL,
"document() : internal error tctxt == NULL\n");
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
return;
}
uri = xmlParseURI((const char *) URI);
if (uri == NULL) {
xsltTransformError(tctxt, NULL, NULL,
"document() : failed to parse URI\n");
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
return;
}
/*
* check for and remove fragment identifier
*/
fragment = (xmlChar *)uri->fragment;
if (fragment != NULL) {
xmlChar *newURI;
uri->fragment = NULL;
newURI = xmlSaveUri(uri);
idoc = xsltLoadDocument(tctxt, newURI);
xmlFree(newURI);
} else
idoc = xsltLoadDocument(tctxt, URI);
xmlFreeURI(uri);
if (idoc == NULL) {
if ((URI == NULL) ||
(URI[0] == '#') ||
((tctxt->style->doc != NULL) &&
(xmlStrEqual(tctxt->style->doc->URL, URI))))
{
/*
* This selects the stylesheet's doc itself.
*/
doc = tctxt->style->doc;
} else {
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
if (fragment != NULL)
xmlFree(fragment);
return;
}
} else
doc = idoc->doc;
if (fragment == NULL) {
valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr) doc));
return;
}
/* use XPointer of HTML location for fragment ID */
#ifdef LIBXML_XPTR_ENABLED
xptrctxt = xmlXPtrNewContext(doc, NULL, NULL);
if (xptrctxt == NULL) {
xsltTransformError(tctxt, NULL, NULL,
"document() : internal error xptrctxt == NULL\n");
goto out_fragment;
}
resObj = xmlXPtrEval(fragment, xptrctxt);
xmlXPathFreeContext(xptrctxt);
#endif
xmlFree(fragment);
if (resObj == NULL)
goto out_fragment;
switch (resObj->type) {
case XPATH_NODESET:
break;
case XPATH_UNDEFINED:
case XPATH_BOOLEAN:
case XPATH_NUMBER:
case XPATH_STRING:
case XPATH_POINT:
case XPATH_USERS:
case XPATH_XSLT_TREE:
case XPATH_RANGE:
case XPATH_LOCATIONSET:
xsltTransformError(tctxt, NULL, NULL,
"document() : XPointer does not select a node set: #%s\n",
fragment);
goto out_object;
}
valuePush(ctxt, resObj);
return;
out_object:
xmlXPathFreeObject(resObj);
out_fragment:
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltDocumentFunctionLoadDocument(xmlXPathParserContextPtr ctxt, xmlChar* URI)
{
xsltTransformContextPtr tctxt;
xmlURIPtr uri;
xmlChar *fragment;
xsltDocumentPtr idoc; /* document info */
xmlDocPtr doc;
xmlXPathContextPtr xptrctxt = NULL;
xmlXPathObjectPtr resObj = NULL;
tctxt = xsltXPathGetTransformContext(ctxt);
if (tctxt == NULL) {
xsltTransformError(NULL, NULL, NULL,
"document() : internal error tctxt == NULL\n");
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
return;
}
uri = xmlParseURI((const char *) URI);
if (uri == NULL) {
xsltTransformError(tctxt, NULL, NULL,
"document() : failed to parse URI\n");
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
return;
}
/*
* check for and remove fragment identifier
*/
fragment = (xmlChar *)uri->fragment;
if (fragment != NULL) {
xmlChar *newURI;
uri->fragment = NULL;
newURI = xmlSaveUri(uri);
idoc = xsltLoadDocument(tctxt, newURI);
xmlFree(newURI);
} else
idoc = xsltLoadDocument(tctxt, URI);
xmlFreeURI(uri);
if (idoc == NULL) {
if ((URI == NULL) ||
(URI[0] == '#') ||
((tctxt->style->doc != NULL) &&
(xmlStrEqual(tctxt->style->doc->URL, URI))))
{
/*
* This selects the stylesheet's doc itself.
*/
doc = tctxt->style->doc;
} else {
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
if (fragment != NULL)
xmlFree(fragment);
return;
}
} else
doc = idoc->doc;
if (fragment == NULL) {
valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr) doc));
return;
}
/* use XPointer of HTML location for fragment ID */
#ifdef LIBXML_XPTR_ENABLED
xptrctxt = xmlXPtrNewContext(doc, NULL, NULL);
if (xptrctxt == NULL) {
xsltTransformError(tctxt, NULL, NULL,
"document() : internal error xptrctxt == NULL\n");
goto out_fragment;
}
resObj = xmlXPtrEval(fragment, xptrctxt);
xmlXPathFreeContext(xptrctxt);
#endif
if (resObj == NULL)
goto out_fragment;
switch (resObj->type) {
case XPATH_NODESET:
break;
case XPATH_UNDEFINED:
case XPATH_BOOLEAN:
case XPATH_NUMBER:
case XPATH_STRING:
case XPATH_POINT:
case XPATH_USERS:
case XPATH_XSLT_TREE:
case XPATH_RANGE:
case XPATH_LOCATIONSET:
xsltTransformError(tctxt, NULL, NULL,
"document() : XPointer does not select a node set: #%s\n",
fragment);
goto out_object;
}
valuePush(ctxt, resObj);
xmlFree(fragment);
return;
out_object:
xmlXPathFreeObject(resObj);
out_fragment:
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
xmlFree(fragment);
}
| 173,301 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void * adminchild(struct clientparam* param) {
int i, res;
char * buf;
char username[256];
char *sb;
char *req = NULL;
struct printparam pp;
int contentlen = 0;
int isform = 0;
pp.inbuf = 0;
pp.cp = param;
buf = myalloc(LINESIZE);
if(!buf) {RETURN(555);}
i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]);
if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') &&
(buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/')))
{
RETURN(701);
}
buf[i] = 0;
sb = strchr(buf+5, ' ');
if(!sb){
RETURN(702);
}
*sb = 0;
req = mystrdup(buf + ((*buf == 'P')? 6 : 5));
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){
buf[i] = 0;
if(i > 19 && (!strncasecmp(buf, "authorization", 13))){
sb = strchr(buf, ':');
if(!sb)continue;
++sb;
while(isspace(*sb))sb++;
if(!*sb || strncasecmp(sb, "basic", 5)){
continue;
}
sb+=5;
while(isspace(*sb))sb++;
i = de64((unsigned char *)sb, (unsigned char *)username, 255);
if(i<=0)continue;
username[i] = 0;
sb = strchr((char *)username, ':');
if(sb){
*sb = 0;
if(param->password)myfree(param->password);
param->password = (unsigned char *)mystrdup(sb+1);
}
if(param->username) myfree(param->username);
param->username = (unsigned char *)mystrdup(username);
continue;
}
else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){
sb = buf + 15;
while(isspace(*sb))sb++;
contentlen = atoi(sb);
}
else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){
sb = buf + 13;
while(isspace(*sb))sb++;
if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1;
}
}
param->operation = ADMIN;
if(isform && contentlen) {
printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n");
stdpr(&pp, NULL, 0);
}
res = (*param->srv->authfunc)(param);
if(res && res != 10) {
printstr(&pp, authreq);
RETURN(res);
}
if(param->srv->singlepacket || param->redirected){
if(*req == 'C') req[1] = 0;
else *req = 0;
}
sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:"");
if(*req != 'S') printstr(&pp, buf);
switch(*req){
case 'C':
printstr(&pp, counters);
{
struct trafcount *cp;
int num = 0;
for(cp = conf.trafcounter; cp; cp = cp->next, num++){
int inbuf = 0;
if(cp->ace && (param->srv->singlepacket || param->redirected)){
if(!ACLmatches(cp->ace, param))continue;
}
if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0;
if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1;
inbuf += sprintf(buf, "<tr>"
"<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>",
(cp->comment)?cp->comment:" ",
(cp->disabled)?'S':'D',
num,
(cp->disabled)?"NO":"YES"
);
if(!cp->ace || !cp->ace->users){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->src){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->dst){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->ports){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n");
}
if(cp->type == NONE) {
inbuf += sprintf(buf+inbuf,
"</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n"
);
}
else {
inbuf += sprintf(buf+inbuf,
"</td><td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>MB%s</td>"
"<td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>%s</td>",
cp->traflim64 / (1024 * 1024),
rotations[cp->type],
cp->traf64,
cp->cleared?ctime(&cp->cleared):"never"
);
inbuf += sprintf(buf + inbuf,
"<td>%s</td>"
"<td>%i</td>"
"</tr>\r\n",
cp->updated?ctime(&cp->updated):"never",
cp->number
);
}
printstr(&pp, buf);
}
}
printstr(&pp, counterstail);
break;
case 'R':
conf.needreload = 1;
printstr(&pp, "<h3>Reload scheduled</h3>");
break;
case 'S':
{
if(req[1] == 'X'){
printstr(&pp, style);
break;
}
printstr(&pp, xml);
printval(conf.services, TYPE_SERVER, 0, &pp);
printstr(&pp, postxml);
}
break;
case 'F':
{
FILE *fp;
char buf[256];
fp = confopen();
if(!fp){
printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>");
break;
}
printstr(&pp, "<h3>Please be careful editing config file remotely</h3>");
printstr(&pp, "<form method=\"POST\" action=\"/U\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">");
while(fgets(buf, 256, fp)){
printstr(&pp, buf);
}
if(!writable) fclose(fp);
printstr(&pp, "</textarea><br><input type=\"Submit\"></form>");
break;
}
case 'U':
{
int l=0;
int error = 0;
if(!writable || fseek(writable, 0, 0)){
error = 1;
}
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '+', conf.timeouts[STRING_S])) > 0){
if(i > (contentlen - l)) i = (contentlen - l);
buf[i] = 0;
if(!l){
if(strncasecmp(buf, "conffile=", 9)) error = 1;
}
if(!error){
decodeurl((unsigned char *)buf, 1);
fprintf(writable, "%s", l? buf : buf + 9);
}
l += i;
if(l >= contentlen) break;
}
if(writable && !error){
fflush(writable);
#ifndef _WINCE
ftruncate(fileno(writable), ftell(writable));
#endif
}
printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file":
"<h3>Configuration updated</h3>");
}
break;
default:
printstr(&pp, (char *)conf.stringtable[WEBBANNERS]);
break;
}
if(*req != 'S') printstr(&pp, tail);
CLEANRET:
printstr(&pp, NULL);
if(buf) myfree(buf);
(*param->srv->logfunc)(param, (unsigned char *)req);
if(req)myfree(req);
freeparam(param);
return (NULL);
}
Commit Message: Fix: out-of-bounds write and few more bugs in 'admin' configuration upload
CWE ID: CWE-787 | void * adminchild(struct clientparam* param) {
int i, res;
char * buf;
char username[256];
char *sb;
char *req = NULL;
struct printparam pp;
unsigned contentlen = 0;
int isform = 0;
pp.inbuf = 0;
pp.cp = param;
buf = myalloc(LINESIZE);
if(!buf) {RETURN(555);}
i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]);
if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') &&
(buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/')))
{
RETURN(701);
}
buf[i] = 0;
sb = strchr(buf+5, ' ');
if(!sb){
RETURN(702);
}
*sb = 0;
req = mystrdup(buf + ((*buf == 'P')? 6 : 5));
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){
buf[i] = 0;
if(i > 19 && (!strncasecmp(buf, "authorization", 13))){
sb = strchr(buf, ':');
if(!sb)continue;
++sb;
while(isspace(*sb))sb++;
if(!*sb || strncasecmp(sb, "basic", 5)){
continue;
}
sb+=5;
while(isspace(*sb))sb++;
i = de64((unsigned char *)sb, (unsigned char *)username, 255);
if(i<=0)continue;
username[i] = 0;
sb = strchr((char *)username, ':');
if(sb){
*sb = 0;
if(param->password)myfree(param->password);
param->password = (unsigned char *)mystrdup(sb+1);
}
if(param->username) myfree(param->username);
param->username = (unsigned char *)mystrdup(username);
continue;
}
else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){
sb = buf + 15;
while(isspace(*sb))sb++;
sscanf(sb, "%u", &contentlen);
if(contentlen > LINESIZE*1024) contentlen = 0;
}
else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){
sb = buf + 13;
while(isspace(*sb))sb++;
if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1;
}
}
param->operation = ADMIN;
if(isform && contentlen) {
printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n");
stdpr(&pp, NULL, 0);
}
res = (*param->srv->authfunc)(param);
if(res && res != 10) {
printstr(&pp, authreq);
RETURN(res);
}
if(param->srv->singlepacket || param->redirected){
if(*req == 'C') req[1] = 0;
else *req = 0;
}
sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:"");
if(*req != 'S') printstr(&pp, buf);
switch(*req){
case 'C':
printstr(&pp, counters);
{
struct trafcount *cp;
int num = 0;
for(cp = conf.trafcounter; cp; cp = cp->next, num++){
int inbuf = 0;
if(cp->ace && (param->srv->singlepacket || param->redirected)){
if(!ACLmatches(cp->ace, param))continue;
}
if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0;
if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1;
inbuf += sprintf(buf, "<tr>"
"<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>",
(cp->comment)?cp->comment:" ",
(cp->disabled)?'S':'D',
num,
(cp->disabled)?"NO":"YES"
);
if(!cp->ace || !cp->ace->users){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->src){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->dst){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->ports){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n");
}
if(cp->type == NONE) {
inbuf += sprintf(buf+inbuf,
"</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n"
);
}
else {
inbuf += sprintf(buf+inbuf,
"</td><td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>MB%s</td>"
"<td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>%s</td>",
cp->traflim64 / (1024 * 1024),
rotations[cp->type],
cp->traf64,
cp->cleared?ctime(&cp->cleared):"never"
);
inbuf += sprintf(buf + inbuf,
"<td>%s</td>"
"<td>%i</td>"
"</tr>\r\n",
cp->updated?ctime(&cp->updated):"never",
cp->number
);
}
printstr(&pp, buf);
}
}
printstr(&pp, counterstail);
break;
case 'R':
conf.needreload = 1;
printstr(&pp, "<h3>Reload scheduled</h3>");
break;
case 'S':
{
if(req[1] == 'X'){
printstr(&pp, style);
break;
}
printstr(&pp, xml);
printval(conf.services, TYPE_SERVER, 0, &pp);
printstr(&pp, postxml);
}
break;
case 'F':
{
FILE *fp;
char buf[256];
fp = confopen();
if(!fp){
printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>");
break;
}
printstr(&pp, "<h3>Please be careful editing config file remotely</h3>");
printstr(&pp, "<form method=\"POST\" action=\"/U\" enctype=\"application/x-www-form-urlencoded\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">");
while(fgets(buf, 256, fp)){
printstr(&pp, buf);
}
if(!writable) fclose(fp);
printstr(&pp, "</textarea><br><input type=\"Submit\"></form>");
break;
}
case 'U':
{
unsigned l=0;
int error = 0;
if(!writable || !contentlen || fseek(writable, 0, 0)){
error = 1;
}
while(l < contentlen && (i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, (contentlen - l) > LINESIZE - 1?LINESIZE - 1:contentlen - l, '+', conf.timeouts[STRING_S])) > 0){
if(i > (contentlen - l)) i = (contentlen - l);
if(!l){
if(i<9 || strncasecmp(buf, "conffile=", 9)) error = 1;
}
if(!error){
buf[i] = 0;
decodeurl((unsigned char *)buf, 1);
fprintf(writable, "%s", l? buf : buf + 9);
}
l += i;
}
if(writable && !error){
fflush(writable);
#ifndef _WINCE
ftruncate(fileno(writable), ftell(writable));
#endif
}
printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file":
"<h3>Configuration updated</h3>");
}
break;
default:
printstr(&pp, (char *)conf.stringtable[WEBBANNERS]);
break;
}
if(*req != 'S') printstr(&pp, tail);
CLEANRET:
printstr(&pp, NULL);
if(buf) myfree(buf);
(*param->srv->logfunc)(param, (unsigned char *)req);
if(req)myfree(req);
freeparam(param);
return (NULL);
}
| 169,580 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: explicit ElementsAccessorBase(const char* name)
: ElementsAccessor(name) { }
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704 | explicit ElementsAccessorBase(const char* name)
| 174,095 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert4(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
d* (tod(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert4();
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert4(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
d* (tod(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert4();
return JSValue::encode(jsUndefined());
}
| 170,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened(
const ClientOAuthResult& result,
Profile* profile,
Profile::CreateStatus status) {
if (is_force_sign_in_with_usermanager_)
UnlockProfileAndHideLoginUI(profile_->GetPath(), handler_.get());
Browser* browser = NULL;
if (handler_) {
browser = handler_->GetDesktopBrowser();
}
AboutSigninInternals* about_signin_internals =
AboutSigninInternalsFactory::GetForProfile(profile_);
about_signin_internals->OnRefreshTokenReceived("Successful");
std::string account_id =
AccountTrackerServiceFactory::GetForProfile(profile_)
->SeedAccountInfo(gaia_id_, email_);
signin_metrics::AccessPoint access_point =
signin::GetAccessPointForPromoURL(current_url_);
signin_metrics::Reason reason =
signin::GetSigninReasonForPromoURL(current_url_);
SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_);
std::string primary_email =
signin_manager->GetAuthenticatedAccountInfo().email;
if (gaia::AreEmailsSame(email_, primary_email) &&
(reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
reason == signin_metrics::Reason::REASON_UNLOCK) &&
!password_.empty() && profiles::IsLockAvailable(profile_)) {
LocalAuth::SetLocalAuthCredentials(profile_, password_);
}
#if defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED)
if (!password_.empty()) {
scoped_refptr<password_manager::PasswordStore> password_store =
PasswordStoreFactory::GetForProfile(profile_,
ServiceAccessType::EXPLICIT_ACCESS);
if (password_store && !primary_email.empty()) {
password_store->SaveGaiaPasswordHash(
primary_email, base::UTF8ToUTF16(password_),
password_manager::metrics_util::SyncPasswordHashChange::
SAVED_ON_CHROME_SIGNIN);
}
}
#endif
if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
reason == signin_metrics::Reason::REASON_UNLOCK ||
reason == signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT) {
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->
UpdateCredentials(account_id, result.refresh_token);
if (signin::IsAutoCloseEnabledInURL(current_url_)) {
bool show_account_management = ShouldShowAccountManagement(
current_url_,
AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile_));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&InlineLoginHandlerImpl::CloseTab, handler_,
show_account_management));
}
if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
reason == signin_metrics::Reason::REASON_UNLOCK) {
signin_manager->MergeSigninCredentialIntoCookieJar();
}
LogSigninReason(reason);
} else {
browser_sync::ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile_);
SigninErrorController* error_controller =
SigninErrorControllerFactory::GetForProfile(profile_);
OneClickSigninSyncStarter::StartSyncMode start_mode =
OneClickSigninSyncStarter::CONFIRM_SYNC_SETTINGS_FIRST;
if (access_point == signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS ||
choose_what_to_sync_) {
bool show_settings_without_configure =
error_controller->HasError() && sync_service &&
sync_service->IsFirstSetupComplete();
if (!show_settings_without_configure)
start_mode = OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST;
}
OneClickSigninSyncStarter::ConfirmationRequired confirmation_required =
confirm_untrusted_signin_ ?
OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN :
OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
bool start_signin = !HandleCrossAccountError(
result.refresh_token, confirmation_required, start_mode);
if (start_signin) {
CreateSyncStarter(browser, current_url_, result.refresh_token,
OneClickSigninSyncStarter::CURRENT_PROFILE, start_mode,
confirmation_required);
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}
}
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened(
const ClientOAuthResult& result,
Profile* profile,
Profile::CreateStatus status) {
if (is_force_sign_in_with_usermanager_)
UnlockProfileAndHideLoginUI(profile_->GetPath(), handler_.get());
Browser* browser = NULL;
if (handler_) {
browser = handler_->GetDesktopBrowser();
}
AboutSigninInternals* about_signin_internals =
AboutSigninInternalsFactory::GetForProfile(profile_);
about_signin_internals->OnRefreshTokenReceived("Successful");
std::string account_id =
AccountTrackerServiceFactory::GetForProfile(profile_)
->SeedAccountInfo(gaia_id_, email_);
signin_metrics::AccessPoint access_point =
signin::GetAccessPointForPromoURL(current_url_);
signin_metrics::Reason reason =
signin::GetSigninReasonForPromoURL(current_url_);
SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_);
std::string primary_email =
signin_manager->GetAuthenticatedAccountInfo().email;
if (gaia::AreEmailsSame(email_, primary_email) &&
(reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
reason == signin_metrics::Reason::REASON_UNLOCK) &&
!password_.empty() && profiles::IsLockAvailable(profile_)) {
LocalAuth::SetLocalAuthCredentials(profile_, password_);
}
#if defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED)
if (!password_.empty()) {
scoped_refptr<password_manager::PasswordStore> password_store =
PasswordStoreFactory::GetForProfile(profile_,
ServiceAccessType::EXPLICIT_ACCESS);
if (password_store && !primary_email.empty()) {
password_store->SaveGaiaPasswordHash(
primary_email, base::UTF8ToUTF16(password_),
password_manager::metrics_util::SyncPasswordHashChange::
SAVED_ON_CHROME_SIGNIN);
}
}
#endif
if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
reason == signin_metrics::Reason::REASON_UNLOCK ||
reason == signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT) {
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
->UpdateCredentials(account_id, result.refresh_token,
signin_metrics::SourceForRefreshTokenOperation::
kInlineLoginHandler_Signin);
if (signin::IsAutoCloseEnabledInURL(current_url_)) {
bool show_account_management = ShouldShowAccountManagement(
current_url_,
AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile_));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&InlineLoginHandlerImpl::CloseTab, handler_,
show_account_management));
}
if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
reason == signin_metrics::Reason::REASON_UNLOCK) {
signin_manager->MergeSigninCredentialIntoCookieJar();
}
LogSigninReason(reason);
} else {
browser_sync::ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile_);
SigninErrorController* error_controller =
SigninErrorControllerFactory::GetForProfile(profile_);
OneClickSigninSyncStarter::StartSyncMode start_mode =
OneClickSigninSyncStarter::CONFIRM_SYNC_SETTINGS_FIRST;
if (access_point == signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS ||
choose_what_to_sync_) {
bool show_settings_without_configure =
error_controller->HasError() && sync_service &&
sync_service->IsFirstSetupComplete();
if (!show_settings_without_configure)
start_mode = OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST;
}
OneClickSigninSyncStarter::ConfirmationRequired confirmation_required =
confirm_untrusted_signin_ ?
OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN :
OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
bool start_signin = !HandleCrossAccountError(
result.refresh_token, confirmation_required, start_mode);
if (start_signin) {
CreateSyncStarter(browser, current_url_, result.refresh_token,
OneClickSigninSyncStarter::CURRENT_PROFILE, start_mode,
confirmation_required);
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}
}
}
| 172,575 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf,
RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da,
size_t offset, const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7);
ut64 abbr_code;
size_t i;
if (cu->hdr.length > debug_str_len) {
return NULL;
}
while (buf && buf < buf_end && buf >= obuf) {
if (cu->length && cu->capacity == cu->length) {
r_bin_dwarf_expand_cu (cu);
}
buf = r_uleb128 (buf, buf_end - buf, &abbr_code);
if (abbr_code > da->length || !buf) {
return NULL;
}
r_bin_dwarf_init_die (&cu->dies[cu->length]);
if (!abbr_code) {
cu->dies[cu->length].abbrev_code = 0;
cu->length++;
buf++;
continue;
}
cu->dies[cu->length].abbrev_code = abbr_code;
cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag;
abbr_code += offset;
if (da->capacity < abbr_code) {
return NULL;
}
for (i = 0; i < da->decls[abbr_code - 1].length; i++) {
if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) {
r_bin_dwarf_expand_die (&cu->dies[cu->length]);
}
if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) {
eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n");
break;
}
memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i]));
buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf,
&da->decls[abbr_code - 1].specs[i],
&cu->dies[cu->length].attr_values[i],
&cu->hdr, debug_str, debug_str_len);
if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) {
const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string;
sdb_set (s, "DW_AT_comp_dir", name, 0);
}
cu->dies[cu->length].length++;
}
cu->length++;
}
return buf;
}
Commit Message: Fix #10465 - Avoid string on low addresses (workaround) for corrupted dwarf
CWE ID: CWE-119 | static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf,
RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da,
size_t offset, const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7);
ut64 abbr_code;
size_t i;
if (cu->hdr.length > debug_str_len) {
return NULL;
}
while (buf && buf < buf_end && buf >= obuf) {
if (cu->length && cu->capacity == cu->length) {
r_bin_dwarf_expand_cu (cu);
}
buf = r_uleb128 (buf, buf_end - buf, &abbr_code);
if (abbr_code > da->length || !buf) {
return NULL;
}
r_bin_dwarf_init_die (&cu->dies[cu->length]);
if (!abbr_code) {
cu->dies[cu->length].abbrev_code = 0;
cu->length++;
buf++;
continue;
}
cu->dies[cu->length].abbrev_code = abbr_code;
cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag;
abbr_code += offset;
if (da->capacity < abbr_code) {
return NULL;
}
for (i = 0; i < da->decls[abbr_code - 1].length; i++) {
if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) {
r_bin_dwarf_expand_die (&cu->dies[cu->length]);
}
if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) {
eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n");
break;
}
memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i]));
buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf,
&da->decls[abbr_code - 1].specs[i],
&cu->dies[cu->length].attr_values[i],
&cu->hdr, debug_str, debug_str_len);
if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) {
const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string;
if (name > 1024) { // solve some null derefs
sdb_set (s, "DW_AT_comp_dir", name, 0);
} else {
eprintf ("Invalid string pointer at %p\n", name);
}
}
cu->dies[cu->length].length++;
}
cu->length++;
}
return buf;
}
| 169,150 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int amd_gpio_remove(struct platform_device *pdev)
{
struct amd_gpio *gpio_dev;
gpio_dev = platform_get_drvdata(pdev);
gpiochip_remove(&gpio_dev->gc);
pinctrl_unregister(gpio_dev->pctrl);
return 0;
}
Commit Message: pinctrl/amd: Drop pinctrl_unregister for devm_ registered device
It's not necessary to unregister pin controller device registered
with devm_pinctrl_register() and using pinctrl_unregister() leads
to a double free.
Fixes: 3bfd44306c65 ("pinctrl: amd: Add support for additional GPIO")
Signed-off-by: Wei Yongjun <[email protected]>
Signed-off-by: Linus Walleij <[email protected]>
CWE ID: CWE-415 | static int amd_gpio_remove(struct platform_device *pdev)
{
struct amd_gpio *gpio_dev;
gpio_dev = platform_get_drvdata(pdev);
gpiochip_remove(&gpio_dev->gc);
return 0;
}
| 169,419 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Track::EOSBlock::EOSBlock() :
BlockEntry(NULL, LONG_MIN)
{
}
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 | Track::EOSBlock::EOSBlock() :
| 174,272 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CCLayerTreeHostTest::endTest()
{
if (!isMainThread())
CCMainThread::postTask(createMainThreadTask(this, &CCLayerTreeHostTest::endTest));
else {
if (m_beginning)
m_endWhenBeginReturns = true;
else
onEndTest(static_cast<void*>(this));
}
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void CCLayerTreeHostTest::endTest()
{
if (!isMainThread())
m_mainThreadProxy->postTask(createMainThreadTask(this, &CCLayerTreeHostTest::endTest));
else {
if (m_beginning)
m_endWhenBeginReturns = true;
else
onEndTest(static_cast<void*>(this));
}
}
| 170,293 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_sd_count_referred(Jbig2Ctx *ctx, Jbig2Segment *segment)
{
int index;
Jbig2Segment *rsegment;
int n_dicts = 0;
for (index = 0; index < segment->referred_to_segment_count; index++) {
rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]);
if (rsegment && ((rsegment->flags & 63) == 0) &&
rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL))
n_dicts++;
}
return (n_dicts);
}
Commit Message:
CWE ID: CWE-119 | jbig2_sd_count_referred(Jbig2Ctx *ctx, Jbig2Segment *segment)
{
int index;
Jbig2Segment *rsegment;
uint32_t n_dicts = 0;
for (index = 0; index < segment->referred_to_segment_count; index++) {
rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]);
if (rsegment && ((rsegment->flags & 63) == 0) &&
rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL))
n_dicts++;
}
return (n_dicts);
}
| 165,500 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int SoundPool::load(const char* path, int priority __unused)
{
ALOGV("load: path=%s, priority=%d", path, priority);
Mutex::Autolock lock(&mLock);
sp<Sample> sample = new Sample(++mNextSampleID, path);
mSamples.add(sample->sampleID(), sample);
doLoad(sample);
return sample->sampleID();
}
Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread
Sample decoding still occurs in SoundPoolThread
without holding the SoundPool lock.
Bug: 25781119
Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8
CWE ID: CWE-264 | int SoundPool::load(const char* path, int priority __unused)
{
ALOGV("load: path=%s, priority=%d", path, priority);
int sampleID;
{
Mutex::Autolock lock(&mLock);
sampleID = ++mNextSampleID;
sp<Sample> sample = new Sample(sampleID, path);
mSamples.add(sampleID, sample);
sample->startLoad();
}
// mDecodeThread->loadSample() must be called outside of mLock.
// mDecodeThread->loadSample() may block on mDecodeThread message queue space;
// the message queue emptying may block on SoundPool::findSample().
//
// It theoretically possible that sample loads might decode out-of-order.
mDecodeThread->loadSample(sampleID);
return sampleID;
}
| 173,961 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> setValueAndClosePopupCallback(const v8::Arguments& args)
{
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
DOMWindow* imp = V8DOMWindow::toNative(args.Data()->ToObject());
EXCEPTION_BLOCK(int, intValue, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, stringValue, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
DOMWindowPagePopup::setValueAndClosePopup(imp, intValue, stringValue);
return v8::Undefined();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> setValueAndClosePopupCallback(const v8::Arguments& args)
{
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
DOMWindow* imp = V8DOMWindow::toNative(args.Data()->ToObject());
EXCEPTION_BLOCK(int, intValue, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, stringValue, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
DOMWindowPagePopup::setValueAndClosePopup(imp, intValue, stringValue);
return v8::Undefined();
}
| 171,109 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TabletModeWindowManager::Shutdown() {
base::flat_map<aura::Window*, WindowStateType> windows_in_splitview =
GetCarryOverWindowsInSplitView();
SplitViewController* split_view_controller =
Shell::Get()->split_view_controller();
if (split_view_controller->InSplitViewMode()) {
OverviewController* overview_controller =
Shell::Get()->overview_controller();
if (!overview_controller->InOverviewSession() ||
overview_controller->overview_session()->IsEmpty()) {
Shell::Get()->split_view_controller()->EndSplitView(
SplitViewController::EndReason::kExitTabletMode);
overview_controller->EndOverview();
}
}
for (aura::Window* window : added_windows_)
window->RemoveObserver(this);
added_windows_.clear();
Shell::Get()->RemoveShellObserver(this);
Shell::Get()->session_controller()->RemoveObserver(this);
Shell::Get()->overview_controller()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
RemoveWindowCreationObservers();
ScopedObserveWindowAnimation scoped_observe(GetTopWindow(), this,
/*exiting_tablet_mode=*/true);
ArrangeWindowsForClamshellMode(windows_in_splitview);
}
Commit Message: Fix the crash after clamshell -> tablet transition in overview mode.
This CL just reverted some changes that were made in
https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In
that CL, we changed the clamshell <-> tablet transition when clamshell
split view mode is enabled, however, we should keep the old behavior
unchanged if the feature is not enabled, i.e., overview should be ended
if it's active before the transition. Otherwise, it will cause a nullptr
dereference crash since |split_view_drag_indicators_| is not created in
clamshell overview and will be used in tablet overview.
Bug: 982507
Change-Id: I238fe9472648a446cff4ab992150658c228714dd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679306}
CWE ID: CWE-362 | void TabletModeWindowManager::Shutdown() {
base::flat_map<aura::Window*, WindowStateType> carryover_windows_in_splitview;
const bool was_in_overview =
Shell::Get()->overview_controller()->InOverviewSession();
// If clamshell split view mode is not enabled, still keep the old behavior:
// End overview if overview is active and restore all windows' window states
// to their previous window states.
if (!IsClamshellSplitViewModeEnabled()) {
Shell::Get()->overview_controller()->EndOverview();
} else {
// If clamshell split view mode is enabled, there are 4 cases when exiting
// tablet mode:
// 1) overview is active but split view is inactive: keep overview active in
// clamshell mode.
// 2) overview and splitview are both active: keep overview and splitview
// both
// active in clamshell mode, unless if it's single split state, splitview
// and overview will both be ended.
// 3) overview is inactive but split view is active (two snapped windows):
// split view is no longer active. But the two snapped windows will still
// keep snapped in clamshell mode.
// 4) overview and splitview are both inactive: keep the current behavior,
// i.e., restore all windows to its window state before entering tablet
// mode.
// TODO(xdai): Instead of caching snapped windows and their state here, we
// should try to see if it can be done in the WindowState::State impl.
carryover_windows_in_splitview = GetCarryOverWindowsInSplitView();
// For case 2 and 3: End splitview mode for two snapped windows case or
// single split case to match the clamshell split view behavior. (there is
// no both snapped state or single split state in clamshell split view). The
// windows will still be kept snapped though.
SplitViewController* split_view_controller =
Shell::Get()->split_view_controller();
if (split_view_controller->InSplitViewMode()) {
OverviewController* overview_controller =
Shell::Get()->overview_controller();
if (!overview_controller->InOverviewSession() ||
overview_controller->overview_session()->IsEmpty()) {
Shell::Get()->split_view_controller()->EndSplitView(
SplitViewController::EndReason::kExitTabletMode);
overview_controller->EndOverview();
}
}
}
for (aura::Window* window : added_windows_)
window->RemoveObserver(this);
added_windows_.clear();
Shell::Get()->RemoveShellObserver(this);
Shell::Get()->session_controller()->RemoveObserver(this);
Shell::Get()->overview_controller()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
RemoveWindowCreationObservers();
ScopedObserveWindowAnimation scoped_observe(GetTopWindow(), this,
/*exiting_tablet_mode=*/true);
ArrangeWindowsForClamshellMode(carryover_windows_in_splitview,
was_in_overview);
}
| 172,402 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
{
EVP_CIPHER_CTX *ds;
size_t reclen[SSL_MAX_PIPELINES];
unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
int bs, i, j, k, pad = 0, ret, mac_size = 0;
const EVP_CIPHER *enc;
unsigned int ctr;
if (send) {
if (EVP_MD_CTX_md(s->write_hash)) {
int n = EVP_MD_CTX_size(s->write_hash);
OPENSSL_assert(n >= 0);
}
ds = s->enc_write_ctx;
if (s->enc_write_ctx == NULL)
enc = NULL;
else {
int ivlen;
enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
/* For TLSv1.1 and later explicit IV */
if (SSL_USE_EXPLICIT_IV(s)
&& EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
ivlen = EVP_CIPHER_iv_length(enc);
else
ivlen = 0;
if (ivlen > 1) {
for (ctr = 0; ctr < n_recs; ctr++) {
if (recs[ctr].data != recs[ctr].input) {
/*
* we can't write into the input stream: Can this ever
* happen?? (steve)
*/
SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
return -1;
} else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
return -1;
}
}
}
}
} else {
if (EVP_MD_CTX_md(s->read_hash)) {
int n = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(n >= 0);
}
ds = s->enc_read_ctx;
if (s->enc_read_ctx == NULL)
enc = NULL;
else
enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
}
if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
for (ctr = 0; ctr < n_recs; ctr++) {
memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
recs[ctr].input = recs[ctr].data;
}
ret = 1;
} else {
bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
if (n_recs > 1) {
if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_PIPELINE)) {
/*
* We shouldn't have been called with pipeline data if the
* cipher doesn't support pipelining
*/
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
return -1;
}
}
for (ctr = 0; ctr < n_recs; ctr++) {
reclen[ctr] = recs[ctr].length;
if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_AEAD_CIPHER) {
unsigned char *seq;
seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
: RECORD_LAYER_get_read_sequence(&s->rlayer);
if (SSL_IS_DTLS(s)) {
/* DTLS does not support pipelining */
unsigned char dtlsseq[9], *p = dtlsseq;
s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
memcpy(p, &seq[2], 6);
memcpy(buf[ctr], dtlsseq, 8);
} else {
memcpy(buf[ctr], seq, 8);
for (i = 7; i >= 0; i--) { /* increment */
++seq[i];
if (seq[i] != 0)
break;
}
}
buf[ctr][8] = recs[ctr].type;
buf[ctr][9] = (unsigned char)(s->version >> 8);
buf[ctr][10] = (unsigned char)(s->version);
buf[ctr][11] = recs[ctr].length >> 8;
buf[ctr][12] = recs[ctr].length & 0xff;
pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
if (pad <= 0)
return -1;
if (send) {
reclen[ctr] += pad;
recs[ctr].length += pad;
}
} else if ((bs != 1) && send) {
i = bs - ((int)reclen[ctr] % bs);
/* Add weird padding of upto 256 bytes */
/* we need to add 'i' padding bytes of value j */
j = i - 1;
for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
recs[ctr].input[k] = j;
reclen[ctr] += i;
recs[ctr].length += i;
}
if (!send) {
if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
return 0;
}
}
if (n_recs > 1) {
unsigned char *data[SSL_MAX_PIPELINES];
/* Set the output buffers */
for (ctr = 0; ctr < n_recs; ctr++) {
data[ctr] = recs[ctr].data;
}
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
n_recs, data) <= 0) {
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
}
/* Set the input buffers */
for (ctr = 0; ctr < n_recs; ctr++) {
data[ctr] = recs[ctr].input;
}
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
n_recs, data) <= 0
|| EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
n_recs, reclen) <= 0) {
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
return -1;
}
}
i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_CUSTOM_CIPHER)
? (i < 0)
: (i == 0))
return -1; /* AEAD can fail to verify MAC */
if (send == 0) {
if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
}
} else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
}
}
}
ret = 1;
if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
mac_size = EVP_MD_CTX_size(s->read_hash);
if ((bs != 1) && !send) {
int tmpret;
for (ctr = 0; ctr < n_recs; ctr++) {
tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
/*
* If tmpret == 0 then this means publicly invalid so we can
* short circuit things here. Otherwise we must respect constant
* time behaviour.
*/
if (tmpret == 0)
return 0;
ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
ret, -1);
}
}
if (pad && !send) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].length -= pad;
}
}
}
return ret;
}
Commit Message: Don't change the state of the ETM flags until CCS processing
Changing the ciphersuite during a renegotiation can result in a crash
leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS
so this is TLS only.
The problem is caused by changing the flag indicating whether to use ETM
or not immediately on negotiation of ETM, rather than at CCS. Therefore,
during a renegotiation, if the ETM state is changing (usually due to a
change of ciphersuite), then an error/crash will occur.
Due to the fact that there are separate CCS messages for read and write
we actually now need two flags to determine whether to use ETM or not.
CVE-2017-3733
Reviewed-by: Richard Levitte <[email protected]>
CWE ID: CWE-20 | int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
{
EVP_CIPHER_CTX *ds;
size_t reclen[SSL_MAX_PIPELINES];
unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
int bs, i, j, k, pad = 0, ret, mac_size = 0;
const EVP_CIPHER *enc;
unsigned int ctr;
if (send) {
if (EVP_MD_CTX_md(s->write_hash)) {
int n = EVP_MD_CTX_size(s->write_hash);
OPENSSL_assert(n >= 0);
}
ds = s->enc_write_ctx;
if (s->enc_write_ctx == NULL)
enc = NULL;
else {
int ivlen;
enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
/* For TLSv1.1 and later explicit IV */
if (SSL_USE_EXPLICIT_IV(s)
&& EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
ivlen = EVP_CIPHER_iv_length(enc);
else
ivlen = 0;
if (ivlen > 1) {
for (ctr = 0; ctr < n_recs; ctr++) {
if (recs[ctr].data != recs[ctr].input) {
/*
* we can't write into the input stream: Can this ever
* happen?? (steve)
*/
SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
return -1;
} else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
return -1;
}
}
}
}
} else {
if (EVP_MD_CTX_md(s->read_hash)) {
int n = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(n >= 0);
}
ds = s->enc_read_ctx;
if (s->enc_read_ctx == NULL)
enc = NULL;
else
enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
}
if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
for (ctr = 0; ctr < n_recs; ctr++) {
memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
recs[ctr].input = recs[ctr].data;
}
ret = 1;
} else {
bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
if (n_recs > 1) {
if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_PIPELINE)) {
/*
* We shouldn't have been called with pipeline data if the
* cipher doesn't support pipelining
*/
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
return -1;
}
}
for (ctr = 0; ctr < n_recs; ctr++) {
reclen[ctr] = recs[ctr].length;
if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_AEAD_CIPHER) {
unsigned char *seq;
seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
: RECORD_LAYER_get_read_sequence(&s->rlayer);
if (SSL_IS_DTLS(s)) {
/* DTLS does not support pipelining */
unsigned char dtlsseq[9], *p = dtlsseq;
s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
memcpy(p, &seq[2], 6);
memcpy(buf[ctr], dtlsseq, 8);
} else {
memcpy(buf[ctr], seq, 8);
for (i = 7; i >= 0; i--) { /* increment */
++seq[i];
if (seq[i] != 0)
break;
}
}
buf[ctr][8] = recs[ctr].type;
buf[ctr][9] = (unsigned char)(s->version >> 8);
buf[ctr][10] = (unsigned char)(s->version);
buf[ctr][11] = recs[ctr].length >> 8;
buf[ctr][12] = recs[ctr].length & 0xff;
pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
if (pad <= 0)
return -1;
if (send) {
reclen[ctr] += pad;
recs[ctr].length += pad;
}
} else if ((bs != 1) && send) {
i = bs - ((int)reclen[ctr] % bs);
/* Add weird padding of upto 256 bytes */
/* we need to add 'i' padding bytes of value j */
j = i - 1;
for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
recs[ctr].input[k] = j;
reclen[ctr] += i;
recs[ctr].length += i;
}
if (!send) {
if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
return 0;
}
}
if (n_recs > 1) {
unsigned char *data[SSL_MAX_PIPELINES];
/* Set the output buffers */
for (ctr = 0; ctr < n_recs; ctr++) {
data[ctr] = recs[ctr].data;
}
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
n_recs, data) <= 0) {
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
}
/* Set the input buffers */
for (ctr = 0; ctr < n_recs; ctr++) {
data[ctr] = recs[ctr].input;
}
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
n_recs, data) <= 0
|| EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
n_recs, reclen) <= 0) {
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
return -1;
}
}
i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_CUSTOM_CIPHER)
? (i < 0)
: (i == 0))
return -1; /* AEAD can fail to verify MAC */
if (send == 0) {
if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
}
} else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
}
}
}
ret = 1;
if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
mac_size = EVP_MD_CTX_size(s->read_hash);
if ((bs != 1) && !send) {
int tmpret;
for (ctr = 0; ctr < n_recs; ctr++) {
tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
/*
* If tmpret == 0 then this means publicly invalid so we can
* short circuit things here. Otherwise we must respect constant
* time behaviour.
*/
if (tmpret == 0)
return 0;
ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
ret, -1);
}
}
if (pad && !send) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].length -= pad;
}
}
}
return ret;
}
| 168,423 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs41_callback_svc(void *vrqstp)
{
struct svc_rqst *rqstp = vrqstp;
struct svc_serv *serv = rqstp->rq_server;
struct rpc_rqst *req;
int error;
DEFINE_WAIT(wq);
set_freezable();
while (!kthread_should_stop()) {
if (try_to_freeze())
continue;
prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE);
spin_lock_bh(&serv->sv_cb_lock);
if (!list_empty(&serv->sv_cb_list)) {
req = list_first_entry(&serv->sv_cb_list,
struct rpc_rqst, rq_bc_list);
list_del(&req->rq_bc_list);
spin_unlock_bh(&serv->sv_cb_lock);
finish_wait(&serv->sv_cb_waitq, &wq);
dprintk("Invoking bc_svc_process()\n");
error = bc_svc_process(serv, req, rqstp);
dprintk("bc_svc_process() returned w/ error code= %d\n",
error);
} else {
spin_unlock_bh(&serv->sv_cb_lock);
schedule();
finish_wait(&serv->sv_cb_waitq, &wq);
}
flush_signals(current);
}
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | nfs41_callback_svc(void *vrqstp)
{
struct svc_rqst *rqstp = vrqstp;
struct svc_serv *serv = rqstp->rq_server;
struct rpc_rqst *req;
int error;
DEFINE_WAIT(wq);
set_freezable();
while (!kthread_freezable_should_stop(NULL)) {
if (signal_pending(current))
flush_signals(current);
prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE);
spin_lock_bh(&serv->sv_cb_lock);
if (!list_empty(&serv->sv_cb_list)) {
req = list_first_entry(&serv->sv_cb_list,
struct rpc_rqst, rq_bc_list);
list_del(&req->rq_bc_list);
spin_unlock_bh(&serv->sv_cb_lock);
finish_wait(&serv->sv_cb_waitq, &wq);
dprintk("Invoking bc_svc_process()\n");
error = bc_svc_process(serv, req, rqstp);
dprintk("bc_svc_process() returned w/ error code= %d\n",
error);
} else {
spin_unlock_bh(&serv->sv_cb_lock);
if (!kthread_should_stop())
schedule();
finish_wait(&serv->sv_cb_waitq, &wq);
}
}
svc_exit_thread(rqstp);
module_put_and_exit(0);
return 0;
}
| 168,137 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount,
struct vm_area_struct *vma, struct page *check_page)
{
struct mm_struct *mm = vma->vm_mm;
pmd_t *pmd;
pte_t *pte;
pte_t pteval;
spinlock_t *ptl;
struct page *page;
unsigned long address;
unsigned long mmun_start; /* For mmu_notifiers */
unsigned long mmun_end; /* For mmu_notifiers */
unsigned long end;
int ret = SWAP_AGAIN;
int locked_vma = 0;
address = (vma->vm_start + cursor) & CLUSTER_MASK;
end = address + CLUSTER_SIZE;
if (address < vma->vm_start)
address = vma->vm_start;
if (end > vma->vm_end)
end = vma->vm_end;
pmd = mm_find_pmd(mm, address);
if (!pmd)
return ret;
mmun_start = address;
mmun_end = end;
mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
/*
* If we can acquire the mmap_sem for read, and vma is VM_LOCKED,
* keep the sem while scanning the cluster for mlocking pages.
*/
if (down_read_trylock(&vma->vm_mm->mmap_sem)) {
locked_vma = (vma->vm_flags & VM_LOCKED);
if (!locked_vma)
up_read(&vma->vm_mm->mmap_sem); /* don't need it */
}
pte = pte_offset_map_lock(mm, pmd, address, &ptl);
/* Update high watermark before we lower rss */
update_hiwater_rss(mm);
for (; address < end; pte++, address += PAGE_SIZE) {
if (!pte_present(*pte))
continue;
page = vm_normal_page(vma, address, *pte);
BUG_ON(!page || PageAnon(page));
if (locked_vma) {
mlock_vma_page(page); /* no-op if already mlocked */
if (page == check_page)
ret = SWAP_MLOCK;
continue; /* don't unmap */
}
if (ptep_clear_flush_young_notify(vma, address, pte))
continue;
/* Nuke the page table entry. */
flush_cache_page(vma, address, pte_pfn(*pte));
pteval = ptep_clear_flush(vma, address, pte);
/* If nonlinear, store the file page offset in the pte. */
if (page->index != linear_page_index(vma, address)) {
pte_t ptfile = pgoff_to_pte(page->index);
if (pte_soft_dirty(pteval))
pte_file_mksoft_dirty(ptfile);
set_pte_at(mm, address, pte, ptfile);
}
/* Move the dirty bit to the physical page now the pte is gone. */
if (pte_dirty(pteval))
set_page_dirty(page);
page_remove_rmap(page);
page_cache_release(page);
dec_mm_counter(mm, MM_FILEPAGES);
(*mapcount)--;
}
pte_unmap_unlock(pte - 1, ptl);
mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
if (locked_vma)
up_read(&vma->vm_mm->mmap_sem);
return ret;
}
Commit Message: mm: try_to_unmap_cluster() should lock_page() before mlocking
A BUG_ON(!PageLocked) was triggered in mlock_vma_page() by Sasha Levin
fuzzing with trinity. The call site try_to_unmap_cluster() does not lock
the pages other than its check_page parameter (which is already locked).
The BUG_ON in mlock_vma_page() is not documented and its purpose is
somewhat unclear, but apparently it serializes against page migration,
which could otherwise fail to transfer the PG_mlocked flag. This would
not be fatal, as the page would be eventually encountered again, but
NR_MLOCK accounting would become distorted nevertheless. This patch adds
a comment to the BUG_ON in mlock_vma_page() and munlock_vma_page() to that
effect.
The call site try_to_unmap_cluster() is fixed so that for page !=
check_page, trylock_page() is attempted (to avoid possible deadlocks as we
already have check_page locked) and mlock_vma_page() is performed only
upon success. If the page lock cannot be obtained, the page is left
without PG_mlocked, which is again not a problem in the whole unevictable
memory design.
Signed-off-by: Vlastimil Babka <[email protected]>
Signed-off-by: Bob Liu <[email protected]>
Reported-by: Sasha Levin <[email protected]>
Cc: Wanpeng Li <[email protected]>
Cc: Michel Lespinasse <[email protected]>
Cc: KOSAKI Motohiro <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: David Rientjes <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Joonsoo Kim <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount,
struct vm_area_struct *vma, struct page *check_page)
{
struct mm_struct *mm = vma->vm_mm;
pmd_t *pmd;
pte_t *pte;
pte_t pteval;
spinlock_t *ptl;
struct page *page;
unsigned long address;
unsigned long mmun_start; /* For mmu_notifiers */
unsigned long mmun_end; /* For mmu_notifiers */
unsigned long end;
int ret = SWAP_AGAIN;
int locked_vma = 0;
address = (vma->vm_start + cursor) & CLUSTER_MASK;
end = address + CLUSTER_SIZE;
if (address < vma->vm_start)
address = vma->vm_start;
if (end > vma->vm_end)
end = vma->vm_end;
pmd = mm_find_pmd(mm, address);
if (!pmd)
return ret;
mmun_start = address;
mmun_end = end;
mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
/*
* If we can acquire the mmap_sem for read, and vma is VM_LOCKED,
* keep the sem while scanning the cluster for mlocking pages.
*/
if (down_read_trylock(&vma->vm_mm->mmap_sem)) {
locked_vma = (vma->vm_flags & VM_LOCKED);
if (!locked_vma)
up_read(&vma->vm_mm->mmap_sem); /* don't need it */
}
pte = pte_offset_map_lock(mm, pmd, address, &ptl);
/* Update high watermark before we lower rss */
update_hiwater_rss(mm);
for (; address < end; pte++, address += PAGE_SIZE) {
if (!pte_present(*pte))
continue;
page = vm_normal_page(vma, address, *pte);
BUG_ON(!page || PageAnon(page));
if (locked_vma) {
if (page == check_page) {
/* we know we have check_page locked */
mlock_vma_page(page);
ret = SWAP_MLOCK;
} else if (trylock_page(page)) {
/*
* If we can lock the page, perform mlock.
* Otherwise leave the page alone, it will be
* eventually encountered again later.
*/
mlock_vma_page(page);
unlock_page(page);
}
continue; /* don't unmap */
}
if (ptep_clear_flush_young_notify(vma, address, pte))
continue;
/* Nuke the page table entry. */
flush_cache_page(vma, address, pte_pfn(*pte));
pteval = ptep_clear_flush(vma, address, pte);
/* If nonlinear, store the file page offset in the pte. */
if (page->index != linear_page_index(vma, address)) {
pte_t ptfile = pgoff_to_pte(page->index);
if (pte_soft_dirty(pteval))
pte_file_mksoft_dirty(ptfile);
set_pte_at(mm, address, pte, ptfile);
}
/* Move the dirty bit to the physical page now the pte is gone. */
if (pte_dirty(pteval))
set_page_dirty(page);
page_remove_rmap(page);
page_cache_release(page);
dec_mm_counter(mm, MM_FILEPAGES);
(*mapcount)--;
}
pte_unmap_unlock(pte - 1, ptl);
mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
if (locked_vma)
up_read(&vma->vm_mm->mmap_sem);
return ret;
}
| 166,387 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[]) {
char *fin, *fout;
FILE *fpin, *fpout;
uint8_t *inbuf, *outbuf;
uint8_t *inbuf_u, *outbuf_u;
uint8_t *inbuf_v, *outbuf_v;
int f, frames;
int width, height, target_width, target_height;
if (argc < 5) {
printf("Incorrect parameters:\n");
usage(argv[0]);
return 1;
}
fin = argv[1];
fout = argv[4];
if (!parse_dim(argv[2], &width, &height)) {
printf("Incorrect parameters: %s\n", argv[2]);
usage(argv[0]);
return 1;
}
if (!parse_dim(argv[3], &target_width, &target_height)) {
printf("Incorrect parameters: %s\n", argv[3]);
usage(argv[0]);
return 1;
}
fpin = fopen(fin, "rb");
if (fpin == NULL) {
printf("Can't open file %s to read\n", fin);
usage(argv[0]);
return 1;
}
fpout = fopen(fout, "wb");
if (fpout == NULL) {
printf("Can't open file %s to write\n", fout);
usage(argv[0]);
return 1;
}
if (argc >= 6)
frames = atoi(argv[5]);
else
frames = INT_MAX;
printf("Input size: %dx%d\n",
width, height);
printf("Target size: %dx%d, Frames: ",
target_width, target_height);
if (frames == INT_MAX)
printf("All\n");
else
printf("%d\n", frames);
inbuf = (uint8_t*)malloc(width * height * 3 / 2);
outbuf = (uint8_t*)malloc(target_width * target_height * 3 / 2);
inbuf_u = inbuf + width * height;
inbuf_v = inbuf_u + width * height / 4;
outbuf_u = outbuf + target_width * target_height;
outbuf_v = outbuf_u + target_width * target_height / 4;
f = 0;
while (f < frames) {
if (fread(inbuf, width * height * 3 / 2, 1, fpin) != 1)
break;
vp9_resize_frame420(inbuf, width, inbuf_u, inbuf_v, width / 2,
height, width,
outbuf, target_width, outbuf_u, outbuf_v,
target_width / 2,
target_height, target_width);
fwrite(outbuf, target_width * target_height * 3 / 2, 1, fpout);
f++;
}
printf("%d frames processed\n", f);
fclose(fpin);
fclose(fpout);
free(inbuf);
free(outbuf);
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 main(int argc, char *argv[]) {
char *fin, *fout;
FILE *fpin, *fpout;
uint8_t *inbuf, *outbuf;
uint8_t *inbuf_u, *outbuf_u;
uint8_t *inbuf_v, *outbuf_v;
int f, frames;
int width, height, target_width, target_height;
exec_name = argv[0];
if (argc < 5) {
printf("Incorrect parameters:\n");
usage();
return 1;
}
fin = argv[1];
fout = argv[4];
if (!parse_dim(argv[2], &width, &height)) {
printf("Incorrect parameters: %s\n", argv[2]);
usage();
return 1;
}
if (!parse_dim(argv[3], &target_width, &target_height)) {
printf("Incorrect parameters: %s\n", argv[3]);
usage();
return 1;
}
fpin = fopen(fin, "rb");
if (fpin == NULL) {
printf("Can't open file %s to read\n", fin);
usage();
return 1;
}
fpout = fopen(fout, "wb");
if (fpout == NULL) {
printf("Can't open file %s to write\n", fout);
usage();
return 1;
}
if (argc >= 6)
frames = atoi(argv[5]);
else
frames = INT_MAX;
printf("Input size: %dx%d\n",
width, height);
printf("Target size: %dx%d, Frames: ",
target_width, target_height);
if (frames == INT_MAX)
printf("All\n");
else
printf("%d\n", frames);
inbuf = (uint8_t*)malloc(width * height * 3 / 2);
outbuf = (uint8_t*)malloc(target_width * target_height * 3 / 2);
inbuf_u = inbuf + width * height;
inbuf_v = inbuf_u + width * height / 4;
outbuf_u = outbuf + target_width * target_height;
outbuf_v = outbuf_u + target_width * target_height / 4;
f = 0;
while (f < frames) {
if (fread(inbuf, width * height * 3 / 2, 1, fpin) != 1)
break;
vp9_resize_frame420(inbuf, width, inbuf_u, inbuf_v, width / 2,
height, width,
outbuf, target_width, outbuf_u, outbuf_v,
target_width / 2,
target_height, target_width);
fwrite(outbuf, target_width * target_height * 3 / 2, 1, fpout);
f++;
}
printf("%d frames processed\n", f);
fclose(fpin);
fclose(fpout);
free(inbuf);
free(outbuf);
return 0;
}
| 174,479 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem )
{
cJSON *c = array->child;
while ( c && which > 0 ) {
c = c->next;
--which;
}
if ( ! c )
return;
newitem->next = c->next;
newitem->prev = c->prev;
if ( newitem->next )
newitem->next->prev = newitem;
if ( c == array->child )
array->child = newitem;
else
newitem->prev->next = newitem;
c->next = c->prev = 0;
cJSON_Delete( c );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem )
| 167,295 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mk_request_error(int http_status, struct client_session *cs,
struct session_request *sr) {
int ret, fd;
mk_ptr_t message, *page = 0;
struct error_page *entry;
struct mk_list *head;
struct file_info finfo;
mk_header_set_http_status(sr, http_status);
/*
* We are nice sending error pages for clients who at least respect
* the especification
*/
if (http_status != MK_CLIENT_LENGTH_REQUIRED &&
http_status != MK_CLIENT_BAD_REQUEST &&
http_status != MK_CLIENT_REQUEST_ENTITY_TOO_LARGE) {
/* Lookup a customized error page */
mk_list_foreach(head, &sr->host_conf->error_pages) {
entry = mk_list_entry(head, struct error_page, _head);
if (entry->status != http_status) {
continue;
}
/* validate error file */
ret = mk_file_get_info(entry->real_path, &finfo);
if (ret == -1) {
break;
}
/* open file */
fd = open(entry->real_path, config->open_flags);
if (fd == -1) {
break;
}
sr->fd_file = fd;
sr->bytes_to_send = finfo.size;
sr->headers.content_length = finfo.size;
sr->headers.real_length = finfo.size;
memcpy(&sr->file_info, &finfo, sizeof(struct file_info));
mk_header_send(cs->socket, cs, sr);
return mk_http_send_file(cs, sr);
}
}
mk_ptr_reset(&message);
switch (http_status) {
case MK_CLIENT_BAD_REQUEST:
page = mk_request_set_default_page("Bad Request",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_FORBIDDEN:
page = mk_request_set_default_page("Forbidden",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_NOT_FOUND:
mk_string_build(&message.data, &message.len,
"The requested URL was not found on this server.");
page = mk_request_set_default_page("Not Found",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_REQUEST_ENTITY_TOO_LARGE:
mk_string_build(&message.data, &message.len,
"The request entity is too large.");
page = mk_request_set_default_page("Entity too large",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_METHOD_NOT_ALLOWED:
page = mk_request_set_default_page("Method Not Allowed",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_REQUEST_TIMEOUT:
case MK_CLIENT_LENGTH_REQUIRED:
break;
case MK_SERVER_NOT_IMPLEMENTED:
page = mk_request_set_default_page("Method Not Implemented",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_INTERNAL_ERROR:
page = mk_request_set_default_page("Internal Server Error",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_HTTP_VERSION_UNSUP:
mk_ptr_reset(&message);
page = mk_request_set_default_page("HTTP Version Not Supported",
message,
sr->host_conf->host_signature);
break;
}
if (page) {
sr->headers.content_length = page->len;
}
sr->headers.location = NULL;
sr->headers.cgi = SH_NOCGI;
sr->headers.pconnections_left = 0;
sr->headers.last_modified = -1;
if (!page) {
mk_ptr_reset(&sr->headers.content_type);
}
else {
mk_ptr_set(&sr->headers.content_type, "text/html\r\n");
}
mk_header_send(cs->socket, cs, sr);
if (page) {
if (sr->method != MK_HTTP_METHOD_HEAD)
mk_socket_send(cs->socket, page->data, page->len);
mk_ptr_free(page);
mk_mem_free(page);
}
/* Turn off TCP_CORK */
mk_server_cork_flag(cs->socket, TCP_CORK_OFF);
return EXIT_ERROR;
}
Commit Message: Request: new request session flag to mark those files opened by FDT
This patch aims to fix a potential DDoS problem that can be caused
in the server quering repetitive non-existent resources.
When serving a static file, the core use Vhost FDT mechanism, but if
it sends a static error page it does a direct open(2). When closing
the resources for the same request it was just calling mk_vhost_close()
which did not clear properly the file descriptor.
This patch adds a new field on the struct session_request called 'fd_is_fdt',
which contains MK_TRUE or MK_FALSE depending of how fd_file was opened.
Thanks to Matthew Daley <[email protected]> for report and troubleshoot this
problem.
Signed-off-by: Eduardo Silva <[email protected]>
CWE ID: CWE-20 | int mk_request_error(int http_status, struct client_session *cs,
struct session_request *sr) {
int ret, fd;
mk_ptr_t message, *page = 0;
struct error_page *entry;
struct mk_list *head;
struct file_info finfo;
mk_header_set_http_status(sr, http_status);
/*
* We are nice sending error pages for clients who at least respect
* the especification
*/
if (http_status != MK_CLIENT_LENGTH_REQUIRED &&
http_status != MK_CLIENT_BAD_REQUEST &&
http_status != MK_CLIENT_REQUEST_ENTITY_TOO_LARGE) {
/* Lookup a customized error page */
mk_list_foreach(head, &sr->host_conf->error_pages) {
entry = mk_list_entry(head, struct error_page, _head);
if (entry->status != http_status) {
continue;
}
/* validate error file */
ret = mk_file_get_info(entry->real_path, &finfo);
if (ret == -1) {
break;
}
/* open file */
fd = open(entry->real_path, config->open_flags);
if (fd == -1) {
break;
}
sr->fd_file = fd;
sr->fd_is_fdt = MK_FALSE;
sr->bytes_to_send = finfo.size;
sr->headers.content_length = finfo.size;
sr->headers.real_length = finfo.size;
memcpy(&sr->file_info, &finfo, sizeof(struct file_info));
mk_header_send(cs->socket, cs, sr);
return mk_http_send_file(cs, sr);
}
}
mk_ptr_reset(&message);
switch (http_status) {
case MK_CLIENT_BAD_REQUEST:
page = mk_request_set_default_page("Bad Request",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_FORBIDDEN:
page = mk_request_set_default_page("Forbidden",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_NOT_FOUND:
mk_string_build(&message.data, &message.len,
"The requested URL was not found on this server.");
page = mk_request_set_default_page("Not Found",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_REQUEST_ENTITY_TOO_LARGE:
mk_string_build(&message.data, &message.len,
"The request entity is too large.");
page = mk_request_set_default_page("Entity too large",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_METHOD_NOT_ALLOWED:
page = mk_request_set_default_page("Method Not Allowed",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_REQUEST_TIMEOUT:
case MK_CLIENT_LENGTH_REQUIRED:
break;
case MK_SERVER_NOT_IMPLEMENTED:
page = mk_request_set_default_page("Method Not Implemented",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_INTERNAL_ERROR:
page = mk_request_set_default_page("Internal Server Error",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_HTTP_VERSION_UNSUP:
mk_ptr_reset(&message);
page = mk_request_set_default_page("HTTP Version Not Supported",
message,
sr->host_conf->host_signature);
break;
}
if (page) {
sr->headers.content_length = page->len;
}
sr->headers.location = NULL;
sr->headers.cgi = SH_NOCGI;
sr->headers.pconnections_left = 0;
sr->headers.last_modified = -1;
if (!page) {
mk_ptr_reset(&sr->headers.content_type);
}
else {
mk_ptr_set(&sr->headers.content_type, "text/html\r\n");
}
mk_header_send(cs->socket, cs, sr);
if (page) {
if (sr->method != MK_HTTP_METHOD_HEAD)
mk_socket_send(cs->socket, page->data, page->len);
mk_ptr_free(page);
mk_mem_free(page);
}
/* Turn off TCP_CORK */
mk_server_cork_flag(cs->socket, TCP_CORK_OFF);
return EXIT_ERROR;
}
| 166,276 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::Connect(
BluetoothDevice::PairingDelegate* pairing_delegate,
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
if (num_connecting_calls_++ == 0)
adapter_->NotifyDeviceChanged(this);
VLOG(1) << object_path_.value() << ": Connecting, " << num_connecting_calls_
<< " in progress";
if (IsPaired() || !pairing_delegate || !IsPairable()) {
ConnectInternal(false, callback, error_callback);
} else {
DCHECK(!pairing_delegate_);
DCHECK(agent_.get() == NULL);
pairing_delegate_ = pairing_delegate;
pairing_delegate_used_ = false;
dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus();
agent_.reset(BluetoothAgentServiceProvider::Create(
system_bus, dbus::ObjectPath(kAgentPath), this));
DCHECK(agent_.get());
VLOG(1) << object_path_.value() << ": Registering agent for pairing";
DBusThreadManager::Get()->GetBluetoothAgentManagerClient()->
RegisterAgent(
dbus::ObjectPath(kAgentPath),
bluetooth_agent_manager::kKeyboardDisplayCapability,
base::Bind(&BluetoothDeviceChromeOS::OnRegisterAgent,
weak_ptr_factory_.GetWeakPtr(),
callback,
error_callback),
base::Bind(&BluetoothDeviceChromeOS::OnRegisterAgentError,
weak_ptr_factory_.GetWeakPtr(),
error_callback));
}
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::Connect(
BluetoothDevice::PairingDelegate* pairing_delegate,
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
if (num_connecting_calls_++ == 0)
adapter_->NotifyDeviceChanged(this);
VLOG(1) << object_path_.value() << ": Connecting, " << num_connecting_calls_
<< " in progress";
if (IsPaired() || !pairing_delegate || !IsPairable()) {
ConnectInternal(false, callback, error_callback);
} else {
DCHECK(!pairing_context_);
pairing_context_.reset(
new BluetoothAdapterChromeOS::PairingContext(pairing_delegate));
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
Pair(object_path_,
base::Bind(&BluetoothDeviceChromeOS::OnPair,
weak_ptr_factory_.GetWeakPtr(),
callback, error_callback),
base::Bind(&BluetoothDeviceChromeOS::OnPairError,
weak_ptr_factory_.GetWeakPtr(),
error_callback));
}
}
| 171,221 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MediaStreamManagerTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
audio_manager_ = std::make_unique<MockAudioManager>();
audio_system_ =
std::make_unique<media::AudioSystemImpl>(audio_manager_.get());
auto video_capture_provider = std::make_unique<MockVideoCaptureProvider>();
video_capture_provider_ = video_capture_provider.get();
media_stream_manager_ = std::make_unique<MediaStreamManager>(
audio_system_.get(), audio_manager_->GetTaskRunner(),
std::move(video_capture_provider));
base::RunLoop().RunUntilIdle();
ON_CALL(*video_capture_provider_, DoGetDeviceInfosAsync(_))
.WillByDefault(Invoke(
[](VideoCaptureProvider::GetDeviceInfosCallback& result_callback) {
std::vector<media::VideoCaptureDeviceInfo> stub_results;
base::ResetAndReturn(&result_callback).Run(stub_results);
}));
}
Commit Message: Fix MediaObserver notifications in MediaStreamManager.
This CL fixes the stream type used to notify MediaObserver about
cancelled MediaStream requests.
Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate
that all stream types should be cancelled.
However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this
way and the request to update the UI is ignored.
This CL sends a separate notification for each stream type so that the
UI actually gets updated for all stream types in use.
Bug: 816033
Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405
Reviewed-on: https://chromium-review.googlesource.com/939630
Commit-Queue: Guido Urdaneta <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540122}
CWE ID: CWE-20 | MediaStreamManagerTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
audio_manager_ = std::make_unique<MockAudioManager>();
audio_system_ =
std::make_unique<media::AudioSystemImpl>(audio_manager_.get());
auto video_capture_provider = std::make_unique<MockVideoCaptureProvider>();
video_capture_provider_ = video_capture_provider.get();
media_stream_manager_ = std::make_unique<MediaStreamManager>(
audio_system_.get(), audio_manager_->GetTaskRunner(),
std::move(video_capture_provider));
media_observer_ = std::make_unique<MockMediaObserver>();
browser_content_client_ =
std::make_unique<TestBrowserClient>(media_observer_.get());
SetBrowserClientForTesting(browser_content_client_.get());
base::RunLoop().RunUntilIdle();
ON_CALL(*video_capture_provider_, DoGetDeviceInfosAsync(_))
.WillByDefault(Invoke(
[](VideoCaptureProvider::GetDeviceInfosCallback& result_callback) {
std::vector<media::VideoCaptureDeviceInfo> stub_results;
base::ResetAndReturn(&result_callback).Run(stub_results);
}));
}
| 172,735 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Part::slotOpenExtractedEntry(KJob *job)
{
if (!job->error()) {
OpenJob *openJob = qobject_cast<OpenJob*>(job);
Q_ASSERT(openJob);
m_tmpExtractDirList << openJob->tempDir();
const QString fullName = openJob->validatedFilePath();
bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly();
if (!isWritable) {
QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
}
if (isWritable) {
m_fileWatcher = new QFileSystemWatcher;
connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified);
m_fileWatcher->addPath(fullName);
}
if (qobject_cast<OpenWithJob*>(job)) {
const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)};
KRun::displayOpenWithDialog(urls, widget());
} else {
KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile),
QMimeDatabase().mimeTypeForFile(fullName).name(),
widget());
}
} else if (job->error() != KJob::KilledJobError) {
KMessageBox::error(widget(), job->errorString());
}
setReadyGui();
}
Commit Message:
CWE ID: CWE-78 | void Part::slotOpenExtractedEntry(KJob *job)
{
if (!job->error()) {
OpenJob *openJob = qobject_cast<OpenJob*>(job);
Q_ASSERT(openJob);
m_tmpExtractDirList << openJob->tempDir();
const QString fullName = openJob->validatedFilePath();
bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly();
if (!isWritable) {
QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
}
if (isWritable) {
m_fileWatcher = new QFileSystemWatcher;
connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified);
m_fileWatcher->addPath(fullName);
}
if (qobject_cast<OpenWithJob*>(job)) {
const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)};
KRun::displayOpenWithDialog(urls, widget());
} else {
KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile),
QMimeDatabase().mimeTypeForFile(fullName).name(),
widget(), false, false);
}
} else if (job->error() != KJob::KilledJobError) {
KMessageBox::error(widget(), job->errorString());
}
setReadyGui();
}
| 164,992 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AutocompleteEditModel::OpenMatch(const AutocompleteMatch& match,
WindowOpenDisposition disposition,
const GURL& alternate_nav_url,
size_t index) {
if (popup_->IsOpen()) {
AutocompleteLog log(
autocomplete_controller_->input().text(),
just_deleted_text_,
autocomplete_controller_->input().type(),
popup_->selected_line(),
-1, // don't yet know tab ID; set later if appropriate
ClassifyPage(controller_->GetTabContentsWrapper()->
web_contents()->GetURL()),
base::TimeTicks::Now() - time_user_first_modified_omnibox_,
0, // inline autocomplete length; possibly set later
result());
DCHECK(user_input_in_progress_) << "We didn't get here through the "
"expected series of calls. time_user_first_modified_omnibox_ is "
"not set correctly and other things may be wrong.";
if (index != AutocompletePopupModel::kNoMatch)
log.selected_index = index;
else if (!has_temporary_text_)
log.inline_autocompleted_length = inline_autocomplete_text_.length();
if (disposition == CURRENT_TAB) {
log.tab_id = controller_->GetTabContentsWrapper()->
restore_tab_helper()->session_id().id();
}
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
content::Source<Profile>(profile_),
content::Details<AutocompleteLog>(&log));
}
TemplateURL* template_url = match.GetTemplateURL(profile_);
if (template_url) {
if (match.transition == content::PAGE_TRANSITION_KEYWORD) {
if (template_url->IsExtensionKeyword()) {
AutocompleteMatch current_match;
GetInfoForCurrentText(¤t_match, NULL);
const AutocompleteMatch& match =
(index == AutocompletePopupModel::kNoMatch) ?
current_match : result().match_at(index);
size_t prefix_length = match.keyword.length() + 1;
extensions::ExtensionOmniboxEventRouter::OnInputEntered(profile_,
template_url->GetExtensionId(),
UTF16ToUTF8(match.fill_into_edit.substr(prefix_length)));
view_->RevertAll();
return;
}
content::RecordAction(UserMetricsAction("AcceptedKeyword"));
TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
template_url);
} else {
DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition);
}
UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine",
template_url->prepopulate_id(),
TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
}
if (disposition != NEW_BACKGROUND_TAB) {
in_revert_ = true;
view_->RevertAll(); // Revert the box to its unedited state
}
if (match.type == AutocompleteMatch::EXTENSION_APP) {
extensions::LaunchAppFromOmnibox(match, profile_, disposition);
} else {
controller_->OnAutocompleteAccept(match.destination_url, disposition,
match.transition, alternate_nav_url);
}
if (match.starred)
bookmark_utils::RecordBookmarkLaunch(bookmark_utils::LAUNCH_OMNIBOX);
InstantController* instant = controller_->GetInstant();
if (instant && !popup_->IsOpen())
instant->DestroyPreviewContents();
in_revert_ = false;
}
Commit Message: Adds per-provider information to omnibox UMA logs.
Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future.
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10380007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void AutocompleteEditModel::OpenMatch(const AutocompleteMatch& match,
WindowOpenDisposition disposition,
const GURL& alternate_nav_url,
size_t index) {
if (popup_->IsOpen()) {
AutocompleteLog log(
autocomplete_controller_->input().text(),
just_deleted_text_,
autocomplete_controller_->input().type(),
popup_->selected_line(),
-1, // don't yet know tab ID; set later if appropriate
ClassifyPage(controller_->GetTabContentsWrapper()->
web_contents()->GetURL()),
base::TimeTicks::Now() - time_user_first_modified_omnibox_,
0, // inline autocomplete length; possibly set later
result());
DCHECK(user_input_in_progress_) << "We didn't get here through the "
"expected series of calls. time_user_first_modified_omnibox_ is "
"not set correctly and other things may be wrong.";
if (index != AutocompletePopupModel::kNoMatch)
log.selected_index = index;
else if (!has_temporary_text_)
log.inline_autocompleted_length = inline_autocomplete_text_.length();
if (disposition == CURRENT_TAB) {
log.tab_id = controller_->GetTabContentsWrapper()->
restore_tab_helper()->session_id().id();
}
autocomplete_controller_->AddProvidersInfo(&log.providers_info);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
content::Source<Profile>(profile_),
content::Details<AutocompleteLog>(&log));
}
TemplateURL* template_url = match.GetTemplateURL(profile_);
if (template_url) {
if (match.transition == content::PAGE_TRANSITION_KEYWORD) {
if (template_url->IsExtensionKeyword()) {
AutocompleteMatch current_match;
GetInfoForCurrentText(¤t_match, NULL);
const AutocompleteMatch& match =
(index == AutocompletePopupModel::kNoMatch) ?
current_match : result().match_at(index);
size_t prefix_length = match.keyword.length() + 1;
extensions::ExtensionOmniboxEventRouter::OnInputEntered(profile_,
template_url->GetExtensionId(),
UTF16ToUTF8(match.fill_into_edit.substr(prefix_length)));
view_->RevertAll();
return;
}
content::RecordAction(UserMetricsAction("AcceptedKeyword"));
TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
template_url);
} else {
DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition);
}
UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine",
template_url->prepopulate_id(),
TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
}
if (disposition != NEW_BACKGROUND_TAB) {
in_revert_ = true;
view_->RevertAll(); // Revert the box to its unedited state
}
if (match.type == AutocompleteMatch::EXTENSION_APP) {
extensions::LaunchAppFromOmnibox(match, profile_, disposition);
} else {
controller_->OnAutocompleteAccept(match.destination_url, disposition,
match.transition, alternate_nav_url);
}
if (match.starred)
bookmark_utils::RecordBookmarkLaunch(bookmark_utils::LAUNCH_OMNIBOX);
InstantController* instant = controller_->GetInstant();
if (instant && !popup_->IsOpen())
instant->DestroyPreviewContents();
in_revert_ = false;
}
| 170,758 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[])
{
char buff[1024];
int fd, nr, nw;
if (argc < 2) {
fprintf(stderr,
"usage: %s output-filename\n"
" %s |output-command\n"
" %s :host:port\n", argv[0], argv[0], argv[0]);
return 1;
}
fd = open_gen_fd(argv[1]);
if (fd < 0) {
perror("open_gen_fd");
exit(EXIT_FAILURE);
}
while ((nr = read(0, buff, sizeof (buff))) != 0) {
if (nr < 0) {
if (errno == EINTR)
continue;
perror("read");
exit(EXIT_FAILURE);
}
nw = write(fd, buff, nr);
if (nw < 0) {
perror("write");
exit(EXIT_FAILURE);
}
}
return 0;
}
Commit Message: misc oom and possible memory leak fix
CWE ID: | int main(int argc, char *argv[])
{
char buff[1024];
int fd, nr, nw;
if (argc < 2) {
fprintf(stderr,
"usage: %s output-filename\n"
" %s |output-command\n"
" %s :host:port\n", argv[0], argv[0], argv[0]);
return 1;
}
fd = open_gen_fd(argv[1]);
if (fd < 0) {
perror("open_gen_fd");
exit(EXIT_FAILURE);
}
while ((nr = read(0, buff, sizeof (buff))) != 0) {
if (nr < 0) {
if (errno == EINTR)
continue;
perror("read");
exit(EXIT_FAILURE);
}
nw = write(fd, buff, nr);
if (nw < 0) {
perror("write");
exit(EXIT_FAILURE);
}
}
close(fd);
return 0;
}
| 169,758 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Cluster::GetTime() const
{
const long long tc = GetTimeCode();
if (tc < 0)
return tc;
const SegmentInfo* const pInfo = m_pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long t = m_timecode * scale;
return t;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Cluster::GetTime() const
| 174,362 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebRuntimeFeatures::EnableRequireCSSExtensionForFile(bool enable) {
RuntimeEnabledFeatures::SetRequireCSSExtensionForFileEnabled(enable);
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Dave Tapuska <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254 | void WebRuntimeFeatures::EnableRequireCSSExtensionForFile(bool enable) {
| 173,187 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Compositor::Compositor(
const viz::FrameSinkId& frame_sink_id,
ui::ContextFactory* context_factory,
ui::ContextFactoryPrivate* context_factory_private,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
bool enable_pixel_canvas,
ui::ExternalBeginFrameClient* external_begin_frame_client,
bool force_software_compositor,
const char* trace_environment_name)
: context_factory_(context_factory),
context_factory_private_(context_factory_private),
frame_sink_id_(frame_sink_id),
task_runner_(task_runner),
vsync_manager_(new CompositorVSyncManager()),
external_begin_frame_client_(external_begin_frame_client),
force_software_compositor_(force_software_compositor),
layer_animator_collection_(this),
is_pixel_canvas_(enable_pixel_canvas),
lock_manager_(task_runner),
trace_environment_name_(trace_environment_name
? trace_environment_name
: kDefaultTraceEnvironmentName),
context_creation_weak_ptr_factory_(this) {
if (context_factory_private) {
auto* host_frame_sink_manager =
context_factory_private_->GetHostFrameSinkManager();
host_frame_sink_manager->RegisterFrameSinkId(
frame_sink_id_, this, viz::ReportFirstSurfaceActivation::kNo);
host_frame_sink_manager->SetFrameSinkDebugLabel(frame_sink_id_,
"Compositor");
}
root_web_layer_ = cc::Layer::Create();
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
cc::LayerTreeSettings settings;
settings.layers_always_allowed_lcd_text = true;
settings.use_occlusion_for_tile_prioritization = true;
settings.main_frame_before_activation_enabled = false;
settings.delegated_sync_points_required =
context_factory_->SyncTokensRequiredForDisplayCompositor();
settings.enable_edge_anti_aliasing = false;
if (command_line->HasSwitch(cc::switches::kUIShowCompositedLayerBorders)) {
std::string layer_borders_string = command_line->GetSwitchValueASCII(
cc::switches::kUIShowCompositedLayerBorders);
std::vector<base::StringPiece> entries = base::SplitStringPiece(
layer_borders_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (entries.empty()) {
settings.initial_debug_state.show_debug_borders.set();
} else {
for (const auto& entry : entries) {
const struct {
const char* name;
cc::DebugBorderType type;
} kBorders[] = {{cc::switches::kCompositedRenderPassBorders,
cc::DebugBorderType::RENDERPASS},
{cc::switches::kCompositedSurfaceBorders,
cc::DebugBorderType::SURFACE},
{cc::switches::kCompositedLayerBorders,
cc::DebugBorderType::LAYER}};
for (const auto& border : kBorders) {
if (border.name == entry) {
settings.initial_debug_state.show_debug_borders.set(border.type);
break;
}
}
}
}
}
settings.initial_debug_state.show_fps_counter =
command_line->HasSwitch(cc::switches::kUIShowFPSCounter);
settings.initial_debug_state.show_layer_animation_bounds_rects =
command_line->HasSwitch(cc::switches::kUIShowLayerAnimationBounds);
settings.initial_debug_state.show_paint_rects =
command_line->HasSwitch(switches::kUIShowPaintRects);
settings.initial_debug_state.show_property_changed_rects =
command_line->HasSwitch(cc::switches::kUIShowPropertyChangedRects);
settings.initial_debug_state.show_surface_damage_rects =
command_line->HasSwitch(cc::switches::kUIShowSurfaceDamageRects);
settings.initial_debug_state.show_screen_space_rects =
command_line->HasSwitch(cc::switches::kUIShowScreenSpaceRects);
settings.initial_debug_state.SetRecordRenderingStats(
command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking));
settings.enable_surface_synchronization = true;
settings.build_hit_test_data = features::IsVizHitTestingSurfaceLayerEnabled();
settings.use_zero_copy = IsUIZeroCopyEnabled();
settings.use_layer_lists =
command_line->HasSwitch(cc::switches::kUIEnableLayerLists);
settings.use_partial_raster = !settings.use_zero_copy;
settings.use_rgba_4444 =
command_line->HasSwitch(switches::kUIEnableRGBA4444Textures);
#if defined(OS_MACOSX)
settings.resource_settings.use_gpu_memory_buffer_resources =
settings.use_zero_copy;
settings.enable_elastic_overscroll = true;
#endif
settings.memory_policy.bytes_limit_when_visible = 512 * 1024 * 1024;
if (command_line->HasSwitch(
switches::kUiCompositorMemoryLimitWhenVisibleMB)) {
std::string value_str = command_line->GetSwitchValueASCII(
switches::kUiCompositorMemoryLimitWhenVisibleMB);
unsigned value_in_mb;
if (base::StringToUint(value_str, &value_in_mb)) {
settings.memory_policy.bytes_limit_when_visible =
1024 * 1024 * value_in_mb;
}
}
settings.memory_policy.priority_cutoff_when_visible =
gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
settings.disallow_non_exact_resource_reuse =
command_line->HasSwitch(switches::kDisallowNonExactResourceReuse);
if (command_line->HasSwitch(switches::kRunAllCompositorStagesBeforeDraw)) {
settings.wait_for_all_pipeline_stages_before_draw = true;
settings.enable_latency_recovery = false;
}
if (base::FeatureList::IsEnabled(
features::kCompositorThreadedScrollbarScrolling)) {
settings.compositor_threaded_scrollbar_scrolling = true;
}
animation_host_ = cc::AnimationHost::CreateMainInstance();
cc::LayerTreeHost::InitParams params;
params.client = this;
params.task_graph_runner = context_factory_->GetTaskGraphRunner();
params.settings = &settings;
params.main_task_runner = task_runner_;
params.mutator_host = animation_host_.get();
host_ = cc::LayerTreeHost::CreateSingleThreaded(this, std::move(params));
if (base::FeatureList::IsEnabled(features::kUiCompositorScrollWithLayers) &&
host_->GetInputHandler()) {
scroll_input_handler_.reset(
new ScrollInputHandler(host_->GetInputHandler()));
}
animation_timeline_ =
cc::AnimationTimeline::Create(cc::AnimationIdProvider::NextTimelineId());
animation_host_->AddAnimationTimeline(animation_timeline_.get());
host_->SetHasGpuRasterizationTrigger(features::IsUiGpuRasterizationEnabled());
host_->SetRootLayer(root_web_layer_);
host_->SetVisible(true);
if (command_line->HasSwitch(switches::kUISlowAnimations)) {
slow_animations_ = std::make_unique<ScopedAnimationDurationScaleMode>(
ScopedAnimationDurationScaleMode::SLOW_DURATION);
}
}
Commit Message: Fix PIP window being blank after minimize/show
DesktopWindowTreeHostX11::SetVisible only made the call into
OnNativeWidgetVisibilityChanged when transitioning from shown
to minimized and not vice versa. This is because this change
https://chromium-review.googlesource.com/c/chromium/src/+/1437263
considered IsVisible to be true when minimized, which made
IsVisible always true in this case. This caused layers to be hidden
but never shown again.
This is a reland of:
https://chromium-review.googlesource.com/c/chromium/src/+/1580103
Bug: 949199
Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617
Reviewed-by: Scott Violet <[email protected]>
Commit-Queue: enne <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654280}
CWE ID: CWE-284 | Compositor::Compositor(
const viz::FrameSinkId& frame_sink_id,
ui::ContextFactory* context_factory,
ui::ContextFactoryPrivate* context_factory_private,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
bool enable_pixel_canvas,
ui::ExternalBeginFrameClient* external_begin_frame_client,
bool force_software_compositor,
const char* trace_environment_name)
: context_factory_(context_factory),
context_factory_private_(context_factory_private),
frame_sink_id_(frame_sink_id),
task_runner_(task_runner),
vsync_manager_(new CompositorVSyncManager()),
external_begin_frame_client_(external_begin_frame_client),
force_software_compositor_(force_software_compositor),
layer_animator_collection_(this),
is_pixel_canvas_(enable_pixel_canvas),
lock_manager_(task_runner),
trace_environment_name_(trace_environment_name
? trace_environment_name
: kDefaultTraceEnvironmentName),
context_creation_weak_ptr_factory_(this) {
if (context_factory_private) {
auto* host_frame_sink_manager =
context_factory_private_->GetHostFrameSinkManager();
host_frame_sink_manager->RegisterFrameSinkId(
frame_sink_id_, this, viz::ReportFirstSurfaceActivation::kNo);
host_frame_sink_manager->SetFrameSinkDebugLabel(frame_sink_id_,
"Compositor");
}
root_web_layer_ = cc::Layer::Create();
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
cc::LayerTreeSettings settings;
settings.layers_always_allowed_lcd_text = true;
settings.use_occlusion_for_tile_prioritization = true;
settings.main_frame_before_activation_enabled = false;
settings.delegated_sync_points_required =
context_factory_->SyncTokensRequiredForDisplayCompositor();
settings.enable_edge_anti_aliasing = false;
if (command_line->HasSwitch(cc::switches::kUIShowCompositedLayerBorders)) {
std::string layer_borders_string = command_line->GetSwitchValueASCII(
cc::switches::kUIShowCompositedLayerBorders);
std::vector<base::StringPiece> entries = base::SplitStringPiece(
layer_borders_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (entries.empty()) {
settings.initial_debug_state.show_debug_borders.set();
} else {
for (const auto& entry : entries) {
const struct {
const char* name;
cc::DebugBorderType type;
} kBorders[] = {{cc::switches::kCompositedRenderPassBorders,
cc::DebugBorderType::RENDERPASS},
{cc::switches::kCompositedSurfaceBorders,
cc::DebugBorderType::SURFACE},
{cc::switches::kCompositedLayerBorders,
cc::DebugBorderType::LAYER}};
for (const auto& border : kBorders) {
if (border.name == entry) {
settings.initial_debug_state.show_debug_borders.set(border.type);
break;
}
}
}
}
}
settings.initial_debug_state.show_fps_counter =
command_line->HasSwitch(cc::switches::kUIShowFPSCounter);
settings.initial_debug_state.show_layer_animation_bounds_rects =
command_line->HasSwitch(cc::switches::kUIShowLayerAnimationBounds);
settings.initial_debug_state.show_paint_rects =
command_line->HasSwitch(switches::kUIShowPaintRects);
settings.initial_debug_state.show_property_changed_rects =
command_line->HasSwitch(cc::switches::kUIShowPropertyChangedRects);
settings.initial_debug_state.show_surface_damage_rects =
command_line->HasSwitch(cc::switches::kUIShowSurfaceDamageRects);
settings.initial_debug_state.show_screen_space_rects =
command_line->HasSwitch(cc::switches::kUIShowScreenSpaceRects);
settings.initial_debug_state.SetRecordRenderingStats(
command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking));
settings.enable_surface_synchronization = true;
settings.build_hit_test_data = features::IsVizHitTestingSurfaceLayerEnabled();
settings.use_zero_copy = IsUIZeroCopyEnabled();
settings.use_layer_lists =
command_line->HasSwitch(cc::switches::kUIEnableLayerLists);
settings.use_partial_raster = !settings.use_zero_copy;
settings.use_rgba_4444 =
command_line->HasSwitch(switches::kUIEnableRGBA4444Textures);
#if defined(OS_MACOSX)
settings.resource_settings.use_gpu_memory_buffer_resources =
settings.use_zero_copy;
settings.enable_elastic_overscroll = true;
#endif
settings.memory_policy.bytes_limit_when_visible = 512 * 1024 * 1024;
if (command_line->HasSwitch(
switches::kUiCompositorMemoryLimitWhenVisibleMB)) {
std::string value_str = command_line->GetSwitchValueASCII(
switches::kUiCompositorMemoryLimitWhenVisibleMB);
unsigned value_in_mb;
if (base::StringToUint(value_str, &value_in_mb)) {
settings.memory_policy.bytes_limit_when_visible =
1024 * 1024 * value_in_mb;
}
}
settings.memory_policy.priority_cutoff_when_visible =
gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
settings.disallow_non_exact_resource_reuse =
command_line->HasSwitch(switches::kDisallowNonExactResourceReuse);
if (command_line->HasSwitch(switches::kRunAllCompositorStagesBeforeDraw)) {
settings.wait_for_all_pipeline_stages_before_draw = true;
settings.enable_latency_recovery = false;
}
if (base::FeatureList::IsEnabled(
features::kCompositorThreadedScrollbarScrolling)) {
settings.compositor_threaded_scrollbar_scrolling = true;
}
animation_host_ = cc::AnimationHost::CreateMainInstance();
cc::LayerTreeHost::InitParams params;
params.client = this;
params.task_graph_runner = context_factory_->GetTaskGraphRunner();
params.settings = &settings;
params.main_task_runner = task_runner_;
params.mutator_host = animation_host_.get();
host_ = cc::LayerTreeHost::CreateSingleThreaded(this, std::move(params));
if (base::FeatureList::IsEnabled(features::kUiCompositorScrollWithLayers) &&
host_->GetInputHandler()) {
scroll_input_handler_.reset(
new ScrollInputHandler(host_->GetInputHandler()));
}
animation_timeline_ =
cc::AnimationTimeline::Create(cc::AnimationIdProvider::NextTimelineId());
animation_host_->AddAnimationTimeline(animation_timeline_.get());
host_->SetHasGpuRasterizationTrigger(features::IsUiGpuRasterizationEnabled());
host_->SetRootLayer(root_web_layer_);
// This shouldn't be done in the constructor in order to match Widget.
// See: http://crbug.com/956264.
host_->SetVisible(true);
if (command_line->HasSwitch(switches::kUISlowAnimations)) {
slow_animations_ = std::make_unique<ScopedAnimationDurationScaleMode>(
ScopedAnimationDurationScaleMode::SLOW_DURATION);
}
}
| 172,515 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DoCheckFakeData(uint8* audio_data, size_t length) {
Type* output = reinterpret_cast<Type*>(audio_data);
for (size_t i = 0; i < length; i++) {
EXPECT_TRUE(algorithm_.is_muted() || output[i] != 0);
}
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void DoCheckFakeData(uint8* audio_data, size_t length) {
if (algorithm_.is_muted())
ASSERT_EQ(sum, 0);
else
ASSERT_NE(sum, 0);
}
| 171,531 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response ServiceWorkerHandler::DispatchSyncEvent(
const std::string& origin,
const std::string& registration_id,
const std::string& tag,
bool last_chance) {
if (!enabled_)
return CreateDomainNotEnabledErrorResponse();
if (!process_)
return CreateContextErrorResponse();
int64_t id = 0;
if (!base::StringToInt64(registration_id, &id))
return CreateInvalidVersionIdErrorResponse();
StoragePartitionImpl* partition =
static_cast<StoragePartitionImpl*>(process_->GetStoragePartition());
BackgroundSyncContext* sync_context = partition->GetBackgroundSyncContext();
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&DispatchSyncEventOnIO, context_,
base::WrapRefCounted(sync_context),
GURL(origin), id, tag, last_chance));
return Response::OK();
}
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 | Response ServiceWorkerHandler::DispatchSyncEvent(
const std::string& origin,
const std::string& registration_id,
const std::string& tag,
bool last_chance) {
if (!enabled_)
return CreateDomainNotEnabledErrorResponse();
if (!storage_partition_)
return CreateContextErrorResponse();
int64_t id = 0;
if (!base::StringToInt64(registration_id, &id))
return CreateInvalidVersionIdErrorResponse();
BackgroundSyncContext* sync_context =
storage_partition_->GetBackgroundSyncContext();
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&DispatchSyncEventOnIO, context_,
base::WrapRefCounted(sync_context),
GURL(origin), id, tag, last_chance));
return Response::OK();
}
| 172,767 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool MediaControlsProgressView::OnMousePressed(const ui::MouseEvent& event) {
gfx::Point location_in_bar(event.location());
ConvertPointToTarget(this, this->progress_bar_, &location_in_bar);
if (!event.IsOnlyLeftMouseButton() ||
!progress_bar_->GetLocalBounds().Contains(location_in_bar)) {
return false;
}
HandleSeeking(location_in_bar);
return true;
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | bool MediaControlsProgressView::OnMousePressed(const ui::MouseEvent& event) {
if (!event.IsOnlyLeftMouseButton() || event.y() < kMinClickHeight ||
event.y() > kMaxClickHeight) {
return false;
}
HandleSeeking(event.location());
return true;
}
| 172,348 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: exsltStrAlignFunction (xmlXPathParserContextPtr ctxt, int nargs) {
xmlChar *str, *padding, *alignment, *ret;
int str_l, padding_l;
if ((nargs < 2) || (nargs > 3)) {
xmlXPathSetArityError(ctxt);
return;
}
if (nargs == 3)
alignment = xmlXPathPopString(ctxt);
else
alignment = NULL;
padding = xmlXPathPopString(ctxt);
str = xmlXPathPopString(ctxt);
str_l = xmlUTF8Strlen (str);
padding_l = xmlUTF8Strlen (padding);
if (str_l == padding_l) {
xmlXPathReturnString (ctxt, str);
xmlFree(padding);
xmlFree(alignment);
return;
}
if (str_l > padding_l) {
ret = xmlUTF8Strndup (str, padding_l);
} else {
if (xmlStrEqual(alignment, (const xmlChar *) "right")) {
ret = xmlUTF8Strndup (padding, padding_l - str_l);
ret = xmlStrcat (ret, str);
} else if (xmlStrEqual(alignment, (const xmlChar *) "center")) {
int left = (padding_l - str_l) / 2;
int right_start;
ret = xmlUTF8Strndup (padding, left);
ret = xmlStrcat (ret, str);
right_start = xmlUTF8Strsize (padding, left + str_l);
ret = xmlStrcat (ret, padding + right_start);
} else {
int str_s;
str_s = xmlStrlen (str);
ret = xmlStrdup (str);
ret = xmlStrcat (ret, padding + str_s);
}
}
xmlXPathReturnString (ctxt, ret);
xmlFree(str);
xmlFree(padding);
xmlFree(alignment);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | exsltStrAlignFunction (xmlXPathParserContextPtr ctxt, int nargs) {
xmlChar *str, *padding, *alignment, *ret;
int str_l, padding_l;
if ((nargs < 2) || (nargs > 3)) {
xmlXPathSetArityError(ctxt);
return;
}
if (nargs == 3)
alignment = xmlXPathPopString(ctxt);
else
alignment = NULL;
padding = xmlXPathPopString(ctxt);
str = xmlXPathPopString(ctxt);
str_l = xmlUTF8Strlen (str);
padding_l = xmlUTF8Strlen (padding);
if (str_l == padding_l) {
xmlXPathReturnString (ctxt, str);
xmlFree(padding);
xmlFree(alignment);
return;
}
if (str_l > padding_l) {
ret = xmlUTF8Strndup (str, padding_l);
} else {
if (xmlStrEqual(alignment, (const xmlChar *) "right")) {
ret = xmlUTF8Strndup (padding, padding_l - str_l);
ret = xmlStrcat (ret, str);
} else if (xmlStrEqual(alignment, (const xmlChar *) "center")) {
int left = (padding_l - str_l) / 2;
int right_start;
ret = xmlUTF8Strndup (padding, left);
ret = xmlStrcat (ret, str);
right_start = xmlUTF8Strsize (padding, left + str_l);
ret = xmlStrcat (ret, padding + right_start);
} else {
int str_s;
str_s = xmlUTF8Strsize(padding, str_l);
ret = xmlStrdup (str);
ret = xmlStrcat (ret, padding + str_s);
}
}
xmlXPathReturnString (ctxt, ret);
xmlFree(str);
xmlFree(padding);
xmlFree(alignment);
}
| 173,295 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MediaStreamDispatcherHost::~MediaStreamDispatcherHost() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
bindings_.CloseAllBindings();
CancelAllRequests();
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | MediaStreamDispatcherHost::~MediaStreamDispatcherHost() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
CancelAllRequests();
}
| 173,098 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {
while (begin && isspace ((ut8)str[*begin])) {
++(*begin);
}
if (!str[*begin]) { // null byte
*end = *begin;
return TT_EOF;
} else if (isalpha ((ut8)str[*begin])) { // word token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) {
++(*end);
}
return TT_WORD;
} else if (isdigit ((ut8)str[*begin])) { // number token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.
++(*end);
}
return TT_NUMBER;
} else { // special character: [, ], +, *, ...
*end = *begin + 1;
return TT_SPECIAL;
}
}
Commit Message: Fix #12239 - crash in the x86.nz assembler ##asm (#12252)
CWE ID: CWE-125 | static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {
if (*begin > strlen (str)) {
return TT_EOF;
}
while (begin && str[*begin] && isspace ((ut8)str[*begin])) {
++(*begin);
}
if (!str[*begin]) { // null byte
*end = *begin;
return TT_EOF;
}
if (isalpha ((ut8)str[*begin])) { // word token
*end = *begin;
while (end && str[*end] && isalnum ((ut8)str[*end])) {
++(*end);
}
return TT_WORD;
}
if (isdigit ((ut8)str[*begin])) { // number token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.
++(*end);
}
return TT_NUMBER;
} else { // special character: [, ], +, *, ...
*end = *begin + 1;
return TT_SPECIAL;
}
}
| 168,970 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GURL SanitizeFrontendURL(const GURL& url,
const std::string& scheme,
const std::string& host,
const std::string& path,
bool allow_query_and_fragment) {
std::vector<std::string> query_parts;
std::string fragment;
if (allow_query_and_fragment) {
for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
std::string value = SanitizeFrontendQueryParam(it.GetKey(),
it.GetValue());
if (!value.empty()) {
query_parts.push_back(
base::StringPrintf("%s=%s", it.GetKey().c_str(), value.c_str()));
}
}
if (url.has_ref())
fragment = '#' + url.ref();
}
std::string query =
query_parts.empty() ? "" : "?" + base::JoinString(query_parts, "&");
std::string constructed =
base::StringPrintf("%s://%s%s%s%s", scheme.c_str(), host.c_str(),
path.c_str(), query.c_str(), fragment.c_str());
GURL result = GURL(constructed);
if (!result.is_valid())
return GURL();
return result;
}
Commit Message: Improve sanitization of remoteFrontendUrl in DevTools
This change ensures that the decoded remoteFrontendUrl parameter cannot
contain any single quote in its value. As of this commit, none of the
permitted query params in SanitizeFrontendQueryParam can contain single
quotes.
Note that the existing SanitizeEndpoint function does not explicitly
check for single quotes. This is fine since single quotes in the query
string are already URL-encoded and the values validated by
SanitizeEndpoint are not url-decoded elsewhere.
BUG=798163
TEST=Manually, see https://crbug.com/798163#c1
TEST=./unit_tests --gtest_filter=DevToolsUIBindingsTest.SanitizeFrontendURL
Change-Id: I5a08e8ce6f1abc2c8d2a0983fef63e1e194cd242
Reviewed-on: https://chromium-review.googlesource.com/846979
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Rob Wu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#527250}
CWE ID: CWE-20 | GURL SanitizeFrontendURL(const GURL& url,
const std::string& scheme,
const std::string& host,
const std::string& path,
bool allow_query_and_fragment) {
std::vector<std::string> query_parts;
std::string fragment;
if (allow_query_and_fragment) {
for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
std::string value = SanitizeFrontendQueryParam(it.GetKey(),
it.GetValue());
if (!value.empty()) {
query_parts.push_back(
base::StringPrintf("%s=%s", it.GetKey().c_str(), value.c_str()));
}
}
if (url.has_ref() && url.ref_piece().find('\'') == base::StringPiece::npos)
fragment = '#' + url.ref();
}
std::string query =
query_parts.empty() ? "" : "?" + base::JoinString(query_parts, "&");
std::string constructed =
base::StringPrintf("%s://%s%s%s%s", scheme.c_str(), host.c_str(),
path.c_str(), query.c_str(), fragment.c_str());
GURL result = GURL(constructed);
if (!result.is_valid())
return GURL();
return result;
}
| 172,689 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(images); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);
Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);
Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);
Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1588
CWE ID: CWE-125 | MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,
MagickMax(Ar_image->columns,Cr_image->columns),1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,
MagickMax(Ai_image->columns,Ci_image->columns),1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,
MagickMax(Br_image->columns,Cr_image->columns),1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,
MagickMax(Bi_image->columns,Ci_image->columns),1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(images); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);
Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);
Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);
Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
| 170,194 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: make_error(png_store* volatile psIn, png_byte PNG_CONST colour_type,
png_byte bit_depth, int interlace_type, int test, png_const_charp name)
{
png_store * volatile ps = psIn;
context(ps, fault);
check_interlace_type(interlace_type);
Try
{
png_structp pp;
png_infop pi;
pp = set_store_for_write(ps, &pi, name);
if (pp == NULL)
Throw ps;
png_set_IHDR(pp, pi, transform_width(pp, colour_type, bit_depth),
transform_height(pp, colour_type, bit_depth), bit_depth, colour_type,
interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
if (colour_type == 3) /* palette */
init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
/* Time for a few errors; these are in various optional chunks, the
* standard tests test the standard chunks pretty well.
*/
# define exception__prev exception_prev_1
# define exception__env exception_env_1
Try
{
/* Expect this to throw: */
ps->expect_error = !error_test[test].warning;
ps->expect_warning = error_test[test].warning;
ps->saw_warning = 0;
error_test[test].fn(pp, pi);
/* Normally the error is only detected here: */
png_write_info(pp, pi);
/* And handle the case where it was only a warning: */
if (ps->expect_warning && ps->saw_warning)
Throw ps;
/* If we get here there is a problem, we have success - no error or
* no warning - when we shouldn't have success. Log an error.
*/
store_log(ps, pp, error_test[test].msg, 1 /*error*/);
}
Catch (fault)
ps = fault; /* expected exit, make sure ps is not clobbered */
#undef exception__prev
#undef exception__env
/* And clear these flags */
ps->expect_error = 0;
ps->expect_warning = 0;
/* Now write the whole image, just to make sure that the detected, or
* undetected, errro has not created problems inside libpng.
*/
if (png_get_rowbytes(pp, pi) !=
transform_rowsize(pp, colour_type, bit_depth))
png_error(pp, "row size incorrect");
else
{
png_uint_32 h = transform_height(pp, colour_type, bit_depth);
int npasses = png_set_interlace_handling(pp);
int pass;
if (npasses != npasses_from_interlace_type(pp, interlace_type))
png_error(pp, "write: png_set_interlace_handling failed");
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
for (y=0; y<h; ++y)
{
png_byte buffer[TRANSFORM_ROWMAX];
transform_row(pp, buffer, colour_type, bit_depth, y);
png_write_row(pp, buffer);
}
}
}
png_write_end(pp, pi);
/* The following deletes the file that was just written. */
store_write_reset(ps);
}
Catch(fault)
{
store_write_reset(fault);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | make_error(png_store* volatile psIn, png_byte PNG_CONST colour_type,
make_error(png_store* const ps, png_byte const colour_type,
png_byte bit_depth, int interlace_type, int test, png_const_charp name)
{
context(ps, fault);
check_interlace_type(interlace_type);
Try
{
png_infop pi;
const png_structp pp = set_store_for_write(ps, &pi, name);
png_uint_32 w, h;
gnu_volatile(pp)
if (pp == NULL)
Throw ps;
w = transform_width(pp, colour_type, bit_depth);
gnu_volatile(w)
h = transform_height(pp, colour_type, bit_depth);
gnu_volatile(h)
png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
if (colour_type == 3) /* palette */
init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
/* Time for a few errors; these are in various optional chunks, the
* standard tests test the standard chunks pretty well.
*/
# define exception__prev exception_prev_1
# define exception__env exception_env_1
Try
{
gnu_volatile(exception__prev)
/* Expect this to throw: */
ps->expect_error = !error_test[test].warning;
ps->expect_warning = error_test[test].warning;
ps->saw_warning = 0;
error_test[test].fn(pp, pi);
/* Normally the error is only detected here: */
png_write_info(pp, pi);
/* And handle the case where it was only a warning: */
if (ps->expect_warning && ps->saw_warning)
Throw ps;
/* If we get here there is a problem, we have success - no error or
* no warning - when we shouldn't have success. Log an error.
*/
store_log(ps, pp, error_test[test].msg, 1 /*error*/);
}
Catch (fault)
{ /* expected exit */
}
#undef exception__prev
#undef exception__env
/* And clear these flags */
ps->expect_error = 0;
ps->expect_warning = 0;
/* Now write the whole image, just to make sure that the detected, or
* undetected, errro has not created problems inside libpng.
*/
if (png_get_rowbytes(pp, pi) !=
transform_rowsize(pp, colour_type, bit_depth))
png_error(pp, "row size incorrect");
else
{
int npasses = set_write_interlace_handling(pp, interlace_type);
int pass;
if (npasses != npasses_from_interlace_type(pp, interlace_type))
png_error(pp, "write: png_set_interlace_handling failed");
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
for (y=0; y<h; ++y)
{
png_byte buffer[TRANSFORM_ROWMAX];
transform_row(pp, buffer, colour_type, bit_depth, y);
# if do_own_interlace
/* If do_own_interlace *and* the image is interlaced we need a
* reduced interlace row; this may be reduced to empty.
*/
if (interlace_type == PNG_INTERLACE_ADAM7)
{
/* The row must not be written if it doesn't exist, notice
* that there are two conditions here, either the row isn't
* ever in the pass or the row would be but isn't wide
* enough to contribute any pixels. In fact the wPass test
* can be used to skip the whole y loop in this case.
*/
if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
PNG_PASS_COLS(w, pass) > 0)
interlace_row(buffer, buffer,
bit_size(pp, colour_type, bit_depth), w, pass,
0/*data always bigendian*/);
else
continue;
}
# endif /* do_own_interlace */
png_write_row(pp, buffer);
}
}
}
png_write_end(pp, pi);
/* The following deletes the file that was just written. */
store_write_reset(ps);
}
Catch(fault)
{
store_write_reset(fault);
}
}
| 173,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: M_bool M_fs_path_ishidden(const char *path, M_fs_info_t *info)
{
M_list_str_t *path_parts;
size_t len;
M_bool ret = M_FALSE;
(void)info;
if (path == NULL || *path == '\0') {
return M_FALSE;
}
/* Hidden. Check if the first character of the last part of the path. Either the file or directory name itself
* starts with a '.'. */
path_parts = M_fs_path_componentize_path(path, M_FS_SYSTEM_UNIX);
len = M_list_str_len(path_parts);
if (len > 0) {
if (*M_list_str_at(path_parts, len-1) == '.') {
ret = M_TRUE;
}
}
M_list_str_destroy(path_parts);
return ret;
}
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_bool M_fs_path_ishidden(const char *path, M_fs_info_t *info)
{
M_list_str_t *path_parts;
size_t len;
M_bool ret = M_FALSE;
(void)info;
if (path == NULL || *path == '\0') {
return M_FALSE;
}
/* Hidden. Check if the first character of the last part of the path. Either the file or directory name itself
* starts with a '.'. */
path_parts = M_fs_path_componentize_path(path, M_FS_SYSTEM_UNIX);
len = M_list_str_len(path_parts);
if (len > 0) {
if (*M_list_str_at(path_parts, len-1) == '.') {
ret = M_TRUE;
}
}
M_list_str_destroy(path_parts);
return ret;
}
| 169,145 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: tbGetBuffer(unsigned size)
{
char *rtrn;
if (size >= BUFFER_SIZE)
return NULL;
if ((BUFFER_SIZE - tbNext) <= size)
tbNext = 0;
rtrn = &textBuffer[tbNext];
tbNext += size;
return rtrn;
}
Commit Message:
CWE ID: CWE-119 | tbGetBuffer(unsigned size)
{
struct textBuffer *tb;
tb = &textBuffer[textBufferIndex];
textBufferIndex = (textBufferIndex + 1) % NUM_BUFFER;
if (size > tb->size) {
free(tb->buffer);
tb->buffer = xnfalloc(size);
tb->size = size;
}
return tb->buffer;
}
| 164,692 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pipe_read(struct kiocb *iocb, const struct iovec *_iov,
unsigned long nr_segs, loff_t pos)
{
struct file *filp = iocb->ki_filp;
struct pipe_inode_info *pipe = filp->private_data;
int do_wakeup;
ssize_t ret;
struct iovec *iov = (struct iovec *)_iov;
size_t total_len;
total_len = iov_length(iov, nr_segs);
/* Null read succeeds. */
if (unlikely(total_len == 0))
return 0;
do_wakeup = 0;
ret = 0;
__pipe_lock(pipe);
for (;;) {
int bufs = pipe->nrbufs;
if (bufs) {
int curbuf = pipe->curbuf;
struct pipe_buffer *buf = pipe->bufs + curbuf;
const struct pipe_buf_operations *ops = buf->ops;
void *addr;
size_t chars = buf->len;
int error, atomic;
if (chars > total_len)
chars = total_len;
error = ops->confirm(pipe, buf);
if (error) {
if (!ret)
ret = error;
break;
}
atomic = !iov_fault_in_pages_write(iov, chars);
redo:
if (atomic)
addr = kmap_atomic(buf->page);
else
addr = kmap(buf->page);
error = pipe_iov_copy_to_user(iov, addr + buf->offset, chars, atomic);
if (atomic)
kunmap_atomic(addr);
else
kunmap(buf->page);
if (unlikely(error)) {
/*
* Just retry with the slow path if we failed.
*/
if (atomic) {
atomic = 0;
goto redo;
}
if (!ret)
ret = error;
break;
}
ret += chars;
buf->offset += chars;
buf->len -= chars;
/* Was it a packet buffer? Clean up and exit */
if (buf->flags & PIPE_BUF_FLAG_PACKET) {
total_len = chars;
buf->len = 0;
}
if (!buf->len) {
buf->ops = NULL;
ops->release(pipe, buf);
curbuf = (curbuf + 1) & (pipe->buffers - 1);
pipe->curbuf = curbuf;
pipe->nrbufs = --bufs;
do_wakeup = 1;
}
total_len -= chars;
if (!total_len)
break; /* common path: read succeeded */
}
if (bufs) /* More to do? */
continue;
if (!pipe->writers)
break;
if (!pipe->waiting_writers) {
/* syscall merging: Usually we must not sleep
* if O_NONBLOCK is set, or if we got some data.
* But if a writer sleeps in kernel space, then
* we can wait for that data without violating POSIX.
*/
if (ret)
break;
if (filp->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
break;
}
}
if (signal_pending(current)) {
if (!ret)
ret = -ERESTARTSYS;
break;
}
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}
pipe_wait(pipe);
}
__pipe_unlock(pipe);
/* Signal writers asynchronously that there is more room. */
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}
if (ret > 0)
file_accessed(filp);
return ret;
}
Commit Message: switch pipe_read() to copy_page_to_iter()
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | pipe_read(struct kiocb *iocb, const struct iovec *_iov,
unsigned long nr_segs, loff_t pos)
{
struct file *filp = iocb->ki_filp;
struct pipe_inode_info *pipe = filp->private_data;
int do_wakeup;
ssize_t ret;
struct iovec *iov = (struct iovec *)_iov;
size_t total_len;
struct iov_iter iter;
total_len = iov_length(iov, nr_segs);
/* Null read succeeds. */
if (unlikely(total_len == 0))
return 0;
iov_iter_init(&iter, iov, nr_segs, total_len, 0);
do_wakeup = 0;
ret = 0;
__pipe_lock(pipe);
for (;;) {
int bufs = pipe->nrbufs;
if (bufs) {
int curbuf = pipe->curbuf;
struct pipe_buffer *buf = pipe->bufs + curbuf;
const struct pipe_buf_operations *ops = buf->ops;
size_t chars = buf->len;
size_t written;
int error;
if (chars > total_len)
chars = total_len;
error = ops->confirm(pipe, buf);
if (error) {
if (!ret)
ret = error;
break;
}
written = copy_page_to_iter(buf->page, buf->offset, chars, &iter);
if (unlikely(written < chars)) {
if (!ret)
ret = -EFAULT;
break;
}
ret += chars;
buf->offset += chars;
buf->len -= chars;
/* Was it a packet buffer? Clean up and exit */
if (buf->flags & PIPE_BUF_FLAG_PACKET) {
total_len = chars;
buf->len = 0;
}
if (!buf->len) {
buf->ops = NULL;
ops->release(pipe, buf);
curbuf = (curbuf + 1) & (pipe->buffers - 1);
pipe->curbuf = curbuf;
pipe->nrbufs = --bufs;
do_wakeup = 1;
}
total_len -= chars;
if (!total_len)
break; /* common path: read succeeded */
}
if (bufs) /* More to do? */
continue;
if (!pipe->writers)
break;
if (!pipe->waiting_writers) {
/* syscall merging: Usually we must not sleep
* if O_NONBLOCK is set, or if we got some data.
* But if a writer sleeps in kernel space, then
* we can wait for that data without violating POSIX.
*/
if (ret)
break;
if (filp->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
break;
}
}
if (signal_pending(current)) {
if (!ret)
ret = -ERESTARTSYS;
break;
}
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}
pipe_wait(pipe);
}
__pipe_unlock(pipe);
/* Signal writers asynchronously that there is more room. */
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}
if (ret > 0)
file_accessed(filp);
return ret;
}
| 169,929 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
msg->msg_namelen = 0;
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
| 166,485 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BaseRenderingContext2D::setFillStyle(
const StringOrCanvasGradientOrCanvasPattern& style) {
DCHECK(!style.IsNull());
ValidateStateStack();
String color_string;
CanvasStyle* canvas_style = nullptr;
if (style.IsString()) {
color_string = style.GetAsString();
if (color_string == GetState().UnparsedFillColor())
return;
Color parsed_color = 0;
if (!ParseColorOrCurrentColor(parsed_color, color_string))
return;
if (GetState().FillStyle()->IsEquivalentRGBA(parsed_color.Rgb())) {
ModifiableState().SetUnparsedFillColor(color_string);
return;
}
canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb());
} else if (style.IsCanvasGradient()) {
canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient());
} else if (style.IsCanvasPattern()) {
CanvasPattern* canvas_pattern = style.GetAsCanvasPattern();
if (OriginClean() && !canvas_pattern->OriginClean()) {
SetOriginTainted();
ClearResolvedFilters();
}
if (canvas_pattern->GetPattern()->IsTextureBacked())
DisableDeferral(kDisableDeferralReasonUsingTextureBackedPattern);
canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern);
}
DCHECK(canvas_style);
ModifiableState().SetFillStyle(canvas_style);
ModifiableState().SetUnparsedFillColor(color_string);
ModifiableState().ClearResolvedFilter();
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Chris Harrelson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200 | void BaseRenderingContext2D::setFillStyle(
const StringOrCanvasGradientOrCanvasPattern& style) {
DCHECK(!style.IsNull());
ValidateStateStack();
String color_string;
CanvasStyle* canvas_style = nullptr;
if (style.IsString()) {
color_string = style.GetAsString();
if (color_string == GetState().UnparsedFillColor())
return;
Color parsed_color = 0;
if (!ParseColorOrCurrentColor(parsed_color, color_string))
return;
if (GetState().FillStyle()->IsEquivalentRGBA(parsed_color.Rgb())) {
ModifiableState().SetUnparsedFillColor(color_string);
return;
}
canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb());
} else if (style.IsCanvasGradient()) {
canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient());
} else if (style.IsCanvasPattern()) {
CanvasPattern* canvas_pattern = style.GetAsCanvasPattern();
if (!origin_tainted_by_content_ && !canvas_pattern->OriginClean()) {
SetOriginTaintedByContent();
}
if (canvas_pattern->GetPattern()->IsTextureBacked())
DisableDeferral(kDisableDeferralReasonUsingTextureBackedPattern);
canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern);
}
DCHECK(canvas_style);
ModifiableState().SetFillStyle(canvas_style);
ModifiableState().SetUnparsedFillColor(color_string);
ModifiableState().ClearResolvedFilter();
}
| 172,908 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ext4_ext_split(handle_t *handle, struct inode *inode,
unsigned int flags,
struct ext4_ext_path *path,
struct ext4_extent *newext, int at)
{
struct buffer_head *bh = NULL;
int depth = ext_depth(inode);
struct ext4_extent_header *neh;
struct ext4_extent_idx *fidx;
int i = at, k, m, a;
ext4_fsblk_t newblock, oldblock;
__le32 border;
ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
int err = 0;
/* make decision: where to split? */
/* FIXME: now decision is simplest: at current extent */
/* if current leaf will be split, then we should use
* border from split point */
if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
return -EFSCORRUPTED;
}
if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
border = path[depth].p_ext[1].ee_block;
ext_debug("leaf will be split."
" next leaf starts at %d\n",
le32_to_cpu(border));
} else {
border = newext->ee_block;
ext_debug("leaf will be added."
" next leaf starts at %d\n",
le32_to_cpu(border));
}
/*
* If error occurs, then we break processing
* and mark filesystem read-only. index won't
* be inserted and tree will be in consistent
* state. Next mount will repair buffers too.
*/
/*
* Get array to track all allocated blocks.
* We need this to handle errors and free blocks
* upon them.
*/
ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), GFP_NOFS);
if (!ablocks)
return -ENOMEM;
/* allocate all needed blocks */
ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
for (a = 0; a < depth - at; a++) {
newblock = ext4_ext_new_meta_block(handle, inode, path,
newext, &err, flags);
if (newblock == 0)
goto cleanup;
ablocks[a] = newblock;
}
/* initialize new leaf */
newblock = ablocks[--a];
if (unlikely(newblock == 0)) {
EXT4_ERROR_INODE(inode, "newblock == 0!");
err = -EFSCORRUPTED;
goto cleanup;
}
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = 0;
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_depth = 0;
/* move remainder of path[depth] to the new leaf */
if (unlikely(path[depth].p_hdr->eh_entries !=
path[depth].p_hdr->eh_max)) {
EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
path[depth].p_hdr->eh_entries,
path[depth].p_hdr->eh_max);
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy from next extent */
m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
ext4_ext_show_move(inode, path, newblock, depth);
if (m) {
struct ext4_extent *ex;
ex = EXT_FIRST_EXTENT(neh);
memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
le16_add_cpu(&neh->eh_entries, m);
}
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old leaf */
if (m) {
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto cleanup;
}
/* create intermediate indexes */
k = depth - at - 1;
if (unlikely(k < 0)) {
EXT4_ERROR_INODE(inode, "k %d < 0!", k);
err = -EFSCORRUPTED;
goto cleanup;
}
if (k)
ext_debug("create %d intermediate indices\n", k);
/* insert new index into current index block */
/* current depth stored in i var */
i = depth - 1;
while (k--) {
oldblock = newblock;
newblock = ablocks[--a];
bh = sb_getblk(inode->i_sb, newblock);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = cpu_to_le16(1);
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
neh->eh_depth = cpu_to_le16(depth - i);
fidx = EXT_FIRST_INDEX(neh);
fidx->ei_block = border;
ext4_idx_store_pblock(fidx, oldblock);
ext_debug("int.index at %d (block %llu): %u -> %llu\n",
i, newblock, le32_to_cpu(border), oldblock);
/* move remainder of path[i] to the new index block */
if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
EXT_LAST_INDEX(path[i].p_hdr))) {
EXT4_ERROR_INODE(inode,
"EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
le32_to_cpu(path[i].p_ext->ee_block));
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy indexes */
m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
EXT_MAX_INDEX(path[i].p_hdr));
ext4_ext_show_move(inode, path, newblock, i);
if (m) {
memmove(++fidx, path[i].p_idx,
sizeof(struct ext4_extent_idx) * m);
le16_add_cpu(&neh->eh_entries, m);
}
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old index */
if (m) {
err = ext4_ext_get_access(handle, inode, path + i);
if (err)
goto cleanup;
le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + i);
if (err)
goto cleanup;
}
i--;
}
/* insert new index */
err = ext4_ext_insert_index(handle, inode, path + at,
le32_to_cpu(border), newblock);
cleanup:
if (bh) {
if (buffer_locked(bh))
unlock_buffer(bh);
brelse(bh);
}
if (err) {
/* free all allocated blocks in error case */
for (i = 0; i < depth; i++) {
if (!ablocks[i])
continue;
ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
EXT4_FREE_BLOCKS_METADATA);
}
}
kfree(ablocks);
return err;
}
Commit Message: ext4: zero out the unused memory region in the extent tree block
This commit zeroes out the unused memory region in the buffer_head
corresponding to the extent metablock after writing the extent header
and the corresponding extent node entries.
This is done to prevent random uninitialized data from getting into
the filesystem when the extent block is synced.
This fixes CVE-2019-11833.
Signed-off-by: Sriram Rajagopalan <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
Cc: [email protected]
CWE ID: CWE-200 | static int ext4_ext_split(handle_t *handle, struct inode *inode,
unsigned int flags,
struct ext4_ext_path *path,
struct ext4_extent *newext, int at)
{
struct buffer_head *bh = NULL;
int depth = ext_depth(inode);
struct ext4_extent_header *neh;
struct ext4_extent_idx *fidx;
int i = at, k, m, a;
ext4_fsblk_t newblock, oldblock;
__le32 border;
ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
int err = 0;
size_t ext_size = 0;
/* make decision: where to split? */
/* FIXME: now decision is simplest: at current extent */
/* if current leaf will be split, then we should use
* border from split point */
if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
return -EFSCORRUPTED;
}
if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
border = path[depth].p_ext[1].ee_block;
ext_debug("leaf will be split."
" next leaf starts at %d\n",
le32_to_cpu(border));
} else {
border = newext->ee_block;
ext_debug("leaf will be added."
" next leaf starts at %d\n",
le32_to_cpu(border));
}
/*
* If error occurs, then we break processing
* and mark filesystem read-only. index won't
* be inserted and tree will be in consistent
* state. Next mount will repair buffers too.
*/
/*
* Get array to track all allocated blocks.
* We need this to handle errors and free blocks
* upon them.
*/
ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), GFP_NOFS);
if (!ablocks)
return -ENOMEM;
/* allocate all needed blocks */
ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
for (a = 0; a < depth - at; a++) {
newblock = ext4_ext_new_meta_block(handle, inode, path,
newext, &err, flags);
if (newblock == 0)
goto cleanup;
ablocks[a] = newblock;
}
/* initialize new leaf */
newblock = ablocks[--a];
if (unlikely(newblock == 0)) {
EXT4_ERROR_INODE(inode, "newblock == 0!");
err = -EFSCORRUPTED;
goto cleanup;
}
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = 0;
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_depth = 0;
/* move remainder of path[depth] to the new leaf */
if (unlikely(path[depth].p_hdr->eh_entries !=
path[depth].p_hdr->eh_max)) {
EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
path[depth].p_hdr->eh_entries,
path[depth].p_hdr->eh_max);
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy from next extent */
m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
ext4_ext_show_move(inode, path, newblock, depth);
if (m) {
struct ext4_extent *ex;
ex = EXT_FIRST_EXTENT(neh);
memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
le16_add_cpu(&neh->eh_entries, m);
}
/* zero out unused area in the extent block */
ext_size = sizeof(struct ext4_extent_header) +
sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old leaf */
if (m) {
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto cleanup;
}
/* create intermediate indexes */
k = depth - at - 1;
if (unlikely(k < 0)) {
EXT4_ERROR_INODE(inode, "k %d < 0!", k);
err = -EFSCORRUPTED;
goto cleanup;
}
if (k)
ext_debug("create %d intermediate indices\n", k);
/* insert new index into current index block */
/* current depth stored in i var */
i = depth - 1;
while (k--) {
oldblock = newblock;
newblock = ablocks[--a];
bh = sb_getblk(inode->i_sb, newblock);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = cpu_to_le16(1);
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
neh->eh_depth = cpu_to_le16(depth - i);
fidx = EXT_FIRST_INDEX(neh);
fidx->ei_block = border;
ext4_idx_store_pblock(fidx, oldblock);
ext_debug("int.index at %d (block %llu): %u -> %llu\n",
i, newblock, le32_to_cpu(border), oldblock);
/* move remainder of path[i] to the new index block */
if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
EXT_LAST_INDEX(path[i].p_hdr))) {
EXT4_ERROR_INODE(inode,
"EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
le32_to_cpu(path[i].p_ext->ee_block));
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy indexes */
m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
EXT_MAX_INDEX(path[i].p_hdr));
ext4_ext_show_move(inode, path, newblock, i);
if (m) {
memmove(++fidx, path[i].p_idx,
sizeof(struct ext4_extent_idx) * m);
le16_add_cpu(&neh->eh_entries, m);
}
/* zero out unused area in the extent block */
ext_size = sizeof(struct ext4_extent_header) +
(sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
memset(bh->b_data + ext_size, 0,
inode->i_sb->s_blocksize - ext_size);
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old index */
if (m) {
err = ext4_ext_get_access(handle, inode, path + i);
if (err)
goto cleanup;
le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + i);
if (err)
goto cleanup;
}
i--;
}
/* insert new index */
err = ext4_ext_insert_index(handle, inode, path + at,
le32_to_cpu(border), newblock);
cleanup:
if (bh) {
if (buffer_locked(bh))
unlock_buffer(bh);
brelse(bh);
}
if (err) {
/* free all allocated blocks in error case */
for (i = 0; i < depth; i++) {
if (!ablocks[i])
continue;
ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
EXT4_FREE_BLOCKS_METADATA);
}
}
kfree(ablocks);
return err;
}
| 169,678 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int check_entry_size_and_hooks(struct arpt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!arp_checkentry(&e->arp))
return -EINVAL;
err = xt_check_entry_offsets(e, e->target_offset, e->next_offset);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
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 | static inline int check_entry_size_and_hooks(struct arpt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!arp_checkentry(&e->arp))
return -EINVAL;
err = xt_check_entry_offsets(e, e->elems, e->target_offset,
e->next_offset);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void __ip_select_ident(struct net *net, struct iphdr *iph, int segs)
{
static u32 ip_idents_hashrnd __read_mostly;
u32 hash, id;
net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd));
hash = jhash_3words((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol ^ net_hash_mix(net),
ip_idents_hashrnd);
id = ip_idents_reserve(hash, segs);
iph->id = htons(id);
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | void __ip_select_ident(struct net *net, struct iphdr *iph, int segs)
{
u32 hash, id;
/* Note the following code is not safe, but this is okay. */
if (unlikely(siphash_key_is_zero(&net->ipv4.ip_id_key)))
get_random_bytes(&net->ipv4.ip_id_key,
sizeof(net->ipv4.ip_id_key));
hash = siphash_3u32((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol,
&net->ipv4.ip_id_key);
id = ip_idents_reserve(hash, segs);
iph->id = htons(id);
}
| 169,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op;
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
Commit Message: Fix #9943 - Invalid free on RAnal.avr
CWE ID: CWE-416 | INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op = {0};
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
| 169,222 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. 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
length;
length=count*quantum;
if ((count == 0) || (quantum != (length/count)))
{
errno=ENOMEM;
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));
memory_info->length=length;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,length) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,length);
if (memory_info->blob != NULL)
memory_info->type=AlignedVirtualMemory;
else
RelinquishMagickResource(MemoryResource,length);
}
if ((memory_info->blob == NULL) &&
(AcquireMagickResource(MapResource,length) != MagickFalse))
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,length);
if (memory_info->blob != NULL)
memory_info->type=MapVirtualMemory;
else
RelinquishMagickResource(MapResource,length);
}
if (memory_info->blob == NULL)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
if ((lseek(file,length-1,SEEK_SET) >= 0) && (write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,length);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
(void) AcquireMagickResource(MapResource,length);
}
}
(void) close(file);
}
}
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(length);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
Commit Message:
CWE ID: CWE-189 | MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
length;
length=count*quantum;
if ((count == 0) || (quantum != (length/count)))
{
errno=ENOMEM;
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));
memory_info->length=length;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,length) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,length);
if (memory_info->blob != NULL)
memory_info->type=AlignedVirtualMemory;
else
RelinquishMagickResource(MemoryResource,length);
}
if ((memory_info->blob == NULL) &&
(AcquireMagickResource(MapResource,length) != MagickFalse))
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,length);
if (memory_info->blob != NULL)
memory_info->type=MapVirtualMemory;
else
RelinquishMagickResource(MapResource,length);
}
if ((memory_info->blob == NULL) &&
(AcquireMagickResource(DiskResource,length) != MagickFalse))
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file == -1)
RelinquishMagickResource(DiskResource,length);
else
{
if ((lseek(file,length-1,SEEK_SET) < 0) || (write(file,"",1) != 1))
RelinquishMagickResource(DiskResource,length);
else
{
if (AcquireMagickResource(MapResource,length) == MagickFalse)
RelinquishMagickResource(DiskResource,length);
else
{
memory_info->blob=MapBlob(file,IOMode,0,length);
if (memory_info->blob != NULL)
memory_info->type=MapVirtualMemory;
else
{
RelinquishMagickResource(MapResource,length);
RelinquishMagickResource(DiskResource,length);
}
}
}
(void) close(file);
}
}
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(length);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
| 168,859 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Chapters::Edition::ShallowCopy(Edition& rhs) const
{
rhs.m_atoms = m_atoms;
rhs.m_atoms_size = m_atoms_size;
rhs.m_atoms_count = m_atoms_count;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void Chapters::Edition::ShallowCopy(Edition& rhs) const
rhs.m_displays = m_displays;
rhs.m_displays_size = m_displays_size;
rhs.m_displays_count = m_displays_count;
}
| 174,441 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ieee80211_radiotap_iterator_init(
struct ieee80211_radiotap_iterator *iterator,
struct ieee80211_radiotap_header *radiotap_header,
int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns)
{
/* Linux only supports version 0 radiotap format */
if (radiotap_header->it_version)
return -EINVAL;
/* sanity check for allowed length and radiotap length field */
if (max_length < get_unaligned_le16(&radiotap_header->it_len))
return -EINVAL;
iterator->_rtheader = radiotap_header;
iterator->_max_length = get_unaligned_le16(&radiotap_header->it_len);
iterator->_arg_index = 0;
iterator->_bitmap_shifter = get_unaligned_le32(&radiotap_header->it_present);
iterator->_arg = (uint8_t *)radiotap_header + sizeof(*radiotap_header);
iterator->_reset_on_ext = 0;
iterator->_next_bitmap = &radiotap_header->it_present;
iterator->_next_bitmap++;
iterator->_vns = vns;
iterator->current_namespace = &radiotap_ns;
iterator->is_radiotap_ns = 1;
/* find payload start allowing for extended bitmap(s) */
if (iterator->_bitmap_shifter & (1<<IEEE80211_RADIOTAP_EXT)) {
while (get_unaligned_le32(iterator->_arg) &
(1 << IEEE80211_RADIOTAP_EXT)) {
iterator->_arg += sizeof(uint32_t);
/*
* check for insanity where the present bitmaps
* keep claiming to extend up to or even beyond the
* stated radiotap header length
*/
if ((unsigned long)iterator->_arg -
(unsigned long)iterator->_rtheader >
(unsigned long)iterator->_max_length)
return -EINVAL;
}
iterator->_arg += sizeof(uint32_t);
/*
* no need to check again for blowing past stated radiotap
* header length, because ieee80211_radiotap_iterator_next
* checks it before it is dereferenced
*/
}
iterator->this_arg = iterator->_arg;
/* we are all initialized happily */
return 0;
}
Commit Message: wireless: radiotap: fix parsing buffer overrun
When parsing an invalid radiotap header, the parser can overrun
the buffer that is passed in because it doesn't correctly check
1) the minimum radiotap header size
2) the space for extended bitmaps
The first issue doesn't affect any in-kernel user as they all
check the minimum size before calling the radiotap function.
The second issue could potentially affect the kernel if an skb
is passed in that consists only of the radiotap header with a
lot of extended bitmaps that extend past the SKB. In that case
a read-only buffer overrun by at most 4 bytes is possible.
Fix this by adding the appropriate checks to the parser.
Cc: [email protected]
Reported-by: Evan Huus <[email protected]>
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-119 | int ieee80211_radiotap_iterator_init(
struct ieee80211_radiotap_iterator *iterator,
struct ieee80211_radiotap_header *radiotap_header,
int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns)
{
/* check the radiotap header can actually be present */
if (max_length < sizeof(struct ieee80211_radiotap_header))
return -EINVAL;
/* Linux only supports version 0 radiotap format */
if (radiotap_header->it_version)
return -EINVAL;
/* sanity check for allowed length and radiotap length field */
if (max_length < get_unaligned_le16(&radiotap_header->it_len))
return -EINVAL;
iterator->_rtheader = radiotap_header;
iterator->_max_length = get_unaligned_le16(&radiotap_header->it_len);
iterator->_arg_index = 0;
iterator->_bitmap_shifter = get_unaligned_le32(&radiotap_header->it_present);
iterator->_arg = (uint8_t *)radiotap_header + sizeof(*radiotap_header);
iterator->_reset_on_ext = 0;
iterator->_next_bitmap = &radiotap_header->it_present;
iterator->_next_bitmap++;
iterator->_vns = vns;
iterator->current_namespace = &radiotap_ns;
iterator->is_radiotap_ns = 1;
/* find payload start allowing for extended bitmap(s) */
if (iterator->_bitmap_shifter & (1<<IEEE80211_RADIOTAP_EXT)) {
while (get_unaligned_le32(iterator->_arg) &
(1 << IEEE80211_RADIOTAP_EXT)) {
iterator->_arg += sizeof(uint32_t);
/*
* check for insanity where the present bitmaps
* keep claiming to extend up to or even beyond the
* stated radiotap header length
*/
if ((unsigned long)iterator->_arg -
(unsigned long)iterator->_rtheader +
sizeof(uint32_t) >
(unsigned long)iterator->_max_length)
return -EINVAL;
}
iterator->_arg += sizeof(uint32_t);
/*
* no need to check again for blowing past stated radiotap
* header length, because ieee80211_radiotap_iterator_next
* checks it before it is dereferenced
*/
}
iterator->this_arg = iterator->_arg;
/* we are all initialized happily */
return 0;
}
| 165,909 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process)
{
int ret, status;
pid_t init_pid, pid, attached_pid, expected;
struct lxc_proc_context_info *init_ctx;
char* cwd;
char* new_cwd;
int ipc_sockets[2];
signed long personality;
if (!options)
options = &attach_static_default_options;
init_pid = lxc_cmd_get_init_pid(name, lxcpath);
if (init_pid < 0) {
ERROR("failed to get the init pid");
return -1;
}
init_ctx = lxc_proc_get_context_info(init_pid);
if (!init_ctx) {
ERROR("failed to get context of the init process, pid = %ld", (long)init_pid);
return -1;
}
personality = get_personality(name, lxcpath);
if (init_ctx->personality < 0) {
ERROR("Failed to get personality of the container");
lxc_proc_put_context_info(init_ctx);
return -1;
}
init_ctx->personality = personality;
if (!fetch_seccomp(name, lxcpath, init_ctx, options))
WARN("Failed to get seccomp policy");
cwd = getcwd(NULL, 0);
/* determine which namespaces the container was created with
* by asking lxc-start, if necessary
*/
if (options->namespaces == -1) {
options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath);
/* call failed */
if (options->namespaces == -1) {
ERROR("failed to automatically determine the "
"namespaces which the container unshared");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
}
/* create a socket pair for IPC communication; set SOCK_CLOEXEC in order
* to make sure we don't irritate other threads that want to fork+exec away
*
* IMPORTANT: if the initial process is multithreaded and another call
* just fork()s away without exec'ing directly after, the socket fd will
* exist in the forked process from the other thread and any close() in
* our own child process will not really cause the socket to close properly,
* potentiall causing the parent to hang.
*
* For this reason, while IPC is still active, we have to use shutdown()
* if the child exits prematurely in order to signal that the socket
* is closed and cannot assume that the child exiting will automatically
* do that.
*
* IPC mechanism: (X is receiver)
* initial process intermediate attached
* X <--- send pid of
* attached proc,
* then exit
* send 0 ------------------------------------> X
* [do initialization]
* X <------------------------------------ send 1
* [add to cgroup, ...]
* send 2 ------------------------------------> X
* close socket close socket
* run program
*/
ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
if (ret < 0) {
SYSERROR("could not set up required IPC mechanism for attaching");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
/* create intermediate subprocess, three reasons:
* 1. runs all pthread_atfork handlers and the
* child will no longer be threaded
* (we can't properly setns() in a threaded process)
* 2. we can't setns() in the child itself, since
* we want to make sure we are properly attached to
* the pidns
* 3. also, the initial thread has to put the attached
* process into the cgroup, which we can only do if
* we didn't already setns() (otherwise, user
* namespaces will hate us)
*/
pid = fork();
if (pid < 0) {
SYSERROR("failed to create first subprocess");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
if (pid) {
pid_t to_cleanup_pid = pid;
/* initial thread, we close the socket that is for the
* subprocesses
*/
close(ipc_sockets[1]);
free(cwd);
/* attach to cgroup, if requested */
if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
if (!cgroup_attach(name, lxcpath, pid))
goto cleanup_error;
}
/* Let the child process know to go ahead */
status = 0;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("error using IPC to notify attached process for initialization (0)");
goto cleanup_error;
}
/* get pid from intermediate process */
ret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL);
if (ret <= 0) {
if (ret != 0)
ERROR("error using IPC to receive pid of attached process");
goto cleanup_error;
}
/* ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313 */
if (options->stdin_fd == 0) {
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
}
/* reap intermediate process */
ret = wait_for_pid(pid);
if (ret < 0)
goto cleanup_error;
/* we will always have to reap the grandchild now */
to_cleanup_pid = attached_pid;
/* tell attached process it may start initializing */
status = 0;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("error using IPC to notify attached process for initialization (0)");
goto cleanup_error;
}
/* wait for the attached process to finish initializing */
expected = 1;
ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected);
if (ret <= 0) {
if (ret != 0)
ERROR("error using IPC to receive notification from attached process (1)");
goto cleanup_error;
}
/* tell attached process we're done */
status = 2;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("error using IPC to notify attached process for initialization (2)");
goto cleanup_error;
}
/* now shut down communication with child, we're done */
shutdown(ipc_sockets[0], SHUT_RDWR);
close(ipc_sockets[0]);
lxc_proc_put_context_info(init_ctx);
/* we're done, the child process should now execute whatever
* it is that the user requested. The parent can now track it
* with waitpid() or similar.
*/
*attached_process = attached_pid;
return 0;
cleanup_error:
/* first shut down the socket, then wait for the pid,
* otherwise the pid we're waiting for may never exit
*/
shutdown(ipc_sockets[0], SHUT_RDWR);
close(ipc_sockets[0]);
if (to_cleanup_pid)
(void) wait_for_pid(to_cleanup_pid);
lxc_proc_put_context_info(init_ctx);
return -1;
}
/* first subprocess begins here, we close the socket that is for the
* initial thread
*/
close(ipc_sockets[0]);
/* Wait for the parent to have setup cgroups */
expected = 0;
status = -1;
ret = lxc_read_nointr_expect(ipc_sockets[1], &status, sizeof(status), &expected);
if (ret <= 0) {
ERROR("error communicating with child process");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
/* attach now, create another subprocess later, since pid namespaces
* only really affect the children of the current process
*/
ret = lxc_attach_to_ns(init_pid, options->namespaces);
if (ret < 0) {
ERROR("failed to enter the namespace");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
/* attach succeeded, try to cwd */
if (options->initial_cwd)
new_cwd = options->initial_cwd;
else
new_cwd = cwd;
ret = chdir(new_cwd);
if (ret < 0)
WARN("could not change directory to '%s'", new_cwd);
free(cwd);
/* now create the real child process */
{
struct attach_clone_payload payload = {
.ipc_socket = ipc_sockets[1],
.options = options,
.init_ctx = init_ctx,
.exec_function = exec_function,
.exec_payload = exec_payload
};
/* We use clone_parent here to make this subprocess a direct child of
* the initial process. Then this intermediate process can exit and
* the parent can directly track the attached process.
*/
pid = lxc_clone(attach_child_main, &payload, CLONE_PARENT);
}
/* shouldn't happen, clone() should always return positive pid */
if (pid <= 0) {
SYSERROR("failed to create subprocess");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
/* tell grandparent the pid of the pid of the newly created child */
ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid));
if (ret != sizeof(pid)) {
/* if this really happens here, this is very unfortunate, since the
* parent will not know the pid of the attached process and will
* not be able to wait for it (and we won't either due to CLONE_PARENT)
* so the parent won't be able to reap it and the attached process
* will remain a zombie
*/
ERROR("error using IPC to notify main process of pid of the attached process");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
/* the rest is in the hands of the initial and the attached process */
rexit(0);
}
Commit Message: CVE-2015-1334: Don't use the container's /proc during attach
A user could otherwise over-mount /proc and prevent the apparmor profile
or selinux label from being written which combined with a modified
/bin/sh or other commonly used binary would lead to unconfined code
execution.
Reported-by: Roman Fiedler
Signed-off-by: Stéphane Graber <[email protected]>
CWE ID: CWE-17 | int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process)
{
int ret, status;
pid_t init_pid, pid, attached_pid, expected;
struct lxc_proc_context_info *init_ctx;
char* cwd;
char* new_cwd;
int ipc_sockets[2];
int procfd;
signed long personality;
if (!options)
options = &attach_static_default_options;
init_pid = lxc_cmd_get_init_pid(name, lxcpath);
if (init_pid < 0) {
ERROR("failed to get the init pid");
return -1;
}
init_ctx = lxc_proc_get_context_info(init_pid);
if (!init_ctx) {
ERROR("failed to get context of the init process, pid = %ld", (long)init_pid);
return -1;
}
personality = get_personality(name, lxcpath);
if (init_ctx->personality < 0) {
ERROR("Failed to get personality of the container");
lxc_proc_put_context_info(init_ctx);
return -1;
}
init_ctx->personality = personality;
if (!fetch_seccomp(name, lxcpath, init_ctx, options))
WARN("Failed to get seccomp policy");
cwd = getcwd(NULL, 0);
/* determine which namespaces the container was created with
* by asking lxc-start, if necessary
*/
if (options->namespaces == -1) {
options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath);
/* call failed */
if (options->namespaces == -1) {
ERROR("failed to automatically determine the "
"namespaces which the container unshared");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
}
/* create a socket pair for IPC communication; set SOCK_CLOEXEC in order
* to make sure we don't irritate other threads that want to fork+exec away
*
* IMPORTANT: if the initial process is multithreaded and another call
* just fork()s away without exec'ing directly after, the socket fd will
* exist in the forked process from the other thread and any close() in
* our own child process will not really cause the socket to close properly,
* potentiall causing the parent to hang.
*
* For this reason, while IPC is still active, we have to use shutdown()
* if the child exits prematurely in order to signal that the socket
* is closed and cannot assume that the child exiting will automatically
* do that.
*
* IPC mechanism: (X is receiver)
* initial process intermediate attached
* X <--- send pid of
* attached proc,
* then exit
* send 0 ------------------------------------> X
* [do initialization]
* X <------------------------------------ send 1
* [add to cgroup, ...]
* send 2 ------------------------------------> X
* close socket close socket
* run program
*/
ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
if (ret < 0) {
SYSERROR("could not set up required IPC mechanism for attaching");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
/* create intermediate subprocess, three reasons:
* 1. runs all pthread_atfork handlers and the
* child will no longer be threaded
* (we can't properly setns() in a threaded process)
* 2. we can't setns() in the child itself, since
* we want to make sure we are properly attached to
* the pidns
* 3. also, the initial thread has to put the attached
* process into the cgroup, which we can only do if
* we didn't already setns() (otherwise, user
* namespaces will hate us)
*/
pid = fork();
if (pid < 0) {
SYSERROR("failed to create first subprocess");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
if (pid) {
pid_t to_cleanup_pid = pid;
/* initial thread, we close the socket that is for the
* subprocesses
*/
close(ipc_sockets[1]);
free(cwd);
/* attach to cgroup, if requested */
if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
if (!cgroup_attach(name, lxcpath, pid))
goto cleanup_error;
}
/* Let the child process know to go ahead */
status = 0;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("error using IPC to notify attached process for initialization (0)");
goto cleanup_error;
}
/* get pid from intermediate process */
ret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL);
if (ret <= 0) {
if (ret != 0)
ERROR("error using IPC to receive pid of attached process");
goto cleanup_error;
}
/* ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313 */
if (options->stdin_fd == 0) {
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
}
/* reap intermediate process */
ret = wait_for_pid(pid);
if (ret < 0)
goto cleanup_error;
/* we will always have to reap the grandchild now */
to_cleanup_pid = attached_pid;
/* tell attached process it may start initializing */
status = 0;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("error using IPC to notify attached process for initialization (0)");
goto cleanup_error;
}
/* wait for the attached process to finish initializing */
expected = 1;
ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected);
if (ret <= 0) {
if (ret != 0)
ERROR("error using IPC to receive notification from attached process (1)");
goto cleanup_error;
}
/* tell attached process we're done */
status = 2;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("error using IPC to notify attached process for initialization (2)");
goto cleanup_error;
}
/* now shut down communication with child, we're done */
shutdown(ipc_sockets[0], SHUT_RDWR);
close(ipc_sockets[0]);
lxc_proc_put_context_info(init_ctx);
/* we're done, the child process should now execute whatever
* it is that the user requested. The parent can now track it
* with waitpid() or similar.
*/
*attached_process = attached_pid;
return 0;
cleanup_error:
/* first shut down the socket, then wait for the pid,
* otherwise the pid we're waiting for may never exit
*/
shutdown(ipc_sockets[0], SHUT_RDWR);
close(ipc_sockets[0]);
if (to_cleanup_pid)
(void) wait_for_pid(to_cleanup_pid);
lxc_proc_put_context_info(init_ctx);
return -1;
}
/* first subprocess begins here, we close the socket that is for the
* initial thread
*/
close(ipc_sockets[0]);
/* Wait for the parent to have setup cgroups */
expected = 0;
status = -1;
ret = lxc_read_nointr_expect(ipc_sockets[1], &status, sizeof(status), &expected);
if (ret <= 0) {
ERROR("error communicating with child process");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
procfd = open("/proc", O_DIRECTORY | O_RDONLY);
if (procfd < 0) {
SYSERROR("Unable to open /proc");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
/* attach now, create another subprocess later, since pid namespaces
* only really affect the children of the current process
*/
ret = lxc_attach_to_ns(init_pid, options->namespaces);
if (ret < 0) {
ERROR("failed to enter the namespace");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
/* attach succeeded, try to cwd */
if (options->initial_cwd)
new_cwd = options->initial_cwd;
else
new_cwd = cwd;
ret = chdir(new_cwd);
if (ret < 0)
WARN("could not change directory to '%s'", new_cwd);
free(cwd);
/* now create the real child process */
{
struct attach_clone_payload payload = {
.ipc_socket = ipc_sockets[1],
.options = options,
.init_ctx = init_ctx,
.exec_function = exec_function,
.exec_payload = exec_payload,
.procfd = procfd
};
/* We use clone_parent here to make this subprocess a direct child of
* the initial process. Then this intermediate process can exit and
* the parent can directly track the attached process.
*/
pid = lxc_clone(attach_child_main, &payload, CLONE_PARENT);
}
/* shouldn't happen, clone() should always return positive pid */
if (pid <= 0) {
SYSERROR("failed to create subprocess");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
/* tell grandparent the pid of the pid of the newly created child */
ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid));
if (ret != sizeof(pid)) {
/* if this really happens here, this is very unfortunate, since the
* parent will not know the pid of the attached process and will
* not be able to wait for it (and we won't either due to CLONE_PARENT)
* so the parent won't be able to reap it and the attached process
* will remain a zombie
*/
ERROR("error using IPC to notify main process of pid of the attached process");
shutdown(ipc_sockets[1], SHUT_RDWR);
rexit(-1);
}
/* the rest is in the hands of the initial and the attached process */
rexit(0);
}
| 166,724 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int treeRead(struct READER *reader, struct DATAOBJECT *data) {
int i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy,
szy;
char *input, *output;
uint8_t node_type, node_level;
uint16_t entries_used;
uint32_t size_of_chunk;
uint32_t filter_mask;
uint64_t address_of_left_sibling, address_of_right_sibling, start[4],
child_pointer, key, store;
char buf[4];
UNUSED(node_level);
UNUSED(address_of_right_sibling);
UNUSED(address_of_left_sibling);
UNUSED(key);
if (data->ds.dimensionality > 3) {
log("TREE dimensions > 3");
return MYSOFA_INVALID_FORMAT;
}
/* read signature */
if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "TREE", 4)) {
log("cannot read signature of TREE\n");
return MYSOFA_INVALID_FORMAT;
} log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf);
node_type = (uint8_t)fgetc(reader->fhd);
node_level = (uint8_t)fgetc(reader->fhd);
entries_used = (uint16_t)readValue(reader, 2);
if(entries_used>0x1000)
return MYSOFA_UNSUPPORTED_FORMAT;
address_of_left_sibling = readValue(reader,
reader->superblock.size_of_offsets);
address_of_right_sibling = readValue(reader,
reader->superblock.size_of_offsets);
elements = 1;
for (j = 0; j < data->ds.dimensionality; j++)
elements *= data->datalayout_chunk[j];
dy = data->datalayout_chunk[1];
dz = data->datalayout_chunk[2];
sx = data->ds.dimension_size[0];
sy = data->ds.dimension_size[1];
sz = data->ds.dimension_size[2];
dzy = dz * dy;
szy = sz * sy;
size = data->datalayout_chunk[data->ds.dimensionality];
log("elements %d size %d\n",elements,size);
if (!(output = malloc(elements * size))) {
return MYSOFA_NO_MEMORY;
}
for (e = 0; e < entries_used * 2; e++) {
if (node_type == 0) {
key = readValue(reader, reader->superblock.size_of_lengths);
} else {
size_of_chunk = (uint32_t)readValue(reader, 4);
filter_mask = (uint32_t)readValue(reader, 4);
if (filter_mask) {
log("TREE all filters must be enabled\n");
free(output);
return MYSOFA_INVALID_FORMAT;
}
for (j = 0; j < data->ds.dimensionality; j++) {
start[j] = readValue(reader, 8);
log("start %d %lu\n",j,start[j]);
}
if (readValue(reader, 8)) {
break;
}
child_pointer = readValue(reader,
reader->superblock.size_of_offsets);
log(" data at %lX len %u\n", child_pointer, size_of_chunk);
/* read data */
store = ftell(reader->fhd);
if (fseek(reader->fhd, child_pointer, SEEK_SET)<0) {
free(output);
return errno;
}
if (!(input = malloc(size_of_chunk))) {
free(output);
return MYSOFA_NO_MEMORY;
}
if (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) {
free(output);
free(input);
return MYSOFA_INVALID_FORMAT;
}
olen = elements * size;
err = gunzip(size_of_chunk, input, &olen, output);
free(input);
log(" gunzip %d %d %d\n",err, olen, elements*size);
if (err || olen != elements * size) {
free(output);
return MYSOFA_INVALID_FORMAT;
}
switch (data->ds.dimensionality) {
case 1:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements + start[0];
if (x < sx) {
j = x * size + b;
((char*)data->data)[j] = output[i];
}
}
break;
case 2:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements;
y = x % dy + start[1];
x = x / dy + start[0];
if (y < sy && x < sx) {
j = ((x * sy + y) * size) + b;
((char*)data->data)[j] = output[i];
}
}
break;
case 3:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements;
z = x % dz + start[2];
y = (x / dz) % dy + start[1];
x = (x / dzy) + start[0];
if (z < sz && y < sy && x < sx) {
j = (x * szy + y * sz + z) * size + b;
((char*)data->data)[j] = output[i];
}
}
break;
default:
log("invalid dim\n");
return MYSOFA_INTERNAL_ERROR;
}
if(fseek(reader->fhd, store, SEEK_SET)<0) {
free(output);
return errno;
}
}
}
free(output);
if(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */
return errno;
return MYSOFA_OK;
}
Commit Message: Fixed security issue 1
CWE ID: CWE-20 | int treeRead(struct READER *reader, struct DATAOBJECT *data) {
int i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy,
szy;
char *input, *output;
uint8_t node_type, node_level;
uint16_t entries_used;
uint32_t size_of_chunk;
uint32_t filter_mask;
uint64_t address_of_left_sibling, address_of_right_sibling, start[4],
child_pointer, key, store;
char buf[4];
UNUSED(node_level);
UNUSED(address_of_right_sibling);
UNUSED(address_of_left_sibling);
UNUSED(key);
if (data->ds.dimensionality > 3) {
log("TREE dimensions > 3");
return MYSOFA_INVALID_FORMAT;
}
/* read signature */
if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "TREE", 4)) {
log("cannot read signature of TREE\n");
return MYSOFA_INVALID_FORMAT;
} log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf);
node_type = (uint8_t)fgetc(reader->fhd);
node_level = (uint8_t)fgetc(reader->fhd);
entries_used = (uint16_t)readValue(reader, 2);
if(entries_used>0x1000)
return MYSOFA_UNSUPPORTED_FORMAT;
address_of_left_sibling = readValue(reader,
reader->superblock.size_of_offsets);
address_of_right_sibling = readValue(reader,
reader->superblock.size_of_offsets);
elements = 1;
for (j = 0; j < data->ds.dimensionality; j++)
elements *= data->datalayout_chunk[j];
dy = data->datalayout_chunk[1];
dz = data->datalayout_chunk[2];
sx = data->ds.dimension_size[0];
sy = data->ds.dimension_size[1];
sz = data->ds.dimension_size[2];
dzy = dz * dy;
szy = sz * sy;
size = data->datalayout_chunk[data->ds.dimensionality];
log("elements %d size %d\n",elements,size);
if (!(output = malloc(elements * size))) {
return MYSOFA_NO_MEMORY;
}
for (e = 0; e < entries_used * 2; e++) {
if (node_type == 0) {
key = readValue(reader, reader->superblock.size_of_lengths);
} else {
size_of_chunk = (uint32_t)readValue(reader, 4);
filter_mask = (uint32_t)readValue(reader, 4);
if (filter_mask) {
log("TREE all filters must be enabled\n");
free(output);
return MYSOFA_INVALID_FORMAT;
}
for (j = 0; j < data->ds.dimensionality; j++) {
start[j] = readValue(reader, 8);
log("start %d %lu\n",j,start[j]);
}
if (readValue(reader, 8)) {
break;
}
child_pointer = readValue(reader,
reader->superblock.size_of_offsets);
log(" data at %lX len %u\n", child_pointer, size_of_chunk);
/* read data */
store = ftell(reader->fhd);
if (fseek(reader->fhd, child_pointer, SEEK_SET)<0) {
free(output);
return errno;
}
if (!(input = malloc(size_of_chunk))) {
free(output);
return MYSOFA_NO_MEMORY;
}
if (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) {
free(output);
free(input);
return MYSOFA_INVALID_FORMAT;
}
olen = elements * size;
err = gunzip(size_of_chunk, input, &olen, output);
free(input);
log(" gunzip %d %d %d\n",err, olen, elements*size);
if (err || olen != elements * size) {
free(output);
return MYSOFA_INVALID_FORMAT;
}
switch (data->ds.dimensionality) {
case 1:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements + start[0];
j = x * size + b;
if (j>=0 && j < elements * size) {
((char*)data->data)[j] = output[i];
}
}
break;
case 2:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements;
y = x % dy + start[1];
x = x / dy + start[0];
j = ((x * sy + y) * size) + b;
if (j>=0 && j < elements * size) {
((char*)data->data)[j] = output[i];
}
}
break;
case 3:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements;
z = x % dz + start[2];
y = (x / dz) % dy + start[1];
x = (x / dzy) + start[0];
j = (x * szy + y * sz + z) * size + b;
if (j>=0 && j < elements * size) {
((char*)data->data)[j] = output[i];
}
}
break;
default:
log("invalid dim\n");
return MYSOFA_INTERNAL_ERROR;
}
if(fseek(reader->fhd, store, SEEK_SET)<0) {
free(output);
return errno;
}
}
}
free(output);
if(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */
return errno;
return MYSOFA_OK;
}
| 169,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeOSCancelHandwriting(InputMethodStatusConnection* connection,
int n_strokes) {
g_return_if_fail(connection);
connection->CancelHandwriting(n_strokes);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ChromeOSCancelHandwriting(InputMethodStatusConnection* connection,
IBusController::~IBusController() {
}
| 170,520 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
{
printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
goto err0;
}
globalParams = new GlobalParams();
ok = extractPages (argv[1], argv[2]);
if (ok) {
exitCode = 0;
}
delete globalParams;
err0:
return exitCode;
}
Commit Message:
CWE ID: CWE-20 | bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%d' if more than one page should be extracted", destFileName);
return false;
}
// destFileName can have multiple %% and one %d
// We use auxDestFileName to replace all the valid % appearances
// by 'A' (random char that is not %), if at the end of replacing
// any of the valid appearances there is still any % around, the
// pattern is wrong
char *auxDestFileName = strdup(destFileName);
// %% can appear as many times as you want
char *p = strstr(auxDestFileName, "%%");
while (p != NULL) {
*p = 'A';
*(p + 1) = 'A';
p = strstr(p, "%%");
}
// %d can appear only one time
p = strstr(auxDestFileName, "%d");
if (p != NULL) {
*p = 'A';
}
// at this point any other % is wrong
p = strstr(auxDestFileName, "%");
if (p != NULL) {
error(errSyntaxError, -1, "'{0:s}' can only contain one '%d' pattern", destFileName);
free(auxDestFileName);
return false;
}
free(auxDestFileName);
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
{
printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
goto err0;
}
globalParams = new GlobalParams();
ok = extractPages (argv[1], argv[2]);
if (ok) {
exitCode = 0;
}
delete globalParams;
err0:
return exitCode;
}
| 164,653 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int irda_recvmsg_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
int noblock = flags & MSG_DONTWAIT;
size_t copied = 0;
int target, err;
long timeo;
IRDA_DEBUG(3, "%s()\n", __func__);
if ((err = sock_error(sk)) < 0)
return err;
if (sock->flags & __SO_ACCEPTCON)
return -EINVAL;
err =-EOPNOTSUPP;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
err = 0;
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, noblock);
msg->msg_namelen = 0;
do {
int chunk;
struct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue);
if (skb == NULL) {
DEFINE_WAIT(wait);
err = 0;
if (copied >= target)
break;
prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
;
else if (noblock)
err = -EAGAIN;
else if (signal_pending(current))
err = sock_intr_errno(timeo);
else if (sk->sk_state != TCP_ESTABLISHED)
err = -ENOTCONN;
else if (skb_peek(&sk->sk_receive_queue) == NULL)
/* Wait process until data arrives */
schedule();
finish_wait(sk_sleep(sk), &wait);
if (err)
return err;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
continue;
}
chunk = min_t(unsigned int, skb->len, size);
if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
skb_pull(skb, chunk);
/* put the skb back if we didn't use it up.. */
if (skb->len) {
IRDA_DEBUG(1, "%s(), back on q!\n",
__func__);
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
IRDA_DEBUG(0, "%s() questionable!?\n", __func__);
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int irda_recvmsg_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
int noblock = flags & MSG_DONTWAIT;
size_t copied = 0;
int target, err;
long timeo;
IRDA_DEBUG(3, "%s()\n", __func__);
if ((err = sock_error(sk)) < 0)
return err;
if (sock->flags & __SO_ACCEPTCON)
return -EINVAL;
err =-EOPNOTSUPP;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
err = 0;
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, noblock);
do {
int chunk;
struct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue);
if (skb == NULL) {
DEFINE_WAIT(wait);
err = 0;
if (copied >= target)
break;
prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
;
else if (noblock)
err = -EAGAIN;
else if (signal_pending(current))
err = sock_intr_errno(timeo);
else if (sk->sk_state != TCP_ESTABLISHED)
err = -ENOTCONN;
else if (skb_peek(&sk->sk_receive_queue) == NULL)
/* Wait process until data arrives */
schedule();
finish_wait(sk_sleep(sk), &wait);
if (err)
return err;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
continue;
}
chunk = min_t(unsigned int, skb->len, size);
if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
skb_pull(skb, chunk);
/* put the skb back if we didn't use it up.. */
if (skb->len) {
IRDA_DEBUG(1, "%s(), back on q!\n",
__func__);
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
IRDA_DEBUG(0, "%s() questionable!?\n", __func__);
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
| 166,502 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pmd_access_permitted(orig, write))
return 0;
if (pmd_devmap(orig))
return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
refs = 0;
page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = compound_head(pmd_page(orig));
if (!page_cache_add_speculative(head, refs)) {
*nr -= refs;
return 0;
}
if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pmd_access_permitted(orig, write))
return 0;
if (pmd_devmap(orig))
return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
refs = 0;
page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = try_get_compound_head(pmd_page(orig), refs);
if (!head) {
*nr -= refs;
return 0;
}
if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
| 170,226 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; ғ > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
#if defined(OS_WIN)
"ӏ > i;"
#else
"ӏ > l;"
#endif
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add more to confusables list
U+04FB (ӻ) to f
U+050F (ԏ) to t
U+050B (ԋ) and U+0527 (ԧ) to h
U+0437(з) and U+04E1(ӡ) to 3
Add tests for the above entries and tests for ASCII-digit spoofing.
Bug: 816769,820068
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I6cd0a7e97cd0ec2df522ce30f632acfd7b78eee2
Reviewed-on: https://chromium-review.googlesource.com/962875
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#543600}
CWE ID: | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// U+04C8 (ӈ), U+04CA (ӊ), U+050B (ԋ), U+0527 (ԧ), U+0529 (ԩ)} => h
// - {U+0167 (ŧ), U+0442 (т), U+04AD (ҭ), U+050F (ԏ)} => t
// - {U+0493 (ғ), U+04FB (ӻ)} => f
// - {U+0437 (з), U+04E1 (ӡ)} => 3
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
#if defined(OS_WIN)
"ӏ > i;"
#else
"ӏ > l;"
#endif
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,736 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
Image
*image;
IndexPacket
*indexes;
long
x_offset,
y_offset;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/591
CWE ID: CWE-835 | static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
Image
*image;
IndexPacket
*indexes;
long
x_offset,
y_offset;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,008 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Element* siblingWithAriaRole(String role, Node* node) {
Node* parent = node->parentNode();
if (!parent)
return 0;
for (Element* sibling = ElementTraversal::firstChild(*parent); sibling;
sibling = ElementTraversal::nextSibling(*sibling)) {
const AtomicString& siblingAriaRole =
AccessibleNode::getProperty(sibling, AOMStringProperty::kRole);
if (equalIgnoringCase(siblingAriaRole, role))
return sibling;
}
return 0;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | static Element* siblingWithAriaRole(String role, Node* node) {
Node* parent = node->parentNode();
if (!parent)
return 0;
for (Element* sibling = ElementTraversal::firstChild(*parent); sibling;
sibling = ElementTraversal::nextSibling(*sibling)) {
const AtomicString& siblingAriaRole =
AccessibleNode::getProperty(sibling, AOMStringProperty::kRole);
if (equalIgnoringASCIICase(siblingAriaRole, role))
return sibling;
}
return 0;
}
| 171,921 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadXCFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[14];
Image
*image;
int
foundPropEnd = 0;
MagickBooleanType
status;
MagickOffsetType
offset;
register ssize_t
i;
size_t
image_type,
length;
ssize_t
count;
XCFDocInfo
doc_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
count=ReadBlob(image,14,(unsigned char *) magick);
if ((count != 14) ||
(LocaleNCompare((char *) magick,"gimp xcf",8) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ResetMagickMemory(&doc_info,0,sizeof(XCFDocInfo));
doc_info.exception=exception;
doc_info.width=ReadBlobMSBLong(image);
doc_info.height=ReadBlobMSBLong(image);
if ((doc_info.width > 262144) || (doc_info.height > 262144))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
doc_info.image_type=ReadBlobMSBLong(image);
/*
Initialize image attributes.
*/
image->columns=doc_info.width;
image->rows=doc_info.height;
image_type=doc_info.image_type;
doc_info.file_size=GetBlobSize(image);
image->compression=NoCompression;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image_type == GIMP_RGB)
;
else
if (image_type == GIMP_GRAY)
image->colorspace=GRAYColorspace;
else
if (image_type == GIMP_INDEXED)
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
(void) SetImageOpacity(image,OpaqueOpacity);
(void) SetImageBackgroundColor(image);
/*
Read properties.
*/
while ((foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse))
{
PropType prop_type = (PropType) ReadBlobMSBLong(image);
size_t prop_size = ReadBlobMSBLong(image);
switch (prop_type)
{
case PROP_END:
foundPropEnd=1;
break;
case PROP_COLORMAP:
{
/* Cannot rely on prop_size here--the value is set incorrectly
by some Gimp versions.
*/
size_t num_colours = ReadBlobMSBLong(image);
if (DiscardBlobBytes(image,3*num_colours) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
if (info->file_version == 0)
{
gint i;
g_message (_("XCF warning: version 0 of XCF file format\n"
"did not save indexed colormaps correctly.\n"
"Substituting grayscale map."));
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
xcf_seek_pos (info, info->cp + gimage->num_cols);
for (i = 0; i<gimage->num_cols; i++)
{
gimage->cmap[i*3+0] = i;
gimage->cmap[i*3+1] = i;
gimage->cmap[i*3+2] = i;
}
}
else
{
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
info->cp +=
xcf_read_int8 (info->fp,
(guint8*) gimage->cmap, gimage->num_cols*3);
}
*/
break;
}
case PROP_COMPRESSION:
{
doc_info.compression = ReadBlobByte(image);
if ((doc_info.compression != COMPRESS_NONE) &&
(doc_info.compression != COMPRESS_RLE) &&
(doc_info.compression != COMPRESS_ZLIB) &&
(doc_info.compression != COMPRESS_FRACTAL))
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
break;
case PROP_GUIDES:
{
/* just skip it - we don't care about guides */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
break;
case PROP_RESOLUTION:
{
/* float xres = (float) */ (void) ReadBlobMSBLong(image);
/* float yres = (float) */ (void) ReadBlobMSBLong(image);
/*
if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION ||
yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION)
{
g_message ("Warning, resolution out of range in XCF file");
xres = gimage->gimp->config->default_xresolution;
yres = gimage->gimp->config->default_yresolution;
}
*/
/* BOGUS: we don't write these yet because we aren't
reading them properly yet :(
image->x_resolution = xres;
image->y_resolution = yres;
*/
}
break;
case PROP_TATTOO:
{
/* we need to read it, even if we ignore it */
/*size_t tattoo_state = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PARASITES:
{
/* BOGUS: we may need these for IPTC stuff */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
gssize_t base = info->cp;
GimpParasite *p;
while (info->cp - base < prop_size)
{
p = xcf_load_parasite (info);
gimp_image_parasite_attach (gimage, p);
gimp_parasite_free (p);
}
if (info->cp - base != prop_size)
g_message ("Error detected while loading an image's parasites");
*/
}
break;
case PROP_UNIT:
{
/* BOGUS: ignore for now... */
/*size_t unit = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PATHS:
{
/* BOGUS: just skip it for now */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
PathList *paths = xcf_load_bzpaths (gimage, info);
gimp_image_set_paths (gimage, paths);
*/
}
break;
case PROP_USER_UNIT:
{
char unit_string[1000];
/*BOGUS: ignored for now */
/*float factor = (float) */ (void) ReadBlobMSBLong(image);
/* size_t digits = */ (void) ReadBlobMSBLong(image);
for (i=0; i<5; i++)
(void) ReadBlobStringWithLongSize(image, unit_string,
sizeof(unit_string));
}
break;
default:
{
int buf[16];
ssize_t amount;
/* read over it... */
while ((prop_size > 0) && (EOFBlob(image) == MagickFalse))
{
amount=(ssize_t) MagickMin(16, prop_size);
amount=(ssize_t) ReadBlob(image,(size_t) amount,(unsigned char *) &buf);
if (!amount)
ThrowReaderException(CorruptImageError,"CorruptImage");
prop_size -= (size_t) MagickMin(16,(size_t) amount);
}
}
break;
}
}
if (foundPropEnd == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
{
; /* do nothing, were just pinging! */
}
else
{
int
current_layer = 0,
foundAllLayers = MagickFalse,
number_layers = 0;
MagickOffsetType
oldPos=TellBlob(image);
XCFLayerInfo
*layer_info;
/*
The read pointer.
*/
do
{
ssize_t offset = ReadBlobMSBSignedLong(image);
if (offset == 0)
foundAllLayers=MagickTrue;
else
number_layers++;
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
} while (foundAllLayers == MagickFalse);
doc_info.number_layers=number_layers;
offset=SeekBlob(image,oldPos,SEEK_SET); /* restore the position! */
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* allocate our array of layer info blocks */
length=(size_t) number_layers;
layer_info=(XCFLayerInfo *) AcquireQuantumMemory(length,
sizeof(*layer_info));
if (layer_info == (XCFLayerInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(layer_info,0,number_layers*sizeof(XCFLayerInfo));
for ( ; ; )
{
MagickBooleanType
layer_ok;
MagickOffsetType
offset,
saved_pos;
/* read in the offset of the next layer */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
/* if the offset is 0 then we are at the end
* of the layer list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next layer offset is stored.
*/
saved_pos=TellBlob(image);
/* seek to the layer offset */
if (SeekBlob(image,offset,SEEK_SET) != offset)
ThrowReaderException(ResourceLimitError,"NotEnoughPixelData");
/* read in the layer */
layer_ok=ReadOneLayer(image_info,image,&doc_info,
&layer_info[current_layer],current_layer);
if (layer_ok == MagickFalse)
{
int j;
for (j=0; j < current_layer; j++)
layer_info[j].image=DestroyImage(layer_info[j].image);
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
current_layer++;
}
#if 0
{
/* NOTE: XCF layers are REVERSED from composite order! */
signed int j;
for (j=number_layers-1; j>=0; j--) {
/* BOGUS: need to consider layer blending modes!! */
if ( layer_info[j].visible ) { /* only visible ones, please! */
CompositeImage(image, OverCompositeOp, layer_info[j].image,
layer_info[j].offset_x, layer_info[j].offset_y );
layer_info[j].image =DestroyImage( layer_info[j].image );
/* If we do this, we'll get REAL gray images! */
if ( image_type == GIMP_GRAY ) {
QuantizeInfo qi;
GetQuantizeInfo(&qi);
qi.colorspace = GRAYColorspace;
QuantizeImage( &qi, layer_info[j].image );
}
}
}
}
#else
{
/* NOTE: XCF layers are REVERSED from composite order! */
ssize_t j;
/* now reverse the order of the layers as they are put
into subimages
*/
for (j=(long) number_layers-1; j >= 0; j--)
AppendImageToList(&image,layer_info[j].image);
}
#endif
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
#if 0 /* BOGUS: do we need the channels?? */
while (MagickTrue)
{
/* read in the offset of the next channel */
info->cp += xcf_read_int32 (info->fp, &offset, 1);
/* if the offset is 0 then we are at the end
* of the channel list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next channel offset is stored.
*/
saved_pos = info->cp;
/* seek to the channel offset */
xcf_seek_pos (info, offset);
/* read in the layer */
channel = xcf_load_channel (info, gimage);
if (channel == 0)
goto error;
num_successful_elements++;
/* add the channel to the image if its not the selection */
if (channel != gimage->selection_mask)
gimp_image_add_channel (gimage, channel, -1);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
xcf_seek_pos (info, saved_pos);
}
#endif
}
(void) CloseBlob(image);
DestroyImage(RemoveFirstImageFromList(&image));
if (image_type == GIMP_GRAY)
image->type=GrayscaleType;
return(GetFirstImageInList(image));
}
Commit Message: Check for image list before we destroy the last image in XCF coder (patch sent privately by Андрей Черный)
CWE ID: CWE-476 | static Image *ReadXCFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[14];
Image
*image;
int
foundPropEnd = 0;
MagickBooleanType
status;
MagickOffsetType
offset;
register ssize_t
i;
size_t
image_type,
length;
ssize_t
count;
XCFDocInfo
doc_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
count=ReadBlob(image,14,(unsigned char *) magick);
if ((count != 14) ||
(LocaleNCompare((char *) magick,"gimp xcf",8) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ResetMagickMemory(&doc_info,0,sizeof(XCFDocInfo));
doc_info.exception=exception;
doc_info.width=ReadBlobMSBLong(image);
doc_info.height=ReadBlobMSBLong(image);
if ((doc_info.width > 262144) || (doc_info.height > 262144))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
doc_info.image_type=ReadBlobMSBLong(image);
/*
Initialize image attributes.
*/
image->columns=doc_info.width;
image->rows=doc_info.height;
image_type=doc_info.image_type;
doc_info.file_size=GetBlobSize(image);
image->compression=NoCompression;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image_type == GIMP_RGB)
;
else
if (image_type == GIMP_GRAY)
image->colorspace=GRAYColorspace;
else
if (image_type == GIMP_INDEXED)
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
(void) SetImageOpacity(image,OpaqueOpacity);
(void) SetImageBackgroundColor(image);
/*
Read properties.
*/
while ((foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse))
{
PropType prop_type = (PropType) ReadBlobMSBLong(image);
size_t prop_size = ReadBlobMSBLong(image);
switch (prop_type)
{
case PROP_END:
foundPropEnd=1;
break;
case PROP_COLORMAP:
{
/* Cannot rely on prop_size here--the value is set incorrectly
by some Gimp versions.
*/
size_t num_colours = ReadBlobMSBLong(image);
if (DiscardBlobBytes(image,3*num_colours) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
if (info->file_version == 0)
{
gint i;
g_message (_("XCF warning: version 0 of XCF file format\n"
"did not save indexed colormaps correctly.\n"
"Substituting grayscale map."));
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
xcf_seek_pos (info, info->cp + gimage->num_cols);
for (i = 0; i<gimage->num_cols; i++)
{
gimage->cmap[i*3+0] = i;
gimage->cmap[i*3+1] = i;
gimage->cmap[i*3+2] = i;
}
}
else
{
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
info->cp +=
xcf_read_int8 (info->fp,
(guint8*) gimage->cmap, gimage->num_cols*3);
}
*/
break;
}
case PROP_COMPRESSION:
{
doc_info.compression = ReadBlobByte(image);
if ((doc_info.compression != COMPRESS_NONE) &&
(doc_info.compression != COMPRESS_RLE) &&
(doc_info.compression != COMPRESS_ZLIB) &&
(doc_info.compression != COMPRESS_FRACTAL))
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
break;
case PROP_GUIDES:
{
/* just skip it - we don't care about guides */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
break;
case PROP_RESOLUTION:
{
/* float xres = (float) */ (void) ReadBlobMSBLong(image);
/* float yres = (float) */ (void) ReadBlobMSBLong(image);
/*
if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION ||
yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION)
{
g_message ("Warning, resolution out of range in XCF file");
xres = gimage->gimp->config->default_xresolution;
yres = gimage->gimp->config->default_yresolution;
}
*/
/* BOGUS: we don't write these yet because we aren't
reading them properly yet :(
image->x_resolution = xres;
image->y_resolution = yres;
*/
}
break;
case PROP_TATTOO:
{
/* we need to read it, even if we ignore it */
/*size_t tattoo_state = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PARASITES:
{
/* BOGUS: we may need these for IPTC stuff */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
gssize_t base = info->cp;
GimpParasite *p;
while (info->cp - base < prop_size)
{
p = xcf_load_parasite (info);
gimp_image_parasite_attach (gimage, p);
gimp_parasite_free (p);
}
if (info->cp - base != prop_size)
g_message ("Error detected while loading an image's parasites");
*/
}
break;
case PROP_UNIT:
{
/* BOGUS: ignore for now... */
/*size_t unit = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PATHS:
{
/* BOGUS: just skip it for now */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
PathList *paths = xcf_load_bzpaths (gimage, info);
gimp_image_set_paths (gimage, paths);
*/
}
break;
case PROP_USER_UNIT:
{
char unit_string[1000];
/*BOGUS: ignored for now */
/*float factor = (float) */ (void) ReadBlobMSBLong(image);
/* size_t digits = */ (void) ReadBlobMSBLong(image);
for (i=0; i<5; i++)
(void) ReadBlobStringWithLongSize(image, unit_string,
sizeof(unit_string));
}
break;
default:
{
int buf[16];
ssize_t amount;
/* read over it... */
while ((prop_size > 0) && (EOFBlob(image) == MagickFalse))
{
amount=(ssize_t) MagickMin(16, prop_size);
amount=(ssize_t) ReadBlob(image,(size_t) amount,(unsigned char *) &buf);
if (!amount)
ThrowReaderException(CorruptImageError,"CorruptImage");
prop_size -= (size_t) MagickMin(16,(size_t) amount);
}
}
break;
}
}
if (foundPropEnd == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
{
; /* do nothing, were just pinging! */
}
else
{
int
current_layer = 0,
foundAllLayers = MagickFalse,
number_layers = 0;
MagickOffsetType
oldPos=TellBlob(image);
XCFLayerInfo
*layer_info;
/*
The read pointer.
*/
do
{
ssize_t offset = ReadBlobMSBSignedLong(image);
if (offset == 0)
foundAllLayers=MagickTrue;
else
number_layers++;
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
} while (foundAllLayers == MagickFalse);
doc_info.number_layers=number_layers;
offset=SeekBlob(image,oldPos,SEEK_SET); /* restore the position! */
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* allocate our array of layer info blocks */
length=(size_t) number_layers;
layer_info=(XCFLayerInfo *) AcquireQuantumMemory(length,
sizeof(*layer_info));
if (layer_info == (XCFLayerInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(layer_info,0,number_layers*sizeof(XCFLayerInfo));
for ( ; ; )
{
MagickBooleanType
layer_ok;
MagickOffsetType
offset,
saved_pos;
/* read in the offset of the next layer */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
/* if the offset is 0 then we are at the end
* of the layer list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next layer offset is stored.
*/
saved_pos=TellBlob(image);
/* seek to the layer offset */
if (SeekBlob(image,offset,SEEK_SET) != offset)
ThrowReaderException(ResourceLimitError,"NotEnoughPixelData");
/* read in the layer */
layer_ok=ReadOneLayer(image_info,image,&doc_info,
&layer_info[current_layer],current_layer);
if (layer_ok == MagickFalse)
{
int j;
for (j=0; j < current_layer; j++)
layer_info[j].image=DestroyImage(layer_info[j].image);
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
current_layer++;
}
#if 0
{
/* NOTE: XCF layers are REVERSED from composite order! */
signed int j;
for (j=number_layers-1; j>=0; j--) {
/* BOGUS: need to consider layer blending modes!! */
if ( layer_info[j].visible ) { /* only visible ones, please! */
CompositeImage(image, OverCompositeOp, layer_info[j].image,
layer_info[j].offset_x, layer_info[j].offset_y );
layer_info[j].image =DestroyImage( layer_info[j].image );
/* If we do this, we'll get REAL gray images! */
if ( image_type == GIMP_GRAY ) {
QuantizeInfo qi;
GetQuantizeInfo(&qi);
qi.colorspace = GRAYColorspace;
QuantizeImage( &qi, layer_info[j].image );
}
}
}
}
#else
{
/* NOTE: XCF layers are REVERSED from composite order! */
ssize_t j;
/* now reverse the order of the layers as they are put
into subimages
*/
for (j=(long) number_layers-1; j >= 0; j--)
AppendImageToList(&image,layer_info[j].image);
}
#endif
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
#if 0 /* BOGUS: do we need the channels?? */
while (MagickTrue)
{
/* read in the offset of the next channel */
info->cp += xcf_read_int32 (info->fp, &offset, 1);
/* if the offset is 0 then we are at the end
* of the channel list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next channel offset is stored.
*/
saved_pos = info->cp;
/* seek to the channel offset */
xcf_seek_pos (info, offset);
/* read in the layer */
channel = xcf_load_channel (info, gimage);
if (channel == 0)
goto error;
num_successful_elements++;
/* add the channel to the image if its not the selection */
if (channel != gimage->selection_mask)
gimp_image_add_channel (gimage, channel, -1);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
xcf_seek_pos (info, saved_pos);
}
#endif
}
(void) CloseBlob(image);
if (GetNextImageInList(image) != (Image *) NULL)
DestroyImage(RemoveFirstImageFromList(&image));
if (image_type == GIMP_GRAY)
image->type=GrayscaleType;
return(GetFirstImageInList(image));
}
| 168,329 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: CastCastView::CastCastView(CastConfigDelegate* cast_config_delegate)
: cast_config_delegate_(cast_config_delegate) {
set_background(views::Background::CreateSolidBackground(kBackgroundColor));
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
kTrayPopupPaddingHorizontal, 0,
kTrayPopupPaddingBetweenItems));
icon_ = new FixedSizedImageView(0, kTrayPopupItemHeight);
icon_->SetImage(
bundle.GetImageNamed(IDR_AURA_UBER_TRAY_CAST_ENABLED).ToImageSkia());
AddChildView(icon_);
label_container_ = new views::View;
label_container_->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0));
title_ = new views::Label;
title_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
title_->SetFontList(bundle.GetFontList(ui::ResourceBundle::BoldFont));
label_container_->AddChildView(title_);
details_ = new views::Label;
details_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
details_->SetMultiLine(false);
details_->SetEnabledColor(kHeaderTextColorNormal);
label_container_->AddChildView(details_);
AddChildView(label_container_);
base::string16 stop_button_text =
ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
IDS_ASH_STATUS_TRAY_CAST_STOP);
stop_button_ = new TrayPopupLabelButton(this, stop_button_text);
AddChildView(stop_button_);
UpdateLabel();
}
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 | CastCastView::CastCastView(CastConfigDelegate* cast_config_delegate)
: cast_config_delegate_(cast_config_delegate) {
set_background(views::Background::CreateSolidBackground(kBackgroundColor));
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
kTrayPopupPaddingHorizontal, 0,
kTrayPopupPaddingBetweenItems));
icon_ = new FixedSizedImageView(0, kTrayPopupItemHeight);
icon_->SetImage(
bundle.GetImageNamed(IDR_AURA_UBER_TRAY_CAST_ENABLED).ToImageSkia());
AddChildView(icon_);
label_container_ = new views::View;
label_container_->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0));
title_ = new views::Label;
title_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
title_->SetFontList(bundle.GetFontList(ui::ResourceBundle::BoldFont));
title_->SetText(
bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_CAST_UNKNOWN_CAST_TYPE));
label_container_->AddChildView(title_);
details_ = new views::Label;
details_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
details_->SetMultiLine(false);
details_->SetEnabledColor(kHeaderTextColorNormal);
details_->SetText(
bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_CAST_UNKNOWN_RECEIVER));
label_container_->AddChildView(details_);
AddChildView(label_container_);
base::string16 stop_button_text =
ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
IDS_ASH_STATUS_TRAY_CAST_STOP);
stop_button_ = new TrayPopupLabelButton(this, stop_button_text);
AddChildView(stop_button_);
UpdateLabel();
}
| 171,624 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int atusb_read_reg(struct atusb *atusb, uint8_t reg)
{
struct usb_device *usb_dev = atusb->usb_dev;
int ret;
uint8_t value;
dev_dbg(&usb_dev->dev, "atusb: reg = 0x%x\n", reg);
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_REG_READ, ATUSB_REQ_FROM_DEV,
0, reg, &value, 1, 1000);
return ret >= 0 ? value : ret;
}
Commit Message: ieee802154: atusb: do not use the stack for buffers to make them DMA able
From 4.9 we should really avoid using the stack here as this will not be DMA
able on various platforms. This changes the buffers already being present in
time of 4.9 being released. This should go into stable as well.
Reported-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Stefan Schmidt <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119 | static int atusb_read_reg(struct atusb *atusb, uint8_t reg)
{
struct usb_device *usb_dev = atusb->usb_dev;
int ret;
uint8_t *buffer;
uint8_t value;
buffer = kmalloc(1, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
dev_dbg(&usb_dev->dev, "atusb: reg = 0x%x\n", reg);
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_REG_READ, ATUSB_REQ_FROM_DEV,
0, reg, buffer, 1, 1000);
if (ret >= 0) {
value = buffer[0];
kfree(buffer);
return value;
} else {
kfree(buffer);
return ret;
}
}
| 168,392 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,
++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls -
rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls -
rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
<< r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
<< r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
pi->pirlvl->prcheightexpn);
pi->prcno = prcvind *
pi->pirlvl->numhprcs +
prchind;
assert(pi->prcno <
pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
Commit Message: Fixed an integer overflow problem in the JPC codec that later resulted
in the use of uninitialized data.
CWE ID: CWE-190 | static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,
++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
<< r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
<< r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
pi->pirlvl->prcheightexpn);
pi->prcno = prcvind *
pi->pirlvl->numhprcs +
prchind;
assert(pi->prcno <
pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
| 168,471 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_attr3_leaf_lookup_int(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
xfs_dahash_t hashval;
int probe;
int span;
trace_xfs_attr_leaf_lookup(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8);
/*
* Binary search. (note: small blocks will skip this loop)
*/
hashval = args->hashval;
probe = span = ichdr.count / 2;
for (entry = &entries[probe]; span > 4; entry = &entries[probe]) {
span /= 2;
if (be32_to_cpu(entry->hashval) < hashval)
probe += span;
else if (be32_to_cpu(entry->hashval) > hashval)
probe -= span;
else
break;
}
ASSERT(probe >= 0 && (!ichdr.count || probe < ichdr.count));
ASSERT(span <= 4 || be32_to_cpu(entry->hashval) == hashval);
/*
* Since we may have duplicate hashval's, find the first matching
* hashval in the leaf.
*/
while (probe > 0 && be32_to_cpu(entry->hashval) >= hashval) {
entry--;
probe--;
}
while (probe < ichdr.count &&
be32_to_cpu(entry->hashval) < hashval) {
entry++;
probe++;
}
if (probe == ichdr.count || be32_to_cpu(entry->hashval) != hashval) {
args->index = probe;
return XFS_ERROR(ENOATTR);
}
/*
* Duplicate keys may be present, so search all of them for a match.
*/
for (; probe < ichdr.count && (be32_to_cpu(entry->hashval) == hashval);
entry++, probe++) {
/*
* GROT: Add code to remove incomplete entries.
*/
/*
* If we are looking for INCOMPLETE entries, show only those.
* If we are looking for complete entries, show only those.
*/
if ((args->flags & XFS_ATTR_INCOMPLETE) !=
(entry->flags & XFS_ATTR_INCOMPLETE)) {
continue;
}
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, probe);
if (name_loc->namelen != args->namelen)
continue;
if (memcmp(args->name, name_loc->nameval,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
return XFS_ERROR(EEXIST);
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, probe);
if (name_rmt->namelen != args->namelen)
continue;
if (memcmp(args->name, name_rmt->name,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
args->valuelen = be32_to_cpu(name_rmt->valuelen);
args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
args->rmtblkcnt = xfs_attr3_rmt_blocks(
args->dp->i_mount,
args->valuelen);
return XFS_ERROR(EEXIST);
}
}
args->index = probe;
return XFS_ERROR(ENOATTR);
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19 | xfs_attr3_leaf_lookup_int(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
xfs_dahash_t hashval;
int probe;
int span;
trace_xfs_attr_leaf_lookup(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8);
/*
* Binary search. (note: small blocks will skip this loop)
*/
hashval = args->hashval;
probe = span = ichdr.count / 2;
for (entry = &entries[probe]; span > 4; entry = &entries[probe]) {
span /= 2;
if (be32_to_cpu(entry->hashval) < hashval)
probe += span;
else if (be32_to_cpu(entry->hashval) > hashval)
probe -= span;
else
break;
}
ASSERT(probe >= 0 && (!ichdr.count || probe < ichdr.count));
ASSERT(span <= 4 || be32_to_cpu(entry->hashval) == hashval);
/*
* Since we may have duplicate hashval's, find the first matching
* hashval in the leaf.
*/
while (probe > 0 && be32_to_cpu(entry->hashval) >= hashval) {
entry--;
probe--;
}
while (probe < ichdr.count &&
be32_to_cpu(entry->hashval) < hashval) {
entry++;
probe++;
}
if (probe == ichdr.count || be32_to_cpu(entry->hashval) != hashval) {
args->index = probe;
return XFS_ERROR(ENOATTR);
}
/*
* Duplicate keys may be present, so search all of them for a match.
*/
for (; probe < ichdr.count && (be32_to_cpu(entry->hashval) == hashval);
entry++, probe++) {
/*
* GROT: Add code to remove incomplete entries.
*/
/*
* If we are looking for INCOMPLETE entries, show only those.
* If we are looking for complete entries, show only those.
*/
if ((args->flags & XFS_ATTR_INCOMPLETE) !=
(entry->flags & XFS_ATTR_INCOMPLETE)) {
continue;
}
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, probe);
if (name_loc->namelen != args->namelen)
continue;
if (memcmp(args->name, name_loc->nameval,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
return XFS_ERROR(EEXIST);
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, probe);
if (name_rmt->namelen != args->namelen)
continue;
if (memcmp(args->name, name_rmt->name,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
args->rmtvaluelen = be32_to_cpu(name_rmt->valuelen);
args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
args->rmtblkcnt = xfs_attr3_rmt_blocks(
args->dp->i_mount,
args->rmtvaluelen);
return XFS_ERROR(EEXIST);
}
}
args->index = probe;
return XFS_ERROR(ENOATTR);
}
| 166,737 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void *hashtable_iter_at(hashtable_t *hashtable, const char *key)
{
pair_t *pair;
size_t hash;
bucket_t *bucket;
hash = hash_str(key);
bucket = &hashtable->buckets[hash % num_buckets(hashtable)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return NULL;
return &pair->list;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | void *hashtable_iter_at(hashtable_t *hashtable, const char *key)
{
pair_t *pair;
size_t hash;
bucket_t *bucket;
hash = hash_str(key);
bucket = &hashtable->buckets[hash & hashmask(hashtable->order)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return NULL;
return &pair->list;
}
| 166,532 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetCryptohomeLibrary(
CryptohomeLibrary* library, bool own) {
library_->crypto_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void CrosLibrary::TestApi::SetCryptohomeLibrary(
| 170,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void bdt_enable(void)
{
bdt_log("ENABLE BT");
if (bt_enabled) {
bdt_log("Bluetooth is already enabled");
return;
}
status = sBtInterface->enable();
check_return_status(status);
}
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
CWE ID: CWE-20 | void bdt_enable(void)
{
bdt_log("ENABLE BT");
if (bt_enabled) {
bdt_log("Bluetooth is already enabled");
return;
}
status = sBtInterface->enable(false);
check_return_status(status);
}
| 173,555 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: LayerTreeCoordinator::LayerTreeCoordinator(WebPage* webPage)
: LayerTreeHost(webPage)
, m_notifyAfterScheduledLayerFlush(false)
, m_isValid(true)
, m_waitingForUIProcess(true)
, m_isSuspended(false)
, m_contentsScale(1)
, m_shouldSendScrollPositionUpdate(true)
, m_shouldSyncFrame(false)
, m_shouldSyncRootLayer(true)
, m_layerFlushTimer(this, &LayerTreeCoordinator::layerFlushTimerFired)
, m_layerFlushSchedulingEnabled(true)
, m_forceRepaintAsyncCallbackID(0)
{
m_rootLayer = GraphicsLayer::create(this);
CoordinatedGraphicsLayer* webRootLayer = toCoordinatedGraphicsLayer(m_rootLayer.get());
webRootLayer->setRootLayer(true);
#ifndef NDEBUG
m_rootLayer->setName("LayerTreeCoordinator root layer");
#endif
m_rootLayer->setDrawsContent(false);
m_rootLayer->setSize(m_webPage->size());
m_layerTreeContext.webLayerID = toCoordinatedGraphicsLayer(webRootLayer)->id();
m_nonCompositedContentLayer = GraphicsLayer::create(this);
toCoordinatedGraphicsLayer(m_rootLayer.get())->setCoordinatedGraphicsLayerClient(this);
#ifndef NDEBUG
m_nonCompositedContentLayer->setName("LayerTreeCoordinator non-composited content");
#endif
m_nonCompositedContentLayer->setDrawsContent(true);
m_nonCompositedContentLayer->setSize(m_webPage->size());
m_rootLayer->addChild(m_nonCompositedContentLayer.get());
if (m_webPage->hasPageOverlay())
createPageOverlayLayer();
scheduleLayerFlush();
}
Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases
https://bugs.webkit.org/show_bug.cgi?id=95072
Reviewed by Jocelyn Turcotte.
Release graphic buffers that haven't been used for a while in order to save memory.
This way we can give back memory to the system when no user interaction happens
after a period of time, for example when we are in the background.
* Shared/ShareableBitmap.h:
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp:
(WebKit::LayerTreeCoordinator::LayerTreeCoordinator):
(WebKit::LayerTreeCoordinator::beginContentUpdate):
(WebKit):
(WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases):
(WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired):
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h:
(LayerTreeCoordinator):
* WebProcess/WebPage/UpdateAtlas.cpp:
(WebKit::UpdateAtlas::UpdateAtlas):
(WebKit::UpdateAtlas::didSwapBuffers):
Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer
and this way we can track whether this atlas is used with m_areaAllocator.
(WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer):
* WebProcess/WebPage/UpdateAtlas.h:
(WebKit::UpdateAtlas::addTimeInactive):
(WebKit::UpdateAtlas::isInactive):
(WebKit::UpdateAtlas::isInUse):
(UpdateAtlas):
git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | LayerTreeCoordinator::LayerTreeCoordinator(WebPage* webPage)
: LayerTreeHost(webPage)
, m_notifyAfterScheduledLayerFlush(false)
, m_isValid(true)
, m_waitingForUIProcess(true)
, m_isSuspended(false)
, m_contentsScale(1)
, m_shouldSendScrollPositionUpdate(true)
, m_shouldSyncFrame(false)
, m_shouldSyncRootLayer(true)
, m_layerFlushTimer(this, &LayerTreeCoordinator::layerFlushTimerFired)
, m_releaseInactiveAtlasesTimer(this, &LayerTreeCoordinator::releaseInactiveAtlasesTimerFired)
, m_layerFlushSchedulingEnabled(true)
, m_forceRepaintAsyncCallbackID(0)
{
m_rootLayer = GraphicsLayer::create(this);
CoordinatedGraphicsLayer* webRootLayer = toCoordinatedGraphicsLayer(m_rootLayer.get());
webRootLayer->setRootLayer(true);
#ifndef NDEBUG
m_rootLayer->setName("LayerTreeCoordinator root layer");
#endif
m_rootLayer->setDrawsContent(false);
m_rootLayer->setSize(m_webPage->size());
m_layerTreeContext.webLayerID = toCoordinatedGraphicsLayer(webRootLayer)->id();
m_nonCompositedContentLayer = GraphicsLayer::create(this);
toCoordinatedGraphicsLayer(m_rootLayer.get())->setCoordinatedGraphicsLayerClient(this);
#ifndef NDEBUG
m_nonCompositedContentLayer->setName("LayerTreeCoordinator non-composited content");
#endif
m_nonCompositedContentLayer->setDrawsContent(true);
m_nonCompositedContentLayer->setSize(m_webPage->size());
m_rootLayer->addChild(m_nonCompositedContentLayer.get());
if (m_webPage->hasPageOverlay())
createPageOverlayLayer();
scheduleLayerFlush();
}
| 170,268 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeMockRenderThread::OnDidGetPrintedPagesCount(
int cookie, int number_pages) {
if (printer_.get())
printer_->SetPrintedPagesCount(cookie, number_pages);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void ChromeMockRenderThread::OnDidGetPrintedPagesCount(
int cookie, int number_pages) {
printer_->SetPrintedPagesCount(cookie, number_pages);
}
| 170,848 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void setattr_copy(struct inode *inode, const struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
if (ia_valid & ATTR_UID)
inode->i_uid = attr->ia_uid;
if (ia_valid & ATTR_GID)
inode->i_gid = attr->ia_gid;
if (ia_valid & ATTR_ATIME)
inode->i_atime = timespec_trunc(attr->ia_atime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_MTIME)
inode->i_mtime = timespec_trunc(attr->ia_mtime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_CTIME)
inode->i_ctime = timespec_trunc(attr->ia_ctime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_MODE) {
umode_t mode = attr->ia_mode;
if (!in_group_p(inode->i_gid) &&
!inode_capable(inode, CAP_FSETID))
mode &= ~S_ISGID;
inode->i_mode = mode;
}
}
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Dave Chinner <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | void setattr_copy(struct inode *inode, const struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
if (ia_valid & ATTR_UID)
inode->i_uid = attr->ia_uid;
if (ia_valid & ATTR_GID)
inode->i_gid = attr->ia_gid;
if (ia_valid & ATTR_ATIME)
inode->i_atime = timespec_trunc(attr->ia_atime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_MTIME)
inode->i_mtime = timespec_trunc(attr->ia_mtime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_CTIME)
inode->i_ctime = timespec_trunc(attr->ia_ctime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_MODE) {
umode_t mode = attr->ia_mode;
if (!in_group_p(inode->i_gid) &&
!capable_wrt_inode_uidgid(inode, CAP_FSETID))
mode &= ~S_ISGID;
inode->i_mode = mode;
}
}
| 166,318 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tight_fill_palette(VncState *vs, int x, int y,
size_t count, uint32_t *bg, uint32_t *fg,
VncPalette **palette)
{
int max;
max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor;
if (max < 2 &&
count >= tight_conf[vs->tight.compression].mono_min_rect_size) {
max = 2;
}
if (max >= 256) {
max = 256;
}
switch(vs->clientds.pf.bytes_per_pixel) {
case 4:
return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);
case 2:
return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);
default:
max = 2;
return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);
}
return 0;
}
Commit Message:
CWE ID: CWE-125 | static int tight_fill_palette(VncState *vs, int x, int y,
size_t count, uint32_t *bg, uint32_t *fg,
VncPalette **palette)
{
int max;
max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor;
if (max < 2 &&
count >= tight_conf[vs->tight.compression].mono_min_rect_size) {
max = 2;
}
if (max >= 256) {
max = 256;
}
switch (vs->client_pf.bytes_per_pixel) {
case 4:
return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);
case 2:
return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);
default:
max = 2;
return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);
}
return 0;
}
| 165,466 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int recv_msg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
u32 err;
int res;
/* Catch invalid receive requests */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely(sock->state == SS_UNCONNECTED)) {
res = -ENOTCONN;
goto exit;
}
/* will be updated in set_orig_addr() if needed */
m->msg_namelen = 0;
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Capture sender's address (optional) */
set_orig_addr(m, msg);
/* Capture ancillary data (optional) */
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
if (unlikely(buf_len < sz)) {
sz = buf_len;
m->msg_flags |= MSG_TRUNC;
}
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
m->msg_iov, sz);
if (res)
goto exit;
res = sz;
} else {
if ((sock->state == SS_READY) ||
((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if ((sock->state != SS_READY) &&
(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
exit:
release_sock(sk);
return res;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int recv_msg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
u32 err;
int res;
/* Catch invalid receive requests */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely(sock->state == SS_UNCONNECTED)) {
res = -ENOTCONN;
goto exit;
}
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Capture sender's address (optional) */
set_orig_addr(m, msg);
/* Capture ancillary data (optional) */
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
if (unlikely(buf_len < sz)) {
sz = buf_len;
m->msg_flags |= MSG_TRUNC;
}
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
m->msg_iov, sz);
if (res)
goto exit;
res = sz;
} else {
if ((sock->state == SS_READY) ||
((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if ((sock->state != SS_READY) &&
(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
exit:
release_sock(sk);
return res;
}
| 166,517 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array(
v8::Isolate* isolate,
v8::Local<v8::Object> creation_context,
const base::ListValue* val) const {
v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize()));
for (size_t i = 0; i < val->GetSize(); ++i) {
const base::Value* child = NULL;
CHECK(val->Get(i, &child));
v8::Local<v8::Value> child_v8 =
ToV8ValueImpl(isolate, creation_context, child);
CHECK(!child_v8.IsEmpty());
v8::TryCatch try_catch(isolate);
result->Set(static_cast<uint32_t>(i), child_v8);
if (try_catch.HasCaught())
LOG(ERROR) << "Setter for index " << i << " threw an exception.";
}
return result;
}
Commit Message: V8ValueConverter::ToV8Value should not trigger setters
BUG=606390
Review URL: https://codereview.chromium.org/1918793003
Cr-Commit-Position: refs/heads/master@{#390045}
CWE ID: | v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array(
v8::Isolate* isolate,
v8::Local<v8::Object> creation_context,
const base::ListValue* val) const {
v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize()));
// TODO(robwu): Callers should pass in the context.
v8::Local<v8::Context> context = isolate->GetCurrentContext();
for (size_t i = 0; i < val->GetSize(); ++i) {
const base::Value* child = NULL;
CHECK(val->Get(i, &child));
v8::Local<v8::Value> child_v8 =
ToV8ValueImpl(isolate, creation_context, child);
CHECK(!child_v8.IsEmpty());
v8::Maybe<bool> maybe =
result->CreateDataProperty(context, static_cast<uint32_t>(i), child_v8);
if (!maybe.IsJust() || !maybe.FromJust())
LOG(ERROR) << "Failed to set value at index " << i;
}
return result;
}
| 173,283 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: kdc_process_s4u2self_req(kdc_realm_t *kdc_active_realm,
krb5_kdc_req *request,
krb5_const_principal client_princ,
krb5_const_principal header_srv_princ,
krb5_boolean issuing_referral,
const krb5_db_entry *server,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_timestamp kdc_time,
krb5_pa_s4u_x509_user **s4u_x509_user,
krb5_db_entry **princ_ptr,
const char **status)
{
krb5_error_code code;
krb5_boolean is_local_tgt;
krb5_pa_data *pa_data;
int flags;
krb5_db_entry *princ;
*princ_ptr = NULL;
pa_data = krb5int_find_pa_data(kdc_context,
request->padata, KRB5_PADATA_S4U_X509_USER);
if (pa_data != NULL) {
code = kdc_process_s4u_x509_user(kdc_context,
request,
pa_data,
tgs_subkey,
tgs_session,
s4u_x509_user,
status);
if (code != 0)
return code;
} else {
pa_data = krb5int_find_pa_data(kdc_context,
request->padata, KRB5_PADATA_FOR_USER);
if (pa_data != NULL) {
code = kdc_process_for_user(kdc_active_realm,
pa_data,
tgs_session,
s4u_x509_user,
status);
if (code != 0)
return code;
} else
return 0;
}
/*
* We need to compare the client name in the TGT with the requested
* server name. Supporting server name aliases without assuming a
* global name service makes this difficult to do.
*
* The comparison below handles the following cases (note that the
* term "principal name" below excludes the realm).
*
* (1) The requested service is a host-based service with two name
* components, in which case we assume the principal name to
* contain sufficient qualifying information. The realm is
* ignored for the purpose of comparison.
*
* (2) The requested service name is an enterprise principal name:
* the service principal name is compared with the unparsed
* form of the client name (including its realm).
*
* (3) The requested service is some other name type: an exact
* match is required.
*
* An alternative would be to look up the server once again with
* FLAG_CANONICALIZE | FLAG_CLIENT_REFERRALS_ONLY set, do an exact
* match between the returned name and client_princ. However, this
* assumes that the client set FLAG_CANONICALIZE when requesting
* the TGT and that we have a global name service.
*/
flags = 0;
switch (krb5_princ_type(kdc_context, request->server)) {
case KRB5_NT_SRV_HST: /* (1) */
if (krb5_princ_size(kdc_context, request->server) == 2)
flags |= KRB5_PRINCIPAL_COMPARE_IGNORE_REALM;
break;
case KRB5_NT_ENTERPRISE_PRINCIPAL: /* (2) */
flags |= KRB5_PRINCIPAL_COMPARE_ENTERPRISE;
break;
default: /* (3) */
break;
}
if (!krb5_principal_compare_flags(kdc_context,
request->server,
client_princ,
flags)) {
*status = "INVALID_S4U2SELF_REQUEST";
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error code */
}
/*
* Protocol transition is mutually exclusive with renew/forward/etc
* as well as user-to-user and constrained delegation. This check
* is also made in validate_as_request().
*
* We can assert from this check that the header ticket was a TGT, as
* that is validated previously in validate_tgs_request().
*/
if (request->kdc_options & AS_INVALID_OPTIONS) {
*status = "INVALID AS OPTIONS";
return KRB5KDC_ERR_BADOPTION;
}
/*
* Valid S4U2Self requests can occur in the following combinations:
*
* (1) local TGT, local user, local server
* (2) cross TGT, local user, issuing referral
* (3) cross TGT, non-local user, issuing referral
* (4) cross TGT, non-local user, local server
*
* The first case is for a single-realm S4U2Self scenario; the second,
* third, and fourth cases are for the initial, intermediate (if any), and
* final cross-realm requests in a multi-realm scenario.
*/
is_local_tgt = !is_cross_tgs_principal(header_srv_princ);
if (is_local_tgt && issuing_referral) {
/* The requesting server appears to no longer exist, and we found
* a referral instead. Treat this as a server lookup failure. */
*status = "LOOKING_UP_SERVER";
return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
}
/*
* Do not attempt to lookup principals in foreign realms.
*/
if (is_local_principal(kdc_active_realm,
(*s4u_x509_user)->user_id.user)) {
krb5_db_entry no_server;
krb5_pa_data **e_data = NULL;
if (!is_local_tgt && !issuing_referral) {
/* A local server should not need a cross-realm TGT to impersonate
* a local principal. */
*status = "NOT_CROSS_REALM_REQUEST";
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error */
}
code = krb5_db_get_principal(kdc_context,
(*s4u_x509_user)->user_id.user,
KRB5_KDB_FLAG_INCLUDE_PAC, &princ);
if (code == KRB5_KDB_NOENTRY) {
*status = "UNKNOWN_S4U2SELF_PRINCIPAL";
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
} else if (code) {
*status = "LOOKING_UP_S4U2SELF_PRINCIPAL";
return code; /* caller can free for_user */
}
memset(&no_server, 0, sizeof(no_server));
code = validate_as_request(kdc_active_realm, request, *princ,
no_server, kdc_time, status, &e_data);
if (code) {
krb5_db_free_principal(kdc_context, princ);
krb5_free_pa_data(kdc_context, e_data);
return code;
}
*princ_ptr = princ;
} else if (is_local_tgt) {
/*
* The server is asking to impersonate a principal from another realm,
* using a local TGT. It should instead ask that principal's realm and
* follow referrals back to us.
*/
*status = "S4U2SELF_CLIENT_NOT_OURS";
return KRB5KDC_ERR_POLICY; /* match Windows error */
}
return 0;
}
Commit Message: Ignore password attributes for S4U2Self requests
For consistency with Windows KDCs, allow protocol transition to work
even if the password has expired or needs changing.
Also, when looking up an enterprise principal with an AS request,
treat ERR_KEY_EXP as confirmation that the client is present in the
realm.
[[email protected]: added comment in kdc_process_s4u2self_req(); edited
commit message]
ticket: 8763 (new)
tags: pullup
target_version: 1.17
CWE ID: CWE-617 | kdc_process_s4u2self_req(kdc_realm_t *kdc_active_realm,
krb5_kdc_req *request,
krb5_const_principal client_princ,
krb5_const_principal header_srv_princ,
krb5_boolean issuing_referral,
const krb5_db_entry *server,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_timestamp kdc_time,
krb5_pa_s4u_x509_user **s4u_x509_user,
krb5_db_entry **princ_ptr,
const char **status)
{
krb5_error_code code;
krb5_boolean is_local_tgt;
krb5_pa_data *pa_data;
int flags;
krb5_db_entry *princ;
*princ_ptr = NULL;
pa_data = krb5int_find_pa_data(kdc_context,
request->padata, KRB5_PADATA_S4U_X509_USER);
if (pa_data != NULL) {
code = kdc_process_s4u_x509_user(kdc_context,
request,
pa_data,
tgs_subkey,
tgs_session,
s4u_x509_user,
status);
if (code != 0)
return code;
} else {
pa_data = krb5int_find_pa_data(kdc_context,
request->padata, KRB5_PADATA_FOR_USER);
if (pa_data != NULL) {
code = kdc_process_for_user(kdc_active_realm,
pa_data,
tgs_session,
s4u_x509_user,
status);
if (code != 0)
return code;
} else
return 0;
}
/*
* We need to compare the client name in the TGT with the requested
* server name. Supporting server name aliases without assuming a
* global name service makes this difficult to do.
*
* The comparison below handles the following cases (note that the
* term "principal name" below excludes the realm).
*
* (1) The requested service is a host-based service with two name
* components, in which case we assume the principal name to
* contain sufficient qualifying information. The realm is
* ignored for the purpose of comparison.
*
* (2) The requested service name is an enterprise principal name:
* the service principal name is compared with the unparsed
* form of the client name (including its realm).
*
* (3) The requested service is some other name type: an exact
* match is required.
*
* An alternative would be to look up the server once again with
* FLAG_CANONICALIZE | FLAG_CLIENT_REFERRALS_ONLY set, do an exact
* match between the returned name and client_princ. However, this
* assumes that the client set FLAG_CANONICALIZE when requesting
* the TGT and that we have a global name service.
*/
flags = 0;
switch (krb5_princ_type(kdc_context, request->server)) {
case KRB5_NT_SRV_HST: /* (1) */
if (krb5_princ_size(kdc_context, request->server) == 2)
flags |= KRB5_PRINCIPAL_COMPARE_IGNORE_REALM;
break;
case KRB5_NT_ENTERPRISE_PRINCIPAL: /* (2) */
flags |= KRB5_PRINCIPAL_COMPARE_ENTERPRISE;
break;
default: /* (3) */
break;
}
if (!krb5_principal_compare_flags(kdc_context,
request->server,
client_princ,
flags)) {
*status = "INVALID_S4U2SELF_REQUEST";
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error code */
}
/*
* Protocol transition is mutually exclusive with renew/forward/etc
* as well as user-to-user and constrained delegation. This check
* is also made in validate_as_request().
*
* We can assert from this check that the header ticket was a TGT, as
* that is validated previously in validate_tgs_request().
*/
if (request->kdc_options & AS_INVALID_OPTIONS) {
*status = "INVALID AS OPTIONS";
return KRB5KDC_ERR_BADOPTION;
}
/*
* Valid S4U2Self requests can occur in the following combinations:
*
* (1) local TGT, local user, local server
* (2) cross TGT, local user, issuing referral
* (3) cross TGT, non-local user, issuing referral
* (4) cross TGT, non-local user, local server
*
* The first case is for a single-realm S4U2Self scenario; the second,
* third, and fourth cases are for the initial, intermediate (if any), and
* final cross-realm requests in a multi-realm scenario.
*/
is_local_tgt = !is_cross_tgs_principal(header_srv_princ);
if (is_local_tgt && issuing_referral) {
/* The requesting server appears to no longer exist, and we found
* a referral instead. Treat this as a server lookup failure. */
*status = "LOOKING_UP_SERVER";
return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
}
/*
* Do not attempt to lookup principals in foreign realms.
*/
if (is_local_principal(kdc_active_realm,
(*s4u_x509_user)->user_id.user)) {
krb5_db_entry no_server;
krb5_pa_data **e_data = NULL;
if (!is_local_tgt && !issuing_referral) {
/* A local server should not need a cross-realm TGT to impersonate
* a local principal. */
*status = "NOT_CROSS_REALM_REQUEST";
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error */
}
code = krb5_db_get_principal(kdc_context,
(*s4u_x509_user)->user_id.user,
KRB5_KDB_FLAG_INCLUDE_PAC, &princ);
if (code == KRB5_KDB_NOENTRY) {
*status = "UNKNOWN_S4U2SELF_PRINCIPAL";
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
} else if (code) {
*status = "LOOKING_UP_S4U2SELF_PRINCIPAL";
return code; /* caller can free for_user */
}
memset(&no_server, 0, sizeof(no_server));
/* Ignore password expiration and needchange attributes (as Windows
* does), since S4U2Self is not password authentication. */
princ->pw_expiration = 0;
clear(princ->attributes, KRB5_KDB_REQUIRES_PWCHANGE);
code = validate_as_request(kdc_active_realm, request, *princ,
no_server, kdc_time, status, &e_data);
if (code) {
krb5_db_free_principal(kdc_context, princ);
krb5_free_pa_data(kdc_context, e_data);
return code;
}
*princ_ptr = princ;
} else if (is_local_tgt) {
/*
* The server is asking to impersonate a principal from another realm,
* using a local TGT. It should instead ask that principal's realm and
* follow referrals back to us.
*/
*status = "S4U2SELF_CLIENT_NOT_OURS";
return KRB5KDC_ERR_POLICY; /* match Windows error */
}
return 0;
}
| 168,957 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: generate_palette(png_colorp palette, png_bytep trans, int bit_depth,
png_const_bytep gamma_table, unsigned int *colors)
{
/*
* 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
* 2-bit: entry 0: transparent-green
* entry 1: 40%-red
* entry 2: 80%-blue
* entry 3: opaque-white
* 4-bit: the 16 combinations of the 2-bit case
* 8-bit: the 256 combinations of the 4-bit case
*/
switch (colors[0])
{
default:
fprintf(stderr, "makepng: --colors=...: invalid count %u\n",
colors[0]);
exit(1);
case 1:
set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255,
gamma_table);
return 1;
case 2:
set_color(palette+0, trans+0, colors[1], colors[1], colors[1],
colors[2], gamma_table);
return 1;
case 3:
set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255,
gamma_table);
return 1;
case 4:
set_color(palette+0, trans+0, colors[1], colors[2], colors[3],
colors[4], gamma_table);
return 1;
case 0:
if (bit_depth == 1)
{
set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table);
set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table);
return 2;
}
else
{
unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */
unsigned int x, y, ip;
for (x=0; x<size; ++x) for (y=0; y<size; ++y)
{
ip = x + (size * y);
/* size is at most 16, so the scaled value below fits in 16 bits
*/
# define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2))
# define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\
(interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\
(size*size))
set_color(palette+ip, trans+ip,
/* color: green, red,blue,white */
xyinterp(x, y, 0, 255, 0, 255),
xyinterp(x, y, 255, 0, 0, 255),
xyinterp(x, y, 0, 0, 255, 255),
/* alpha: 0, 102, 204, 255) */
xyinterp(x, y, 0, 102, 204, 255),
gamma_table);
}
return ip+1;
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | generate_palette(png_colorp palette, png_bytep trans, int bit_depth,
png_const_bytep gamma_table, unsigned int *colors)
{
/*
* 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
* 2-bit: entry 0: transparent-green
* entry 1: 40%-red
* entry 2: 80%-blue
* entry 3: opaque-white
* 4-bit: the 16 combinations of the 2-bit case
* 8-bit: the 256 combinations of the 4-bit case
*/
switch (colors[0])
{
default:
fprintf(stderr, "makepng: --colors=...: invalid count %u\n",
colors[0]);
exit(1);
case 1:
set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255,
gamma_table);
return 1;
case 2:
set_color(palette+0, trans+0, colors[1], colors[1], colors[1],
colors[2], gamma_table);
return 1;
case 3:
set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255,
gamma_table);
return 1;
case 4:
set_color(palette+0, trans+0, colors[1], colors[2], colors[3],
colors[4], gamma_table);
return 1;
case 0:
if (bit_depth == 1)
{
set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table);
set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table);
return 2;
}
else
{
unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */
unsigned int x, y;
volatile unsigned int ip = 0;
for (x=0; x<size; ++x) for (y=0; y<size; ++y)
{
ip = x + (size * y);
/* size is at most 16, so the scaled value below fits in 16 bits
*/
# define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2))
# define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\
(interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\
(size*size))
set_color(palette+ip, trans+ip,
/* color: green, red,blue,white */
xyinterp(x, y, 0, 255, 0, 255),
xyinterp(x, y, 255, 0, 0, 255),
xyinterp(x, y, 0, 0, 255, 255),
/* alpha: 0, 102, 204, 255) */
xyinterp(x, y, 0, 102, 204, 255),
gamma_table);
}
return ip+1;
}
}
}
| 173,579 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nalm_dump(FILE * trace, char *data, u32 data_size)
{
GF_BitStream *bs;
Bool rle, large_size;
u32 entry_count;
if (!data) {
fprintf(trace, "<NALUMap rle=\"\" large_size=\"\">\n");
fprintf(trace, "<NALUMapEntry NALU_startNumber=\"\" groupID=\"\"/>\n");
fprintf(trace, "</NALUMap>\n");
return;
}
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 6);
large_size = gf_bs_read_int(bs, 1);
rle = gf_bs_read_int(bs, 1);
entry_count = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "<NALUMap rle=\"%d\" large_size=\"%d\">\n", rle, large_size);
while (entry_count) {
u32 ID;
fprintf(trace, "<NALUMapEntry ");
if (rle) {
u32 start_num = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "NALU_startNumber=\"%d\" ", start_num);
}
ID = gf_bs_read_u16(bs);
fprintf(trace, "groupID=\"%d\"/>\n", ID);
entry_count--;
}
gf_bs_del(bs);
fprintf(trace, "</NALUMap>\n");
return;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125 | static void nalm_dump(FILE * trace, char *data, u32 data_size)
{
GF_BitStream *bs;
Bool rle, large_size;
u32 entry_count;
if (!data) {
fprintf(trace, "<NALUMap rle=\"\" large_size=\"\">\n");
fprintf(trace, "<NALUMapEntry NALU_startNumber=\"\" groupID=\"\"/>\n");
fprintf(trace, "</NALUMap>\n");
return;
}
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 6);
large_size = gf_bs_read_int(bs, 1);
rle = gf_bs_read_int(bs, 1);
entry_count = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "<NALUMap rle=\"%d\" large_size=\"%d\">\n", rle, large_size);
while (entry_count) {
u32 ID;
fprintf(trace, "<NALUMapEntry ");
if (rle) {
u32 start_num = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "NALU_startNumber=\"%d\" ", start_num);
}
ID = gf_bs_read_u16(bs);
fprintf(trace, "groupID=\"%d\"/>\n", ID);
entry_count--;
}
gf_bs_del(bs);
fprintf(trace, "</NALUMap>\n");
return;
}
| 169,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WindowOpenDisposition TestBrowserWindow::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 TestBrowserWindow::GetDispositionForPopupBounds(
| 173,208 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(Phar, copy)
{
char *oldfile, *newfile, *error;
const char *pcr_error;
size_t oldfile_len, newfile_len;
phar_entry_info *oldentry, newentry = {0}, *temp;
int tmp_len = 0;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) {
return;
}
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile);
RETURN_FALSE;
}
if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len)) || oldentry->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) {
if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) || !temp->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
}
tmp_len = (int)newfile_len;
if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname);
RETURN_FALSE;
}
newfile_len = tmp_len;
if (phar_obj->archive->is_persistent) {
if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
/* re-populate with copied-on-write entry */
oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len);
}
memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info));
if (Z_TYPE(newentry.metadata) != IS_UNDEF) {
zval_copy_ctor(&newentry.metadata);
newentry.metadata_str.s = NULL;
}
newentry.filename = estrndup(newfile, newfile_len);
newentry.filename_len = newfile_len;
newentry.fp_refcount = 0;
if (oldentry->fp_type != PHAR_FP) {
if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) {
efree(newentry.filename);
php_stream_close(newentry.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
return;
}
}
zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info));
phar_obj->archive->is_modified = 1;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, copy)
{
char *oldfile, *newfile, *error;
const char *pcr_error;
size_t oldfile_len, newfile_len;
phar_entry_info *oldentry, newentry = {0}, *temp;
int tmp_len = 0;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) {
return;
}
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile);
RETURN_FALSE;
}
if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len)) || oldentry->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) {
if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) || !temp->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
}
tmp_len = (int)newfile_len;
if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname);
RETURN_FALSE;
}
newfile_len = tmp_len;
if (phar_obj->archive->is_persistent) {
if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
/* re-populate with copied-on-write entry */
oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len);
}
memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info));
if (Z_TYPE(newentry.metadata) != IS_UNDEF) {
zval_copy_ctor(&newentry.metadata);
newentry.metadata_str.s = NULL;
}
newentry.filename = estrndup(newfile, newfile_len);
newentry.filename_len = newfile_len;
newentry.fp_refcount = 0;
if (oldentry->fp_type != PHAR_FP) {
if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) {
efree(newentry.filename);
php_stream_close(newentry.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
return;
}
}
zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info));
phar_obj->archive->is_modified = 1;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
| 165,064 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static plist_t parse_string_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_STRING;
data->strval = (char *) malloc(sizeof(char) * (size + 1));
memcpy(data->strval, *bnode, size);
data->strval[size] = '\0';
data->length = strlen(data->strval);
return node_create(NULL, data);
}
Commit Message: bplist: Make sure to bail out if malloc() fails in parse_string_node()
Credit to Wang Junjie <[email protected]> (#93)
CWE ID: CWE-119 | static plist_t parse_string_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_STRING;
data->strval = (char *) malloc(sizeof(char) * (size + 1));
if (!data->strval) {
plist_free_data(data);
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(char) * (size + 1));
return NULL;
}
memcpy(data->strval, *bnode, size);
data->strval[size] = '\0';
data->length = strlen(data->strval);
return node_create(NULL, data);
}
| 168,335 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHPAPI php_stream *_php_stream_memory_create(int mode STREAMS_DC TSRMLS_DC)
{
php_stream_memory_data *self;
php_stream *stream;
self = emalloc(sizeof(*self));
self->data = NULL;
self->fpos = 0;
self->fsize = 0;
self->smax = ~0u;
self->mode = mode;
stream = php_stream_alloc_rel(&php_stream_memory_ops, self, 0, mode & TEMP_STREAM_READONLY ? "rb" : "w+b");
stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
return stream;
}
Commit Message:
CWE ID: CWE-20 | PHPAPI php_stream *_php_stream_memory_create(int mode STREAMS_DC TSRMLS_DC)
{
php_stream_memory_data *self;
php_stream *stream;
self = emalloc(sizeof(*self));
self->data = NULL;
self->fpos = 0;
self->fsize = 0;
self->smax = ~0u;
self->mode = mode;
stream = php_stream_alloc_rel(&php_stream_memory_ops, self, 0, mode & TEMP_STREAM_READONLY ? "rb" : "w+b");
stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
return stream;
}
| 165,474 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackAlignment() {
if (!ContextGL())
return;
ContextGL()->PixelStorei(GL_PACK_ALIGNMENT, pack_alignment_);
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119 | void WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackAlignment() {
void WebGLRenderingContextBase::
DrawingBufferClientRestorePixelPackParameters() {
if (!ContextGL())
return;
ContextGL()->PixelStorei(GL_PACK_ALIGNMENT, pack_alignment_);
}
| 172,289 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (connect(sock, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
goto error;
if (send(sock, &type, 1, 0) != 1)
goto error;
if (send(sock, &length, 2, 0) != 2)
goto error;
if (send(sock, packet, length, 0) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (TEMP_FAILURE_RETRY(connect(sock, (const struct sockaddr *)&addr, sizeof(addr))) == -1)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, &type, 1, 0)) != 1)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, &length, 2, 0)) != 2)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, packet, length, 0)) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
| 173,492 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Splash::vertFlipImage(SplashBitmap *img, int width, int height,
int nComps) {
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
w = width * nComps;
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
w = width * nComps;
lineBuf = (Guchar *)gmalloc(w);
p0 += width, p1 -= width) {
memcpy(lineBuf, p0, width);
memcpy(p0, p1, width);
memcpy(p1, lineBuf, width);
}
}
Commit Message:
CWE ID: CWE-119 | void Splash::vertFlipImage(SplashBitmap *img, int width, int height,
int nComps) {
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
w = width * nComps;
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
if (unlikely(img->data == NULL)) {
error(errInternal, -1, "img->data is NULL in Splash::vertFlipImage");
return;
}
w = width * nComps;
lineBuf = (Guchar *)gmalloc(w);
p0 += width, p1 -= width) {
memcpy(lineBuf, p0, width);
memcpy(p0, p1, width);
memcpy(p1, lineBuf, width);
}
}
| 164,736 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RendererSchedulerImpl::OnShutdownTaskQueue(
const scoped_refptr<MainThreadTaskQueue>& task_queue) {
if (main_thread_only().was_shutdown)
return;
if (task_queue_throttler_)
task_queue_throttler_->ShutdownTaskQueue(task_queue.get());
if (task_runners_.erase(task_queue)) {
switch (task_queue->queue_class()) {
case MainThreadTaskQueue::QueueClass::kTimer:
task_queue->RemoveTaskObserver(
&main_thread_only().timer_task_cost_estimator);
case MainThreadTaskQueue::QueueClass::kLoading:
task_queue->RemoveTaskObserver(
&main_thread_only().loading_task_cost_estimator);
default:
break;
}
}
}
Commit Message: [scheduler] Remove implicit fallthrough in switch
Bail out early when a condition in the switch is fulfilled.
This does not change behaviour due to RemoveTaskObserver being no-op when
the task observer is not present in the list.
[email protected]
Bug: 177475
Change-Id: Ibc7772c79f8a8c8a1d63a997dabe1efda5d3a7bd
Reviewed-on: https://chromium-review.googlesource.com/891187
Reviewed-by: Nico Weber <[email protected]>
Commit-Queue: Alexander Timin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532649}
CWE ID: CWE-119 | void RendererSchedulerImpl::OnShutdownTaskQueue(
const scoped_refptr<MainThreadTaskQueue>& task_queue) {
if (main_thread_only().was_shutdown)
return;
if (task_queue_throttler_)
task_queue_throttler_->ShutdownTaskQueue(task_queue.get());
if (task_runners_.erase(task_queue)) {
switch (task_queue->queue_class()) {
case MainThreadTaskQueue::QueueClass::kTimer:
task_queue->RemoveTaskObserver(
&main_thread_only().timer_task_cost_estimator);
break;
case MainThreadTaskQueue::QueueClass::kLoading:
task_queue->RemoveTaskObserver(
&main_thread_only().loading_task_cost_estimator);
break;
default:
break;
}
}
}
| 172,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer,
raptor_option option)
{
int result = -1;
switch(option) {
case RAPTOR_OPTION_WRITER_AUTO_INDENT:
result = TURTLE_WRITER_AUTO_INDENT(turtle_writer);
break;
case RAPTOR_OPTION_WRITER_INDENT_WIDTH:
result = turtle_writer->indent;
break;
/* writer options */
case RAPTOR_OPTION_WRITER_AUTO_EMPTY:
case RAPTOR_OPTION_WRITER_XML_VERSION:
case RAPTOR_OPTION_WRITER_XML_DECLARATION:
/* parser options */
case RAPTOR_OPTION_SCANNING:
case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES:
case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES:
case RAPTOR_OPTION_ALLOW_BAGID:
case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST:
case RAPTOR_OPTION_NORMALIZE_LANGUAGE:
case RAPTOR_OPTION_NON_NFC_FATAL:
case RAPTOR_OPTION_WARN_OTHER_PARSETYPES:
case RAPTOR_OPTION_CHECK_RDF_ID:
case RAPTOR_OPTION_HTML_TAG_SOUP:
case RAPTOR_OPTION_MICROFORMATS:
case RAPTOR_OPTION_HTML_LINK:
case RAPTOR_OPTION_WWW_TIMEOUT:
case RAPTOR_OPTION_STRICT:
/* Shared */
case RAPTOR_OPTION_NO_NET:
case RAPTOR_OPTION_NO_FILE:
/* XML writer options */
case RAPTOR_OPTION_RELATIVE_URIS:
/* DOT serializer options */
case RAPTOR_OPTION_RESOURCE_BORDER:
case RAPTOR_OPTION_LITERAL_BORDER:
case RAPTOR_OPTION_BNODE_BORDER:
case RAPTOR_OPTION_RESOURCE_FILL:
case RAPTOR_OPTION_LITERAL_FILL:
case RAPTOR_OPTION_BNODE_FILL:
/* JSON serializer options */
case RAPTOR_OPTION_JSON_CALLBACK:
case RAPTOR_OPTION_JSON_EXTRA_DATA:
case RAPTOR_OPTION_RSS_TRIPLES:
case RAPTOR_OPTION_ATOM_ENTRY_URI:
case RAPTOR_OPTION_PREFIX_ELEMENTS:
/* Turtle serializer option */
case RAPTOR_OPTION_WRITE_BASE_URI:
/* WWW option */
case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL:
case RAPTOR_OPTION_WWW_HTTP_USER_AGENT:
case RAPTOR_OPTION_WWW_CERT_FILENAME:
case RAPTOR_OPTION_WWW_CERT_TYPE:
case RAPTOR_OPTION_WWW_CERT_PASSPHRASE:
case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER:
case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST:
default:
break;
}
return result;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200 | raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer,
raptor_option option)
{
int result = -1;
switch(option) {
case RAPTOR_OPTION_WRITER_AUTO_INDENT:
result = TURTLE_WRITER_AUTO_INDENT(turtle_writer);
break;
case RAPTOR_OPTION_WRITER_INDENT_WIDTH:
result = turtle_writer->indent;
break;
/* writer options */
case RAPTOR_OPTION_WRITER_AUTO_EMPTY:
case RAPTOR_OPTION_WRITER_XML_VERSION:
case RAPTOR_OPTION_WRITER_XML_DECLARATION:
/* parser options */
case RAPTOR_OPTION_SCANNING:
case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES:
case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES:
case RAPTOR_OPTION_ALLOW_BAGID:
case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST:
case RAPTOR_OPTION_NORMALIZE_LANGUAGE:
case RAPTOR_OPTION_NON_NFC_FATAL:
case RAPTOR_OPTION_WARN_OTHER_PARSETYPES:
case RAPTOR_OPTION_CHECK_RDF_ID:
case RAPTOR_OPTION_HTML_TAG_SOUP:
case RAPTOR_OPTION_MICROFORMATS:
case RAPTOR_OPTION_HTML_LINK:
case RAPTOR_OPTION_WWW_TIMEOUT:
case RAPTOR_OPTION_STRICT:
/* Shared */
case RAPTOR_OPTION_NO_NET:
case RAPTOR_OPTION_NO_FILE:
case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES:
/* XML writer options */
case RAPTOR_OPTION_RELATIVE_URIS:
/* DOT serializer options */
case RAPTOR_OPTION_RESOURCE_BORDER:
case RAPTOR_OPTION_LITERAL_BORDER:
case RAPTOR_OPTION_BNODE_BORDER:
case RAPTOR_OPTION_RESOURCE_FILL:
case RAPTOR_OPTION_LITERAL_FILL:
case RAPTOR_OPTION_BNODE_FILL:
/* JSON serializer options */
case RAPTOR_OPTION_JSON_CALLBACK:
case RAPTOR_OPTION_JSON_EXTRA_DATA:
case RAPTOR_OPTION_RSS_TRIPLES:
case RAPTOR_OPTION_ATOM_ENTRY_URI:
case RAPTOR_OPTION_PREFIX_ELEMENTS:
/* Turtle serializer option */
case RAPTOR_OPTION_WRITE_BASE_URI:
/* WWW option */
case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL:
case RAPTOR_OPTION_WWW_HTTP_USER_AGENT:
case RAPTOR_OPTION_WWW_CERT_FILENAME:
case RAPTOR_OPTION_WWW_CERT_TYPE:
case RAPTOR_OPTION_WWW_CERT_PASSPHRASE:
case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER:
case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST:
default:
break;
}
return result;
}
| 165,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: dissect_usb_video_control_interface_descriptor(proto_tree *parent_tree, tvbuff_t *tvb,
guint8 descriptor_len, packet_info *pinfo, usb_conv_info_t *usb_conv_info)
{
video_conv_info_t *video_conv_info = NULL;
video_entity_t *entity = NULL;
proto_item *item = NULL;
proto_item *subtype_item = NULL;
proto_tree *tree = NULL;
guint8 entity_id = 0;
guint16 terminal_type = 0;
int offset = 0;
guint8 subtype;
subtype = tvb_get_guint8(tvb, offset+2);
if (parent_tree)
{
const gchar *subtype_str;
subtype_str = val_to_str_ext(subtype, &vc_if_descriptor_subtypes_ext, "Unknown (0x%x)");
tree = proto_tree_add_subtree_format(parent_tree, tvb, offset, descriptor_len,
ett_descriptor_video_control, &item, "VIDEO CONTROL INTERFACE DESCRIPTOR [%s]",
subtype_str);
}
/* Common fields */
dissect_usb_descriptor_header(tree, tvb, offset, &vid_descriptor_type_vals_ext);
subtype_item = proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_subtype, tvb, offset+2, 1, ENC_LITTLE_ENDIAN);
offset += 3;
if (subtype == VC_HEADER)
{
guint8 num_vs_interfaces;
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bcdUVC, tvb, offset, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_vid_ifdesc_wTotalLength, tvb, offset+2, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_dwClockFrequency, tvb, offset+4, 4, ENC_LITTLE_ENDIAN);
num_vs_interfaces = tvb_get_guint8(tvb, offset+8);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bInCollection, tvb, offset+8, 1, ENC_LITTLE_ENDIAN);
if (num_vs_interfaces > 0)
{
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_baInterfaceNr, tvb, offset+9, num_vs_interfaces, ENC_NA);
}
offset += 9 + num_vs_interfaces;
}
else if ((subtype == VC_INPUT_TERMINAL) || (subtype == VC_OUTPUT_TERMINAL))
{
/* Fields common to input and output terminals */
entity_id = tvb_get_guint8(tvb, offset);
terminal_type = tvb_get_letohs(tvb, offset+1);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_id, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_type, tvb, offset+1, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_assoc_terminal, tvb, offset+3, 1, ENC_LITTLE_ENDIAN);
offset += 4;
if (subtype == VC_OUTPUT_TERMINAL)
{
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_src_id, tvb, offset, 1, ENC_LITTLE_ENDIAN);
++offset;
}
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_iTerminal, tvb, offset, 1, ENC_LITTLE_ENDIAN);
++offset;
if (subtype == VC_INPUT_TERMINAL)
{
if (terminal_type == ITT_CAMERA)
{
offset = dissect_usb_video_camera_terminal(tree, tvb, offset);
}
else if (terminal_type == ITT_MEDIA_TRANSPORT_INPUT)
{
/* @todo */
}
}
if (subtype == VC_OUTPUT_TERMINAL)
{
if (terminal_type == OTT_MEDIA_TRANSPORT_OUTPUT)
{
/* @todo */
}
}
}
else
{
/* Field common to extension / processing / selector / encoding units */
entity_id = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_unit_id, tvb, offset, 1, ENC_LITTLE_ENDIAN);
++offset;
if (subtype == VC_PROCESSING_UNIT)
{
offset = dissect_usb_video_processing_unit(tree, tvb, offset);
}
else if (subtype == VC_SELECTOR_UNIT)
{
offset = dissect_usb_video_selector_unit(tree, tvb, offset);
}
else if (subtype == VC_EXTENSION_UNIT)
{
offset = dissect_usb_video_extension_unit(tree, tvb, offset);
}
else if (subtype == VC_ENCODING_UNIT)
{
/* @todo UVC 1.5 */
}
else
{
expert_add_info_format(pinfo, subtype_item, &ei_usb_vid_subtype_unknown,
"Unknown VC subtype %u", subtype);
}
}
/* Soak up descriptor bytes beyond those we know how to dissect */
if (offset < descriptor_len)
{
proto_tree_add_item(tree, hf_usb_vid_descriptor_data, tvb, offset, descriptor_len-offset, ENC_NA);
/* offset = descriptor_len; */
}
if (entity_id != 0)
proto_item_append_text(item, " (Entity %d)", entity_id);
if (subtype != VC_HEADER && usb_conv_info)
{
/* Switch to the usb_conv_info of the Video Control interface */
usb_conv_info = get_usb_iface_conv_info(pinfo, usb_conv_info->interfaceNum);
video_conv_info = (video_conv_info_t *)usb_conv_info->class_data;
if (!video_conv_info)
{
video_conv_info = wmem_new(wmem_file_scope(), video_conv_info_t);
video_conv_info->entities = wmem_tree_new(wmem_file_scope());
usb_conv_info->class_data = video_conv_info;
}
entity = (video_entity_t*) wmem_tree_lookup32(video_conv_info->entities, entity_id);
if (!entity)
{
entity = wmem_new(wmem_file_scope(), video_entity_t);
entity->entityID = entity_id;
entity->subtype = subtype;
entity->terminalType = terminal_type;
wmem_tree_insert32(video_conv_info->entities, entity_id, entity);
}
}
return descriptor_len;
}
Commit Message: Make class "type" for USB conversations.
USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match.
Bug: 12356
Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209
Reviewed-on: https://code.wireshark.org/review/15212
Petri-Dish: Michael Mann <[email protected]>
Reviewed-by: Martin Kaiser <[email protected]>
Petri-Dish: Martin Kaiser <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-476 | dissect_usb_video_control_interface_descriptor(proto_tree *parent_tree, tvbuff_t *tvb,
guint8 descriptor_len, packet_info *pinfo, usb_conv_info_t *usb_conv_info)
{
video_conv_info_t *video_conv_info = NULL;
video_entity_t *entity = NULL;
proto_item *item = NULL;
proto_item *subtype_item = NULL;
proto_tree *tree = NULL;
guint8 entity_id = 0;
guint16 terminal_type = 0;
int offset = 0;
guint8 subtype;
subtype = tvb_get_guint8(tvb, offset+2);
if (parent_tree)
{
const gchar *subtype_str;
subtype_str = val_to_str_ext(subtype, &vc_if_descriptor_subtypes_ext, "Unknown (0x%x)");
tree = proto_tree_add_subtree_format(parent_tree, tvb, offset, descriptor_len,
ett_descriptor_video_control, &item, "VIDEO CONTROL INTERFACE DESCRIPTOR [%s]",
subtype_str);
}
/* Common fields */
dissect_usb_descriptor_header(tree, tvb, offset, &vid_descriptor_type_vals_ext);
subtype_item = proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_subtype, tvb, offset+2, 1, ENC_LITTLE_ENDIAN);
offset += 3;
if (subtype == VC_HEADER)
{
guint8 num_vs_interfaces;
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bcdUVC, tvb, offset, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_vid_ifdesc_wTotalLength, tvb, offset+2, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_dwClockFrequency, tvb, offset+4, 4, ENC_LITTLE_ENDIAN);
num_vs_interfaces = tvb_get_guint8(tvb, offset+8);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bInCollection, tvb, offset+8, 1, ENC_LITTLE_ENDIAN);
if (num_vs_interfaces > 0)
{
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_baInterfaceNr, tvb, offset+9, num_vs_interfaces, ENC_NA);
}
offset += 9 + num_vs_interfaces;
}
else if ((subtype == VC_INPUT_TERMINAL) || (subtype == VC_OUTPUT_TERMINAL))
{
/* Fields common to input and output terminals */
entity_id = tvb_get_guint8(tvb, offset);
terminal_type = tvb_get_letohs(tvb, offset+1);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_id, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_type, tvb, offset+1, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_assoc_terminal, tvb, offset+3, 1, ENC_LITTLE_ENDIAN);
offset += 4;
if (subtype == VC_OUTPUT_TERMINAL)
{
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_src_id, tvb, offset, 1, ENC_LITTLE_ENDIAN);
++offset;
}
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_iTerminal, tvb, offset, 1, ENC_LITTLE_ENDIAN);
++offset;
if (subtype == VC_INPUT_TERMINAL)
{
if (terminal_type == ITT_CAMERA)
{
offset = dissect_usb_video_camera_terminal(tree, tvb, offset);
}
else if (terminal_type == ITT_MEDIA_TRANSPORT_INPUT)
{
/* @todo */
}
}
if (subtype == VC_OUTPUT_TERMINAL)
{
if (terminal_type == OTT_MEDIA_TRANSPORT_OUTPUT)
{
/* @todo */
}
}
}
else
{
/* Field common to extension / processing / selector / encoding units */
entity_id = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_unit_id, tvb, offset, 1, ENC_LITTLE_ENDIAN);
++offset;
if (subtype == VC_PROCESSING_UNIT)
{
offset = dissect_usb_video_processing_unit(tree, tvb, offset);
}
else if (subtype == VC_SELECTOR_UNIT)
{
offset = dissect_usb_video_selector_unit(tree, tvb, offset);
}
else if (subtype == VC_EXTENSION_UNIT)
{
offset = dissect_usb_video_extension_unit(tree, tvb, offset);
}
else if (subtype == VC_ENCODING_UNIT)
{
/* @todo UVC 1.5 */
}
else
{
expert_add_info_format(pinfo, subtype_item, &ei_usb_vid_subtype_unknown,
"Unknown VC subtype %u", subtype);
}
}
/* Soak up descriptor bytes beyond those we know how to dissect */
if (offset < descriptor_len)
{
proto_tree_add_item(tree, hf_usb_vid_descriptor_data, tvb, offset, descriptor_len-offset, ENC_NA);
/* offset = descriptor_len; */
}
if (entity_id != 0)
proto_item_append_text(item, " (Entity %d)", entity_id);
if (subtype != VC_HEADER && usb_conv_info)
{
/* Switch to the usb_conv_info of the Video Control interface */
usb_conv_info = get_usb_iface_conv_info(pinfo, usb_conv_info->interfaceNum);
video_conv_info = (video_conv_info_t *)usb_conv_info->class_data;
if (!video_conv_info)
{
video_conv_info = wmem_new(wmem_file_scope(), video_conv_info_t);
video_conv_info->entities = wmem_tree_new(wmem_file_scope());
usb_conv_info->class_data = video_conv_info;
usb_conv_info->class_data_type = USB_CONV_VIDEO;
} else if (usb_conv_info->class_data_type != USB_CONV_VIDEO) {
/* Stop dissection if another USB type is in the conversation */
return descriptor_len;
}
entity = (video_entity_t*) wmem_tree_lookup32(video_conv_info->entities, entity_id);
if (!entity)
{
entity = wmem_new(wmem_file_scope(), video_entity_t);
entity->entityID = entity_id;
entity->subtype = subtype;
entity->terminalType = terminal_type;
wmem_tree_insert32(video_conv_info->entities, entity_id, entity);
}
}
return descriptor_len;
}
| 167,155 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct mem_size_stats *mss = walk->private;
struct vm_area_struct *vma = mss->vma;
pte_t *pte;
spinlock_t *ptl;
spin_lock(&walk->mm->page_table_lock);
if (pmd_trans_huge(*pmd)) {
if (pmd_trans_splitting(*pmd)) {
spin_unlock(&walk->mm->page_table_lock);
wait_split_huge_page(vma->anon_vma, pmd);
} else {
smaps_pte_entry(*(pte_t *)pmd, addr,
HPAGE_PMD_SIZE, walk);
spin_unlock(&walk->mm->page_table_lock);
mss->anonymous_thp += HPAGE_PMD_SIZE;
return 0;
}
} else {
spin_unlock(&walk->mm->page_table_lock);
}
/*
* The mmap_sem held all the way back in m_start() is what
* keeps khugepaged out of here and from collapsing things
* in here.
*/
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE)
smaps_pte_entry(*pte, addr, PAGE_SIZE, walk);
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264 | static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct mem_size_stats *mss = walk->private;
struct vm_area_struct *vma = mss->vma;
pte_t *pte;
spinlock_t *ptl;
spin_lock(&walk->mm->page_table_lock);
if (pmd_trans_huge(*pmd)) {
if (pmd_trans_splitting(*pmd)) {
spin_unlock(&walk->mm->page_table_lock);
wait_split_huge_page(vma->anon_vma, pmd);
} else {
smaps_pte_entry(*(pte_t *)pmd, addr,
HPAGE_PMD_SIZE, walk);
spin_unlock(&walk->mm->page_table_lock);
mss->anonymous_thp += HPAGE_PMD_SIZE;
return 0;
}
} else {
spin_unlock(&walk->mm->page_table_lock);
}
if (pmd_trans_unstable(pmd))
return 0;
/*
* The mmap_sem held all the way back in m_start() is what
* keeps khugepaged out of here and from collapsing things
* in here.
*/
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE)
smaps_pte_entry(*pte, addr, PAGE_SIZE, walk);
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
| 165,630 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: print_attr_string(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
register u_int i;
ND_TCHECK2(data[0],length);
switch(attr_code)
{
case TUNNEL_PASS:
if (length < 3)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (*data && (*data <=0x1F) )
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data)));
data+=2;
length-=2;
break;
case TUNNEL_CLIENT_END:
case TUNNEL_SERVER_END:
case TUNNEL_PRIV_GROUP:
case TUNNEL_ASSIGN_ID:
case TUNNEL_CLIENT_AUTH:
case TUNNEL_SERVER_AUTH:
if (*data <= 0x1F)
{
if (length < 1)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (*data)
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
}
break;
case EGRESS_VLAN_NAME:
ND_PRINT((ndo, "%s (0x%02x) ",
tok2str(rfc4675_tagged,"Unknown tag",*data),
*data));
data++;
length--;
break;
}
for (i=0; *data && i < length ; i++, data++)
ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-13032/RADIUS: Check whether a byte exists before testing its value.
Reverse the test in a for loop to test the length before testing whether
we have a null byte.
This fixes a buffer over-read discovered by Bhargava Shastry.
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.
Clean up other length tests while we're at it.
CWE ID: CWE-125 | print_attr_string(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
register u_int i;
ND_TCHECK2(data[0],length);
switch(attr_code)
{
case TUNNEL_PASS:
if (length < 3)
goto trunc;
if (*data && (*data <=0x1F) )
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data)));
data+=2;
length-=2;
break;
case TUNNEL_CLIENT_END:
case TUNNEL_SERVER_END:
case TUNNEL_PRIV_GROUP:
case TUNNEL_ASSIGN_ID:
case TUNNEL_CLIENT_AUTH:
case TUNNEL_SERVER_AUTH:
if (*data <= 0x1F)
{
if (length < 1)
goto trunc;
if (*data)
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
}
break;
case EGRESS_VLAN_NAME:
if (length < 1)
goto trunc;
ND_PRINT((ndo, "%s (0x%02x) ",
tok2str(rfc4675_tagged,"Unknown tag",*data),
*data));
data++;
length--;
break;
}
for (i=0; i < length && *data; i++, data++)
ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 167,851 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void __exit pcd_exit(void)
{
struct pcd_unit *cd;
int unit;
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
if (cd->present) {
del_gendisk(cd->disk);
pi_release(cd->pi);
unregister_cdrom(&cd->info);
}
blk_cleanup_queue(cd->disk->queue);
blk_mq_free_tag_set(&cd->tag_set);
put_disk(cd->disk);
}
unregister_blkdev(major, name);
pi_unregister_driver(par_drv);
}
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 void __exit pcd_exit(void)
{
struct pcd_unit *cd;
int unit;
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
if (!cd->disk)
continue;
if (cd->present) {
del_gendisk(cd->disk);
pi_release(cd->pi);
unregister_cdrom(&cd->info);
}
blk_cleanup_queue(cd->disk->queue);
blk_mq_free_tag_set(&cd->tag_set);
put_disk(cd->disk);
}
unregister_blkdev(major, name);
pi_unregister_driver(par_drv);
}
| 169,518 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int usb_audio_probe(struct usb_interface *intf,
const struct usb_device_id *usb_id)
{
struct usb_device *dev = interface_to_usbdev(intf);
const struct snd_usb_audio_quirk *quirk =
(const struct snd_usb_audio_quirk *)usb_id->driver_info;
struct snd_usb_audio *chip;
int i, err;
struct usb_host_interface *alts;
int ifnum;
u32 id;
alts = &intf->altsetting[0];
ifnum = get_iface_desc(alts)->bInterfaceNumber;
id = USB_ID(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (get_alias_id(dev, &id))
quirk = get_alias_quirk(dev, id);
if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)
return -ENXIO;
err = snd_usb_apply_boot_quirk(dev, intf, quirk, id);
if (err < 0)
return err;
/*
* found a config. now register to ALSA
*/
/* check whether it's already registered */
chip = NULL;
mutex_lock(®ister_mutex);
for (i = 0; i < SNDRV_CARDS; i++) {
if (usb_chip[i] && usb_chip[i]->dev == dev) {
if (atomic_read(&usb_chip[i]->shutdown)) {
dev_err(&dev->dev, "USB device is in the shutdown state, cannot create a card instance\n");
err = -EIO;
goto __error;
}
chip = usb_chip[i];
atomic_inc(&chip->active); /* avoid autopm */
break;
}
}
if (! chip) {
/* it's a fresh one.
* now look for an empty slot and create a new card instance
*/
for (i = 0; i < SNDRV_CARDS; i++)
if (!usb_chip[i] &&
(vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&
(pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {
if (enable[i]) {
err = snd_usb_audio_create(intf, dev, i, quirk,
id, &chip);
if (err < 0)
goto __error;
chip->pm_intf = intf;
break;
} else if (vid[i] != -1 || pid[i] != -1) {
dev_info(&dev->dev,
"device (%04x:%04x) is disabled\n",
USB_ID_VENDOR(id),
USB_ID_PRODUCT(id));
err = -ENOENT;
goto __error;
}
}
if (!chip) {
dev_err(&dev->dev, "no available usb audio device\n");
err = -ENODEV;
goto __error;
}
}
dev_set_drvdata(&dev->dev, chip);
/*
* For devices with more than one control interface, we assume the
* first contains the audio controls. We might need a more specific
* check here in the future.
*/
if (!chip->ctrl_intf)
chip->ctrl_intf = alts;
chip->txfr_quirk = 0;
err = 1; /* continue */
if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {
/* need some special handlings */
err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);
if (err < 0)
goto __error;
}
if (err > 0) {
/* create normal USB audio interfaces */
err = snd_usb_create_streams(chip, ifnum);
if (err < 0)
goto __error;
err = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error);
if (err < 0)
goto __error;
}
/* we are allowed to call snd_card_register() many times */
err = snd_card_register(chip->card);
if (err < 0)
goto __error;
usb_chip[chip->index] = chip;
chip->num_interfaces++;
usb_set_intfdata(intf, chip);
atomic_dec(&chip->active);
mutex_unlock(®ister_mutex);
return 0;
__error:
if (chip) {
if (!chip->num_interfaces)
snd_card_free(chip->card);
atomic_dec(&chip->active);
}
mutex_unlock(®ister_mutex);
return err;
}
Commit Message: ALSA: usb-audio: Fix UAF decrement if card has no live interfaces in card.c
If a USB sound card reports 0 interfaces, an error condition is triggered
and the function usb_audio_probe errors out. In the error path, there was a
use-after-free vulnerability where the memory object of the card was first
freed, followed by a decrement of the number of active chips. Moving the
decrement above the atomic_dec fixes the UAF.
[ The original problem was introduced in 3.1 kernel, while it was
developed in a different form. The Fixes tag below indicates the
original commit but it doesn't mean that the patch is applicable
cleanly. -- tiwai ]
Fixes: 362e4e49abe5 ("ALSA: usb-audio - clear chip->probing on error exit")
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Mathias Payer <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416 | static int usb_audio_probe(struct usb_interface *intf,
const struct usb_device_id *usb_id)
{
struct usb_device *dev = interface_to_usbdev(intf);
const struct snd_usb_audio_quirk *quirk =
(const struct snd_usb_audio_quirk *)usb_id->driver_info;
struct snd_usb_audio *chip;
int i, err;
struct usb_host_interface *alts;
int ifnum;
u32 id;
alts = &intf->altsetting[0];
ifnum = get_iface_desc(alts)->bInterfaceNumber;
id = USB_ID(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (get_alias_id(dev, &id))
quirk = get_alias_quirk(dev, id);
if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)
return -ENXIO;
err = snd_usb_apply_boot_quirk(dev, intf, quirk, id);
if (err < 0)
return err;
/*
* found a config. now register to ALSA
*/
/* check whether it's already registered */
chip = NULL;
mutex_lock(®ister_mutex);
for (i = 0; i < SNDRV_CARDS; i++) {
if (usb_chip[i] && usb_chip[i]->dev == dev) {
if (atomic_read(&usb_chip[i]->shutdown)) {
dev_err(&dev->dev, "USB device is in the shutdown state, cannot create a card instance\n");
err = -EIO;
goto __error;
}
chip = usb_chip[i];
atomic_inc(&chip->active); /* avoid autopm */
break;
}
}
if (! chip) {
/* it's a fresh one.
* now look for an empty slot and create a new card instance
*/
for (i = 0; i < SNDRV_CARDS; i++)
if (!usb_chip[i] &&
(vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&
(pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {
if (enable[i]) {
err = snd_usb_audio_create(intf, dev, i, quirk,
id, &chip);
if (err < 0)
goto __error;
chip->pm_intf = intf;
break;
} else if (vid[i] != -1 || pid[i] != -1) {
dev_info(&dev->dev,
"device (%04x:%04x) is disabled\n",
USB_ID_VENDOR(id),
USB_ID_PRODUCT(id));
err = -ENOENT;
goto __error;
}
}
if (!chip) {
dev_err(&dev->dev, "no available usb audio device\n");
err = -ENODEV;
goto __error;
}
}
dev_set_drvdata(&dev->dev, chip);
/*
* For devices with more than one control interface, we assume the
* first contains the audio controls. We might need a more specific
* check here in the future.
*/
if (!chip->ctrl_intf)
chip->ctrl_intf = alts;
chip->txfr_quirk = 0;
err = 1; /* continue */
if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {
/* need some special handlings */
err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);
if (err < 0)
goto __error;
}
if (err > 0) {
/* create normal USB audio interfaces */
err = snd_usb_create_streams(chip, ifnum);
if (err < 0)
goto __error;
err = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error);
if (err < 0)
goto __error;
}
/* we are allowed to call snd_card_register() many times */
err = snd_card_register(chip->card);
if (err < 0)
goto __error;
usb_chip[chip->index] = chip;
chip->num_interfaces++;
usb_set_intfdata(intf, chip);
atomic_dec(&chip->active);
mutex_unlock(®ister_mutex);
return 0;
__error:
if (chip) {
/* chip->active is inside the chip->card object,
* decrement before memory is possibly returned.
*/
atomic_dec(&chip->active);
if (!chip->num_interfaces)
snd_card_free(chip->card);
}
mutex_unlock(®ister_mutex);
return err;
}
| 168,973 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void sycc420_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
const int *y, *cb, *cr, *ny;
unsigned int maxw, maxh, max;
int offset, upb;
unsigned int i, j;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * (size_t)max);
d1 = g = (int*)malloc(sizeof(int) * (size_t)max);
d2 = b = (int*)malloc(sizeof(int) * (size_t)max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i=0U; i < (maxh & ~(unsigned int)1U); i += 2U)
{
ny = y + maxw;
nr = r + maxw; ng = g + maxw; nb = b + maxw;
for(j=0; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
y += maxw; r += maxw; g += maxw; b += maxw;
}
if(i < maxh)
{
for(j=0U; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
#if defined(USE_JPWL) || defined(USE_MJ2)
img->comps[1].w = maxw; img->comps[1].h = maxh;
img->comps[2].w = maxw; img->comps[2].h = maxh;
#else
img->comps[1].w = (OPJ_UINT32)maxw; img->comps[1].h = (OPJ_UINT32)maxh;
img->comps[2].w = (OPJ_UINT32)maxw; img->comps[2].h = (OPJ_UINT32)maxh;
#endif
img->comps[1].dx = img->comps[0].dx;
img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[0].dy;
img->comps[2].dy = img->comps[0].dy;
return;
fails:
if(r) free(r);
if(g) free(g);
if(b) free(b);
}/* sycc420_to_rgb() */
Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745)
42x Images with an odd x0/y0 lead to subsampled component starting at the
2nd column/line.
That is offset = comp->dx * comp->x0 - image->x0 = 1
Fix #726
CWE ID: CWE-125 | static void sycc420_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
const int *y, *cb, *cr, *ny;
size_t maxw, maxh, max, offx, loopmaxw, offy, loopmaxh;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * max);
d1 = g = (int*)malloc(sizeof(int) * max);
d2 = b = (int*)malloc(sizeof(int) * max);
if (r == NULL || g == NULL || b == NULL) goto fails;
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
/* if img->y0 is odd, then first line shall use Cb/Cr = 0 */
offy = img->y0 & 1U;
loopmaxh = maxh - offy;
if (offy > 0U) {
size_t j;
for(j=0; j < maxw; ++j)
{
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
}
}
for(i=0U; i < (loopmaxh & ~(size_t)1U); i += 2U)
{
size_t j;
ny = y + maxw;
nr = r + maxw; ng = g + maxw; nb = b + maxw;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
}
for(j=0; j < (loopmaxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
if(j < loopmaxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
y += maxw; r += maxw; g += maxw; b += maxw;
}
if(i < loopmaxh)
{
size_t j;
for(j=0U; j < (maxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
free(r);
free(g);
free(b);
}/* sycc420_to_rgb() */
| 168,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)
{
rdpCredssp* credssp;
credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp));
ZeroMemory(credssp, sizeof(rdpCredssp));
if (credssp != NULL)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
credssp->instance = instance;
credssp->settings = settings;
credssp->server = settings->ServerMode;
credssp->transport = transport;
credssp->send_seq_num = 0;
credssp->recv_seq_num = 0;
ZeroMemory(&credssp->negoToken, sizeof(SecBuffer));
ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));
ZeroMemory(&credssp->authInfo, sizeof(SecBuffer));
if (credssp->server)
{
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"),
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize);
if (status == ERROR_SUCCESS)
{
credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType,
(BYTE*) credssp->SspiModule, &dwSize);
if (status == ERROR_SUCCESS)
{
_tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule);
RegCloseKey(hKey);
}
}
}
}
}
return credssp;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)
{
rdpCredssp* credssp;
credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp));
ZeroMemory(credssp, sizeof(rdpCredssp));
if (credssp != NULL)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
credssp->instance = instance;
credssp->settings = settings;
credssp->server = settings->ServerMode;
credssp->transport = transport;
credssp->send_seq_num = 0;
credssp->recv_seq_num = 0;
ZeroMemory(&credssp->negoToken, sizeof(SecBuffer));
ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));
ZeroMemory(&credssp->authInfo, sizeof(SecBuffer));
SecInvalidateHandle(&credssp->context);
if (credssp->server)
{
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"),
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize);
if (status == ERROR_SUCCESS)
{
credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType,
(BYTE*) credssp->SspiModule, &dwSize);
if (status == ERROR_SUCCESS)
{
_tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule);
RegCloseKey(hKey);
}
}
}
}
}
return credssp;
}
| 167,599 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowCUTReaderException(severity,tag) \
{ \
if (palette != NULL) \
palette=DestroyImage(palette); \
if (clone_info != NULL) \
clone_info=DestroyImageInfo(clone_info); \
ThrowReaderException(severity,tag); \
}
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
PixelPacket *q;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
NoMemory:
ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
{
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(depth,BImgBuff,i,image);
}
(void) SyncImage(image);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
if(GetCutColors(image)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(q) == ScaleCharToQuantum(1))
{
SetPixelRed(q,QuantumRange);
SetPixelGreen(q,QuantumRange);
SetPixelBlue(q,QuantumRange);
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1599
CWE ID: CWE-20 | static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowCUTReaderException(severity,tag) \
{ \
if (palette != NULL) \
palette=DestroyImage(palette); \
if (clone_info != NULL) \
clone_info=DestroyImageInfo(clone_info); \
ThrowReaderException(severity,tag); \
}
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
PixelPacket *q;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
NoMemory:
ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
(void) memset(BImgBuff,0,(size_t) ldblk*sizeof(*BImgBuff));
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
{
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(depth,BImgBuff,i,image);
}
(void) SyncImage(image);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
if(GetCutColors(image)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(q) == ScaleCharToQuantum(1))
{
SetPixelRed(q,QuantumRange);
SetPixelGreen(q,QuantumRange);
SetPixelBlue(q,QuantumRange);
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 170,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void unix_inflight(struct file *fp)
{
struct sock *s = unix_get_socket(fp);
spin_lock(&unix_gc_lock);
if (s) {
struct unix_sock *u = unix_sk(s);
if (atomic_long_inc_return(&u->inflight) == 1) {
BUG_ON(!list_empty(&u->link));
list_add_tail(&u->link, &gc_inflight_list);
} else {
BUG_ON(list_empty(&u->link));
}
unix_tot_inflight++;
}
fp->f_cred->user->unix_inflight++;
spin_unlock(&unix_gc_lock);
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | void unix_inflight(struct file *fp)
void unix_inflight(struct user_struct *user, struct file *fp)
{
struct sock *s = unix_get_socket(fp);
spin_lock(&unix_gc_lock);
if (s) {
struct unix_sock *u = unix_sk(s);
if (atomic_long_inc_return(&u->inflight) == 1) {
BUG_ON(!list_empty(&u->link));
list_add_tail(&u->link, &gc_inflight_list);
} else {
BUG_ON(list_empty(&u->link));
}
unix_tot_inflight++;
}
user->unix_inflight++;
spin_unlock(&unix_gc_lock);
}
| 167,396 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.