instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AudioParameters GetInputParametersOnDeviceThread(AudioManager* audio_manager,
const std::string& device_id) {
DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread());
if (!audio_manager->HasAudioInputDevices())
return AudioParameters();
return audio_manager->GetInputStreamParameters(device_id);
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | AudioParameters GetInputParametersOnDeviceThread(AudioManager* audio_manager,
const std::string& device_id) {
DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread());
// returns invalid parameters if the device is not found.
if (!audio_manager->HasAudioInputDevices())
return AudioParameters();
return audio_manager->GetInputStreamParameters(device_id);
}
| 171,988 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_attr_shortform_to_leaf(
struct xfs_da_args *args,
struct xfs_buf **leaf_bp)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == -EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
error = xfs_da_shrink_inode(args, 0, bp);
bp = NULL;
if (error)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.geo = args->geo;
nargs.firstblock = args->firstblock;
nargs.dfops = args->dfops;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == -ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != -ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
*leaf_bp = bp;
out:
kmem_free(tmpbuffer);
return error;
}
Commit Message: xfs: don't call xfs_da_shrink_inode with NULL bp
xfs_attr3_leaf_create may have errored out before instantiating a buffer,
for example if the blkno is out of range. In that case there is no work
to do to remove it, and in fact xfs_da_shrink_inode will lead to an oops
if we try.
This also seems to fix a flaw where the original error from
xfs_attr3_leaf_create gets overwritten in the cleanup case, and it
removes a pointless assignment to bp which isn't used after this.
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199969
Reported-by: Xu, Wen <[email protected]>
Tested-by: Xu, Wen <[email protected]>
Signed-off-by: Eric Sandeen <[email protected]>
Reviewed-by: Darrick J. Wong <[email protected]>
Signed-off-by: Darrick J. Wong <[email protected]>
CWE ID: CWE-476 | xfs_attr_shortform_to_leaf(
struct xfs_da_args *args,
struct xfs_buf **leaf_bp)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == -EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
/* xfs_attr3_leaf_create may not have instantiated a block */
if (bp && (xfs_da_shrink_inode(args, 0, bp) != 0))
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.geo = args->geo;
nargs.firstblock = args->firstblock;
nargs.dfops = args->dfops;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == -ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != -ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
*leaf_bp = bp;
out:
kmem_free(tmpbuffer);
return error;
}
| 169,164 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ProcessControlLaunched() {
base::ScopedAllowBlockingForTesting allow_blocking;
base::ProcessId service_pid;
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
#if defined(OS_WIN)
service_process_ =
base::Process::OpenWithAccess(service_pid,
SYNCHRONIZE | PROCESS_QUERY_INFORMATION);
#else
service_process_ = base::Process::Open(service_pid);
#endif
EXPECT_TRUE(service_process_.IsValid());
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
}
Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated().
Bug: 844016
Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0
Reviewed-on: https://chromium-review.googlesource.com/1126576
Commit-Queue: Wez <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573131}
CWE ID: CWE-94 | void ProcessControlLaunched() {
void ProcessControlLaunched(base::OnceClosure on_done) {
base::ScopedAllowBlockingForTesting allow_blocking;
base::ProcessId service_pid;
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
#if defined(OS_WIN)
service_process_ =
base::Process::OpenWithAccess(service_pid,
SYNCHRONIZE | PROCESS_QUERY_INFORMATION);
#else
service_process_ = base::Process::Open(service_pid);
#endif
EXPECT_TRUE(service_process_.IsValid());
std::move(on_done).Run();
}
| 172,053 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
| 167,789 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len)
{
if (src == NULL || src_len == 0) {
return -1;
}
size_t ret = 0;
const char16_t* const end = src + src_len;
while (src < end) {
if ((*src & 0xFC00) == 0xD800 && (src + 1) < end
&& (*++src & 0xFC00) == 0xDC00) {
ret += 4;
src++;
} else {
ret += utf32_codepoint_utf8_length((char32_t) *src++);
}
}
return ret;
}
Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8
Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length
is causing a heap overflow.
Correcting the length computation and adding bound checks to the
conversion functions.
Test: ran libutils_tests
Bug: 29250543
Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb
(cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1)
CWE ID: CWE-119 | ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len)
{
if (src == NULL || src_len == 0) {
return -1;
}
size_t ret = 0;
const char16_t* const end = src + src_len;
while (src < end) {
if ((*src & 0xFC00) == 0xD800 && (src + 1) < end
&& (*(src + 1) & 0xFC00) == 0xDC00) {
ret += 4;
src += 2;
} else {
ret += utf32_codepoint_utf8_length((char32_t) *src++);
}
}
return ret;
}
| 173,420 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MirrorMockJobInterceptor(const base::FilePath& root_http,
ReportResponseHeadersOnUI report_on_ui)
: root_http_(root_http), report_on_ui_(report_on_ui) {}
Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service.
The functionality worked, as part of converting DICE, however the test code didn't work since it
depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to
better match production, which removes the dependency on net/.
Also:
-make GetFilePathWithReplacements replace strings in the mock headers if they're present
-add a global to google_util to ignore ports; that way other tests can be converted without having
to modify each callsite to google_util
Bug: 881976
Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058
Reviewed-on: https://chromium-review.googlesource.com/c/1328142
Commit-Queue: John Abd-El-Malek <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652}
CWE ID: | MirrorMockJobInterceptor(const base::FilePath& root_http,
| 172,577 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Strgrow(Str x)
{
char *old = x->ptr;
int newlen;
newlen = x->length * 6 / 5;
if (newlen == x->length)
newlen += 2;
x->ptr = GC_MALLOC_ATOMIC(newlen);
x->area_size = newlen;
bcopy((void *)old, (void *)x->ptr, x->length);
GC_free(old);
}
Commit Message: Merge pull request #27 from kcwu/fix-strgrow
Fix potential heap buffer corruption due to Strgrow
CWE ID: CWE-119 | Strgrow(Str x)
{
char *old = x->ptr;
int newlen;
newlen = x->area_size * 6 / 5;
if (newlen == x->area_size)
newlen += 2;
x->ptr = GC_MALLOC_ATOMIC(newlen);
x->area_size = newlen;
bcopy((void *)old, (void *)x->ptr, x->length);
GC_free(old);
}
| 166,892 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderViewTest::SetUp() {
if (!GetContentClient()->renderer())
GetContentClient()->set_renderer(&mock_content_renderer_client_);
if (!render_thread_.get())
render_thread_.reset(new MockRenderThread());
render_thread_->set_routing_id(kRouteId);
render_thread_->set_surface_id(kSurfaceId);
render_thread_->set_new_window_routing_id(kNewWindowRouteId);
command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM));
params_.reset(new content::MainFunctionParams(*command_line_));
platform_.reset(new RendererMainPlatformDelegate(*params_));
platform_->PlatformInitialize();
webkit_glue::SetJavaScriptFlags(" --expose-gc");
WebKit::initialize(&webkit_platform_support_);
mock_process_.reset(new MockRenderProcess);
RenderViewImpl* view = RenderViewImpl::Create(
0,
kOpenerId,
content::RendererPreferences(),
WebPreferences(),
new SharedRenderViewCounter(0),
kRouteId,
kSurfaceId,
kInvalidSessionStorageNamespaceId,
string16(),
1,
WebKit::WebScreenInfo(),
false);
view->AddRef();
view_ = view;
mock_keyboard_.reset(new MockKeyboard());
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderViewTest::SetUp() {
if (!GetContentClient()->renderer())
GetContentClient()->set_renderer(&mock_content_renderer_client_);
if (!render_thread_.get())
render_thread_.reset(new MockRenderThread());
render_thread_->set_routing_id(kRouteId);
render_thread_->set_surface_id(kSurfaceId);
render_thread_->set_new_window_routing_id(kNewWindowRouteId);
command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM));
params_.reset(new content::MainFunctionParams(*command_line_));
platform_.reset(new RendererMainPlatformDelegate(*params_));
platform_->PlatformInitialize();
webkit_glue::SetJavaScriptFlags(" --expose-gc");
WebKit::initialize(&webkit_platform_support_);
// Ensure that we register any necessary schemes when initializing WebKit,
// since we are using a MockRenderThread.
RenderThreadImpl::RegisterSchemes();
mock_process_.reset(new MockRenderProcess);
RenderViewImpl* view = RenderViewImpl::Create(
0,
kOpenerId,
content::RendererPreferences(),
WebPreferences(),
new SharedRenderViewCounter(0),
kRouteId,
kSurfaceId,
kInvalidSessionStorageNamespaceId,
string16(),
1,
WebKit::WebScreenInfo(),
false);
view->AddRef();
view_ = view;
mock_keyboard_.reset(new MockKeyboard());
}
| 171,034 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Utterance::FinishAndDestroy() {
completion_task_->Run();
completion_task_ = NULL;
delete this;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void Utterance::FinishAndDestroy() {
| 170,377 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ltree_in(PG_FUNCTION_ARGS)
{
char *buf = (char *) PG_GETARG_POINTER(0);
char *ptr;
nodeitem *list,
*lptr;
int num = 0,
totallen = 0;
int state = LTPRS_WAITNAME;
ltree *result;
ltree_level *curlevel;
int charlen;
int pos = 0;
ptr = buf;
while (*ptr)
{
charlen = pg_mblen(ptr);
if (charlen == 1 && t_iseq(ptr, '.'))
num++;
ptr += charlen;
}
list = lptr = (nodeitem *) palloc(sizeof(nodeitem) * (num + 1));
ptr = buf;
while (*ptr)
{
charlen = pg_mblen(ptr);
if (state == LTPRS_WAITNAME)
{
if (ISALNUM(ptr))
{
lptr->start = ptr;
lptr->wlen = 0;
state = LTPRS_WAITDELIM;
}
else
UNCHAR;
}
else if (state == LTPRS_WAITDELIM)
{
if (charlen == 1 && t_iseq(ptr, '.'))
{
lptr->len = ptr - lptr->start;
if (lptr->wlen > 255)
ereport(ERROR,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("name of level is too long"),
errdetail("Name length is %d, must "
"be < 256, in position %d.",
lptr->wlen, pos)));
totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE);
lptr++;
state = LTPRS_WAITNAME;
}
else if (!ISALNUM(ptr))
UNCHAR;
}
else
/* internal error */
elog(ERROR, "internal error in parser");
ptr += charlen;
lptr->wlen++;
pos++;
}
if (state == LTPRS_WAITDELIM)
{
lptr->len = ptr - lptr->start;
if (lptr->wlen > 255)
ereport(ERROR,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("name of level is too long"),
errdetail("Name length is %d, must "
"be < 256, in position %d.",
lptr->wlen, pos)));
totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE);
lptr++;
}
else if (!(state == LTPRS_WAITNAME && lptr == list))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("syntax error"),
errdetail("Unexpected end of line.")));
result = (ltree *) palloc0(LTREE_HDRSIZE + totallen);
SET_VARSIZE(result, LTREE_HDRSIZE + totallen);
result->numlevel = lptr - list;
curlevel = LTREE_FIRST(result);
lptr = list;
while (lptr - list < result->numlevel)
{
curlevel->len = (uint16) lptr->len;
memcpy(curlevel->name, lptr->start, lptr->len);
curlevel = LEVEL_NEXT(curlevel);
lptr++;
}
pfree(list);
PG_RETURN_POINTER(result);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | ltree_in(PG_FUNCTION_ARGS)
{
char *buf = (char *) PG_GETARG_POINTER(0);
char *ptr;
nodeitem *list,
*lptr;
int num = 0,
totallen = 0;
int state = LTPRS_WAITNAME;
ltree *result;
ltree_level *curlevel;
int charlen;
int pos = 0;
ptr = buf;
while (*ptr)
{
charlen = pg_mblen(ptr);
if (charlen == 1 && t_iseq(ptr, '.'))
num++;
ptr += charlen;
}
if (num + 1 > MaxAllocSize / sizeof(nodeitem))
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of levels (%d) exceeds the maximum allowed (%d)",
num + 1, (int) (MaxAllocSize / sizeof(nodeitem)))));
list = lptr = (nodeitem *) palloc(sizeof(nodeitem) * (num + 1));
ptr = buf;
while (*ptr)
{
charlen = pg_mblen(ptr);
if (state == LTPRS_WAITNAME)
{
if (ISALNUM(ptr))
{
lptr->start = ptr;
lptr->wlen = 0;
state = LTPRS_WAITDELIM;
}
else
UNCHAR;
}
else if (state == LTPRS_WAITDELIM)
{
if (charlen == 1 && t_iseq(ptr, '.'))
{
lptr->len = ptr - lptr->start;
if (lptr->wlen > 255)
ereport(ERROR,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("name of level is too long"),
errdetail("Name length is %d, must "
"be < 256, in position %d.",
lptr->wlen, pos)));
totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE);
lptr++;
state = LTPRS_WAITNAME;
}
else if (!ISALNUM(ptr))
UNCHAR;
}
else
/* internal error */
elog(ERROR, "internal error in parser");
ptr += charlen;
lptr->wlen++;
pos++;
}
if (state == LTPRS_WAITDELIM)
{
lptr->len = ptr - lptr->start;
if (lptr->wlen > 255)
ereport(ERROR,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("name of level is too long"),
errdetail("Name length is %d, must "
"be < 256, in position %d.",
lptr->wlen, pos)));
totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE);
lptr++;
}
else if (!(state == LTPRS_WAITNAME && lptr == list))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("syntax error"),
errdetail("Unexpected end of line.")));
result = (ltree *) palloc0(LTREE_HDRSIZE + totallen);
SET_VARSIZE(result, LTREE_HDRSIZE + totallen);
result->numlevel = lptr - list;
curlevel = LTREE_FIRST(result);
lptr = list;
while (lptr - list < result->numlevel)
{
curlevel->len = (uint16) lptr->len;
memcpy(curlevel->name, lptr->start, lptr->len);
curlevel = LEVEL_NEXT(curlevel);
lptr++;
}
pfree(list);
PG_RETURN_POINTER(result);
}
| 166,405 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GDataFile* AddFile(GDataDirectory* parent,
GDataDirectoryService* directory_service,
int sequence_id) {
GDataFile* file = new GDataFile(NULL, directory_service);
const std::string title = "file" + base::IntToString(sequence_id);
const std::string resource_id = std::string("file_resource_id:") +
title;
file->set_title(title);
file->set_resource_id(resource_id);
file->set_file_md5(std::string("file_md5:") + title);
GDataFileError error = GDATA_FILE_ERROR_FAILED;
FilePath moved_file_path;
directory_service->MoveEntryToDirectory(
parent->GetFilePath(),
file,
base::Bind(&test_util::CopyResultsFromFileMoveCallback,
&error,
&moved_file_path));
test_util::RunBlockingPoolTask();
EXPECT_EQ(GDATA_FILE_OK, error);
EXPECT_EQ(parent->GetFilePath().AppendASCII(title), moved_file_path);
return file;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | GDataFile* AddFile(GDataDirectory* parent,
GDataDirectoryService* directory_service,
int sequence_id) {
GDataFile* file = directory_service->CreateGDataFile();
const std::string title = "file" + base::IntToString(sequence_id);
const std::string resource_id = std::string("file_resource_id:") +
title;
file->set_title(title);
file->set_resource_id(resource_id);
file->set_file_md5(std::string("file_md5:") + title);
GDataFileError error = GDATA_FILE_ERROR_FAILED;
FilePath moved_file_path;
directory_service->MoveEntryToDirectory(
parent->GetFilePath(),
file,
base::Bind(&test_util::CopyResultsFromFileMoveCallback,
&error,
&moved_file_path));
test_util::RunBlockingPoolTask();
EXPECT_EQ(GDATA_FILE_OK, error);
EXPECT_EQ(parent->GetFilePath().AppendASCII(title), moved_file_path);
return file;
}
| 171,495 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
{
AVFilterContext *ctx = inlink->dst;
FieldOrderContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
int h, plane, line_step, line_size, line;
uint8_t *data;
if (!frame->interlaced_frame ||
frame->top_field_first == s->dst_tff)
return ff_filter_frame(outlink, frame);
av_dlog(ctx,
"picture will move %s one line\n",
s->dst_tff ? "up" : "down");
h = frame->height;
for (plane = 0; plane < 4 && frame->data[plane]; plane++) {
line_step = frame->linesize[plane];
line_size = s->line_size[plane];
data = frame->data[plane];
if (s->dst_tff) {
/** Move every line up one line, working from
* the top to the bottom of the frame.
* The original top line is lost.
* The new last line is created as a copy of the
* penultimate line from that field. */
for (line = 0; line < h; line++) {
if (1 + line < frame->height) {
memcpy(data, data + line_step, line_size);
} else {
memcpy(data, data - line_step - line_step, line_size);
}
data += line_step;
}
} else {
/** Move every line down one line, working from
* the bottom to the top of the frame.
* The original bottom line is lost.
* The new first line is created as a copy of the
* second line from that field. */
data += (h - 1) * line_step;
for (line = h - 1; line >= 0 ; line--) {
if (line > 0) {
memcpy(data, data - line_step, line_size);
} else {
memcpy(data, data + line_step + line_step, line_size);
}
data -= line_step;
}
}
}
frame->top_field_first = s->dst_tff;
return ff_filter_frame(outlink, frame);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
{
AVFilterContext *ctx = inlink->dst;
FieldOrderContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
int h, plane, line_step, line_size, line;
uint8_t *data;
if (!frame->interlaced_frame ||
frame->top_field_first == s->dst_tff)
return ff_filter_frame(outlink, frame);
av_dlog(ctx,
"picture will move %s one line\n",
s->dst_tff ? "up" : "down");
h = frame->height;
for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) {
line_step = frame->linesize[plane];
line_size = s->line_size[plane];
data = frame->data[plane];
if (s->dst_tff) {
/** Move every line up one line, working from
* the top to the bottom of the frame.
* The original top line is lost.
* The new last line is created as a copy of the
* penultimate line from that field. */
for (line = 0; line < h; line++) {
if (1 + line < frame->height) {
memcpy(data, data + line_step, line_size);
} else {
memcpy(data, data - line_step - line_step, line_size);
}
data += line_step;
}
} else {
/** Move every line down one line, working from
* the bottom to the top of the frame.
* The original bottom line is lost.
* The new first line is created as a copy of the
* second line from that field. */
data += (h - 1) * line_step;
for (line = h - 1; line >= 0 ; line--) {
if (line > 0) {
memcpy(data, data - line_step, line_size);
} else {
memcpy(data, data + line_step + line_step, line_size);
}
data -= line_step;
}
}
}
frame->top_field_first = s->dst_tff;
return ff_filter_frame(outlink, frame);
}
| 166,000 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t fuse_fill_write_pages(struct fuse_req *req,
struct address_space *mapping,
struct iov_iter *ii, loff_t pos)
{
struct fuse_conn *fc = get_fuse_conn(mapping->host);
unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
size_t count = 0;
int err;
req->in.argpages = 1;
req->page_descs[0].offset = offset;
do {
size_t tmp;
struct page *page;
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
size_t bytes = min_t(size_t, PAGE_CACHE_SIZE - offset,
iov_iter_count(ii));
bytes = min_t(size_t, bytes, fc->max_write - count);
again:
err = -EFAULT;
if (iov_iter_fault_in_readable(ii, bytes))
break;
err = -ENOMEM;
page = grab_cache_page_write_begin(mapping, index, 0);
if (!page)
break;
if (mapping_writably_mapped(mapping))
flush_dcache_page(page);
tmp = iov_iter_copy_from_user_atomic(page, ii, offset, bytes);
flush_dcache_page(page);
if (!tmp) {
unlock_page(page);
page_cache_release(page);
bytes = min(bytes, iov_iter_single_seg_count(ii));
goto again;
}
err = 0;
req->pages[req->num_pages] = page;
req->page_descs[req->num_pages].length = tmp;
req->num_pages++;
iov_iter_advance(ii, tmp);
count += tmp;
pos += tmp;
offset += tmp;
if (offset == PAGE_CACHE_SIZE)
offset = 0;
if (!fc->big_writes)
break;
} while (iov_iter_count(ii) && count < fc->max_write &&
req->num_pages < req->max_pages && offset == 0);
return count > 0 ? count : err;
}
Commit Message: fuse: break infinite loop in fuse_fill_write_pages()
I got a report about unkillable task eating CPU. Further
investigation shows, that the problem is in the fuse_fill_write_pages()
function. If iov's first segment has zero length, we get an infinite
loop, because we never reach iov_iter_advance() call.
Fix this by calling iov_iter_advance() before repeating an attempt to
copy data from userspace.
A similar problem is described in 124d3b7041f ("fix writev regression:
pan hanging unkillable and un-straceable"). If zero-length segmend
is followed by segment with invalid address,
iov_iter_fault_in_readable() checks only first segment (zero-length),
iov_iter_copy_from_user_atomic() skips it, fails at second and
returns zero -> goto again without skipping zero-length segment.
Patch calls iov_iter_advance() before goto again: we'll skip zero-length
segment at second iteraction and iov_iter_fault_in_readable() will detect
invalid address.
Special thanks to Konstantin Khlebnikov, who helped a lot with the commit
description.
Cc: Andrew Morton <[email protected]>
Cc: Maxim Patlasov <[email protected]>
Cc: Konstantin Khlebnikov <[email protected]>
Signed-off-by: Roman Gushchin <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
Fixes: ea9b9907b82a ("fuse: implement perform_write")
Cc: <[email protected]>
CWE ID: CWE-399 | static ssize_t fuse_fill_write_pages(struct fuse_req *req,
struct address_space *mapping,
struct iov_iter *ii, loff_t pos)
{
struct fuse_conn *fc = get_fuse_conn(mapping->host);
unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
size_t count = 0;
int err;
req->in.argpages = 1;
req->page_descs[0].offset = offset;
do {
size_t tmp;
struct page *page;
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
size_t bytes = min_t(size_t, PAGE_CACHE_SIZE - offset,
iov_iter_count(ii));
bytes = min_t(size_t, bytes, fc->max_write - count);
again:
err = -EFAULT;
if (iov_iter_fault_in_readable(ii, bytes))
break;
err = -ENOMEM;
page = grab_cache_page_write_begin(mapping, index, 0);
if (!page)
break;
if (mapping_writably_mapped(mapping))
flush_dcache_page(page);
tmp = iov_iter_copy_from_user_atomic(page, ii, offset, bytes);
flush_dcache_page(page);
iov_iter_advance(ii, tmp);
if (!tmp) {
unlock_page(page);
page_cache_release(page);
bytes = min(bytes, iov_iter_single_seg_count(ii));
goto again;
}
err = 0;
req->pages[req->num_pages] = page;
req->page_descs[req->num_pages].length = tmp;
req->num_pages++;
count += tmp;
pos += tmp;
offset += tmp;
if (offset == PAGE_CACHE_SIZE)
offset = 0;
if (!fc->big_writes)
break;
} while (iov_iter_count(ii) && count < fc->max_write &&
req->num_pages < req->max_pages && offset == 0);
return count > 0 ? count : err;
}
| 167,498 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PaintImage AcceleratedStaticBitmapImage::PaintImageForCurrentFrame() {
CheckThread();
if (!IsValid())
return PaintImage();
sk_sp<SkImage> image;
if (original_skia_image_ &&
original_skia_image_thread_id_ ==
Platform::Current()->CurrentThread()->ThreadId()) {
image = original_skia_image_;
} else {
CreateImageFromMailboxIfNeeded();
image = texture_holder_->GetSkImage();
}
return CreatePaintImageBuilder()
.set_image(image, paint_image_content_id_)
.set_completion_state(PaintImage::CompletionState::DONE)
.TakePaintImage();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | PaintImage AcceleratedStaticBitmapImage::PaintImageForCurrentFrame() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!IsValid())
return PaintImage();
sk_sp<SkImage> image;
if (original_skia_image_ &&
original_skia_image_task_runner_->BelongsToCurrentThread()) {
image = original_skia_image_;
} else {
CreateImageFromMailboxIfNeeded();
image = texture_holder_->GetSkImage();
}
return CreatePaintImageBuilder()
.set_image(image, paint_image_content_id_)
.set_completion_state(PaintImage::CompletionState::DONE)
.TakePaintImage();
}
| 172,596 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void user_login(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr) {
struct mt_packet pdata;
unsigned char md5sum[17];
char md5data[100];
struct mt_credentials *user;
char *slavename;
/* Reparse user file before each login */
read_userfile();
if ((user = find_user(curconn->username)) != NULL) {
md5_state_t state;
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(md5data, sizeof(md5data));
mlock(md5sum, sizeof(md5sum));
if (user->password != NULL) {
mlock(user->password, strlen(user->password));
}
#endif
/* Concat string of 0 + password + pass_salt */
md5data[0] = 0;
strncpy(md5data + 1, user->password, 82);
memcpy(md5data + 1 + strlen(user->password), curconn->pass_salt, 16);
/* Generate md5 sum of md5data with a leading 0 */
md5_init(&state);
md5_append(&state, (const md5_byte_t *)md5data, strlen(user->password) + 17);
md5_finish(&state, (md5_byte_t *)md5sum + 1);
md5sum[0] = 0;
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
curconn->outcounter += add_control_packet(&pdata, MT_CPTYPE_END_AUTH, NULL, 0);
send_udp(curconn, &pdata);
if (curconn->state == STATE_ACTIVE) {
return;
}
}
if (user == NULL || memcmp(md5sum, curconn->trypassword, 17) != 0) {
syslog(LOG_NOTICE, _("(%d) Invalid login by %s."), curconn->seskey, curconn->username);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Login failed, incorrect username or password\r\n"));
/* TODO: should wait some time (not with sleep) before returning, to minimalize brute force attacks */
return;
}
/* User is logged in */
curconn->state = STATE_ACTIVE;
/* Enter terminal mode */
curconn->terminal_mode = 1;
/* Open pts handle */
curconn->ptsfd = posix_openpt(O_RDWR);
if (curconn->ptsfd == -1 || grantpt(curconn->ptsfd) == -1 || unlockpt(curconn->ptsfd) == -1) {
syslog(LOG_ERR, "posix_openpt: %s", strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Terminal error\r\n"));
return;
}
/* Get file path for our pts */
slavename = ptsname(curconn->ptsfd);
if (slavename != NULL) {
pid_t pid;
struct stat sb;
struct passwd *user = (struct passwd *)malloc(sizeof(struct passwd));
struct passwd *tmpuser=user;
char *buffer = malloc(1024);
if (user == NULL || buffer == NULL) {
syslog(LOG_CRIT, _("(%d) Error allocating memory."), curconn->seskey);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("System error, out of memory\r\n"));
return;
}
if (getpwnam_r(curconn->username, user, buffer, 1024, &tmpuser) != 0) {
syslog(LOG_WARNING, _("(%d) Login ok, but local user not accessible (%s)."), curconn->seskey, curconn->username);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Local user not accessible\r\n"));
free(user);
free(buffer);
return;
}
/* Change the owner of the slave pts */
chown(slavename, user->pw_uid, user->pw_gid);
curconn->slavefd = open(slavename, O_RDWR);
if (curconn->slavefd == -1) {
syslog(LOG_ERR, _("Error opening %s: %s"), slavename, strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Error opening terminal\r\n"));
list_remove_connection(curconn);
return;
}
if ((pid = fork()) == 0) {
struct net_interface *interface;
/* Add login information to utmp/wtmp */
uwtmp_login(curconn);
syslog(LOG_INFO, _("(%d) User %s logged in."), curconn->seskey, curconn->username);
/* Initialize terminal environment */
setenv("USER", user->pw_name, 1);
setenv("HOME", user->pw_dir, 1);
setenv("SHELL", user->pw_shell, 1);
setenv("TERM", curconn->terminal_type, 1);
close(sockfd);
close(insockfd);
DL_FOREACH(interfaces, interface) {
if (interface->socketfd > 0) {
close(interface->socketfd);
}
}
setsid();
/* Don't let shell process inherit slavefd */
fcntl (curconn->slavefd, F_SETFD, FD_CLOEXEC);
close(curconn->ptsfd);
/* Redirect STDIN/STDIO/STDERR */
close(0);
dup(curconn->slavefd);
close(1);
dup(curconn->slavefd);
close(2);
dup(curconn->slavefd);
/* Set controlling terminal */
ioctl(0, TIOCSCTTY, 1);
tcsetpgrp(0, getpid());
/* Set user id/group id */
if ((setgid(user->pw_gid) != 0) || (setuid(user->pw_uid) != 0)) {
syslog(LOG_ERR, _("(%d) Could not log in %s (%d:%d): setuid/setgid: %s"), curconn->seskey, curconn->username, user->pw_uid, user->pw_gid, strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Internal error\r\n"));
exit(0);
}
/* Abort login if /etc/nologin exists */
if (stat(_PATH_NOLOGIN, &sb) == 0 && getuid() != 0) {
syslog(LOG_NOTICE, _("(%d) User %s disconnected with " _PATH_NOLOGIN " message."), curconn->seskey, curconn->username);
display_nologin();
curconn->state = STATE_CLOSED;
init_packet(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
send_udp(curconn, &pdata);
exit(0);
}
/* Display MOTD */
display_motd();
chdir(user->pw_dir);
/* Spawn shell */
/* TODO: Maybe use "login -f USER" instead? renders motd and executes shell correctly for system */
execl(user->pw_shell, user->pw_shell, "-", (char *) 0);
exit(0); // just to be sure.
}
free(user);
free(buffer);
close(curconn->slavefd);
curconn->pid = pid;
set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
}
}
Commit Message: Merge pull request #20 from eyalitki/master
2nd round security fixes from eyalitki
CWE ID: CWE-119 | static void user_login(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr) {
struct mt_packet pdata;
unsigned char md5sum[17];
char md5data[100];
struct mt_credentials *user;
char *slavename;
int act_pass_len;
/* Reparse user file before each login */
read_userfile();
if ((user = find_user(curconn->username)) != NULL) {
md5_state_t state;
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(md5data, sizeof(md5data));
mlock(md5sum, sizeof(md5sum));
if (user->password != NULL) {
mlock(user->password, strlen(user->password));
}
#endif
/* calculate the password's actual length */
act_pass_len = strlen(user->password);
act_pass_len = act_pass_len <= 82 ? act_pass_len : 82;
/* Concat string of 0 + password + pass_salt */
md5data[0] = 0;
memcpy(md5data + 1, user->password, act_pass_len);
memcpy(md5data + 1 + act_pass_len, curconn->pass_salt, 16);
/* Generate md5 sum of md5data with a leading 0 */
md5_init(&state);
md5_append(&state, (const md5_byte_t *)md5data, 1 + act_pass_len + 16);
md5_finish(&state, (md5_byte_t *)md5sum + 1);
md5sum[0] = 0;
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
curconn->outcounter += add_control_packet(&pdata, MT_CPTYPE_END_AUTH, NULL, 0);
send_udp(curconn, &pdata);
if (curconn->state == STATE_ACTIVE) {
return;
}
}
if (user == NULL || memcmp(md5sum, curconn->trypassword, 17) != 0) {
syslog(LOG_NOTICE, _("(%d) Invalid login by %s."), curconn->seskey, curconn->username);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Login failed, incorrect username or password\r\n"));
/* TODO: should wait some time (not with sleep) before returning, to minimalize brute force attacks */
return;
}
/* User is logged in */
curconn->state = STATE_ACTIVE;
/* Enter terminal mode */
curconn->terminal_mode = 1;
/* Open pts handle */
curconn->ptsfd = posix_openpt(O_RDWR);
if (curconn->ptsfd == -1 || grantpt(curconn->ptsfd) == -1 || unlockpt(curconn->ptsfd) == -1) {
syslog(LOG_ERR, "posix_openpt: %s", strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Terminal error\r\n"));
return;
}
/* Get file path for our pts */
slavename = ptsname(curconn->ptsfd);
if (slavename != NULL) {
pid_t pid;
struct stat sb;
struct passwd *user = (struct passwd *)malloc(sizeof(struct passwd));
struct passwd *tmpuser=user;
char *buffer = malloc(1024);
if (user == NULL || buffer == NULL) {
syslog(LOG_CRIT, _("(%d) Error allocating memory."), curconn->seskey);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("System error, out of memory\r\n"));
return;
}
if (getpwnam_r(curconn->username, user, buffer, 1024, &tmpuser) != 0) {
syslog(LOG_WARNING, _("(%d) Login ok, but local user not accessible (%s)."), curconn->seskey, curconn->username);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Local user not accessible\r\n"));
free(user);
free(buffer);
return;
}
/* Change the owner of the slave pts */
chown(slavename, user->pw_uid, user->pw_gid);
curconn->slavefd = open(slavename, O_RDWR);
if (curconn->slavefd == -1) {
syslog(LOG_ERR, _("Error opening %s: %s"), slavename, strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Error opening terminal\r\n"));
list_remove_connection(curconn);
return;
}
if ((pid = fork()) == 0) {
struct net_interface *interface;
/* Add login information to utmp/wtmp */
uwtmp_login(curconn);
syslog(LOG_INFO, _("(%d) User %s logged in."), curconn->seskey, curconn->username);
/* Initialize terminal environment */
setenv("USER", user->pw_name, 1);
setenv("HOME", user->pw_dir, 1);
setenv("SHELL", user->pw_shell, 1);
setenv("TERM", curconn->terminal_type, 1);
close(sockfd);
close(insockfd);
DL_FOREACH(interfaces, interface) {
if (interface->socketfd > 0) {
close(interface->socketfd);
}
}
setsid();
/* Don't let shell process inherit slavefd */
fcntl (curconn->slavefd, F_SETFD, FD_CLOEXEC);
close(curconn->ptsfd);
/* Redirect STDIN/STDIO/STDERR */
close(0);
dup(curconn->slavefd);
close(1);
dup(curconn->slavefd);
close(2);
dup(curconn->slavefd);
/* Set controlling terminal */
ioctl(0, TIOCSCTTY, 1);
tcsetpgrp(0, getpid());
/* Set user id/group id */
if ((setgid(user->pw_gid) != 0) || (setuid(user->pw_uid) != 0)) {
syslog(LOG_ERR, _("(%d) Could not log in %s (%d:%d): setuid/setgid: %s"), curconn->seskey, curconn->username, user->pw_uid, user->pw_gid, strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Internal error\r\n"));
exit(0);
}
/* Abort login if /etc/nologin exists */
if (stat(_PATH_NOLOGIN, &sb) == 0 && getuid() != 0) {
syslog(LOG_NOTICE, _("(%d) User %s disconnected with " _PATH_NOLOGIN " message."), curconn->seskey, curconn->username);
display_nologin();
curconn->state = STATE_CLOSED;
init_packet(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
send_udp(curconn, &pdata);
exit(0);
}
/* Display MOTD */
display_motd();
chdir(user->pw_dir);
/* Spawn shell */
/* TODO: Maybe use "login -f USER" instead? renders motd and executes shell correctly for system */
execl(user->pw_shell, user->pw_shell, "-", (char *) 0);
exit(0); // just to be sure.
}
free(user);
free(buffer);
close(curconn->slavefd);
curconn->pid = pid;
set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
}
}
| 166,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
int is_udp4;
bool slow;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len, addr_len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len, addr_len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_msg(skb, sizeof(struct udphdr),
msg, copied);
else {
err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
inet6_iif(skb));
}
*addr_len = sizeof(*sin6);
}
if (np->rxopt.all)
ip6_datagram_recv_common_ctl(sk, msg, skb);
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_specific_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
Commit Message: udp: fix behavior of wrong checksums
We have two problems in UDP stack related to bogus checksums :
1) We return -EAGAIN to application even if receive queue is not empty.
This breaks applications using edge trigger epoll()
2) Under UDP flood, we can loop forever without yielding to other
processes, potentially hanging the host, especially on non SMP.
This patch is an attempt to make things better.
We might in the future add extra support for rt applications
wanting to better control time spent doing a recv() in a hostile
environment. For example we could validate checksums before queuing
packets in socket receive queue.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
int is_udp4;
bool slow;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len, addr_len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len, addr_len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_msg(skb, sizeof(struct udphdr),
msg, copied);
else {
err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
inet6_iif(skb));
}
*addr_len = sizeof(*sin6);
}
if (np->rxopt.all)
ip6_datagram_recv_common_ctl(sk, msg, skb);
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_specific_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
/* starting over for a new packet, but check if we need to yield */
cond_resched();
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
| 166,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi,
HB_GPOS_SubTable* st,
HB_Buffer buffer,
HB_UShort flags,
HB_UShort context_length,
int nesting_level )
{
HB_UShort i, j, mark1_index, mark2_index, property, class;
HB_Fixed x_mark1_value, y_mark1_value,
x_mark2_value, y_mark2_value;
HB_Error error;
HB_GPOSHeader* gpos = gpi->gpos;
HB_MarkMarkPos* mmp = &st->markmark;
HB_MarkArray* ma1;
HB_Mark2Array* ma2;
HB_Mark2Record* m2r;
HB_Anchor* mark1_anchor;
HB_Anchor* mark2_anchor;
HB_Position o;
HB_UNUSED(nesting_level);
if ( context_length != 0xFFFF && context_length < 1 )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS )
return HB_Err_Not_Covered;
if ( CHECK_Property( gpos->gdef, IN_CURITEM(),
flags, &property ) )
return error;
error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(),
&mark1_index );
if ( error )
return error;
/* now we search backwards for a suitable mark glyph until a non-mark
glyph */
if ( buffer->in_pos == 0 )
return HB_Err_Not_Covered;
i = 1;
j = buffer->in_pos - 1;
while ( i <= buffer->in_pos )
{
error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ),
&property );
if ( error )
return error;
if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS )
{
if ( property == (flags & 0xFF00) )
break;
}
else
break;
i++;
j--;
}
error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ),
&mark2_index );
if ( error )
if ( mark1_index >= ma1->MarkCount )
return ERR(HB_Err_Invalid_SubTable);
class = ma1->MarkRecord[mark1_index].Class;
mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor;
if ( class >= mmp->ClassCount )
return ERR(HB_Err_Invalid_SubTable);
ma2 = &mmp->Mark2Array;
if ( mark2_index >= ma2->Mark2Count )
return ERR(HB_Err_Invalid_SubTable);
m2r = &ma2->Mark2Record[mark2_index];
mark2_anchor = &m2r->Mark2Anchor[class];
error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(),
&x_mark1_value, &y_mark1_value );
if ( error )
return error;
error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ),
&x_mark2_value, &y_mark2_value );
if ( error )
return error;
/* anchor points are not cumulative */
o = POSITION( buffer->in_pos );
o->x_pos = x_mark2_value - x_mark1_value;
o->y_pos = y_mark2_value - y_mark1_value;
o->x_advance = 0;
o->y_advance = 0;
o->back = 1;
(buffer->in_pos)++;
return HB_Err_Ok;
}
Commit Message:
CWE ID: CWE-119 | static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi,
HB_GPOS_SubTable* st,
HB_Buffer buffer,
HB_UShort flags,
HB_UShort context_length,
int nesting_level )
{
HB_UShort i, j, mark1_index, mark2_index, property, class;
HB_Fixed x_mark1_value, y_mark1_value,
x_mark2_value, y_mark2_value;
HB_Error error;
HB_GPOSHeader* gpos = gpi->gpos;
HB_MarkMarkPos* mmp = &st->markmark;
HB_MarkArray* ma1;
HB_Mark2Array* ma2;
HB_Mark2Record* m2r;
HB_Anchor* mark1_anchor;
HB_Anchor* mark2_anchor;
HB_Position o;
HB_UNUSED(nesting_level);
if ( context_length != 0xFFFF && context_length < 1 )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS )
return HB_Err_Not_Covered;
if ( CHECK_Property( gpos->gdef, IN_CURITEM(),
flags, &property ) )
return error;
error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(),
&mark1_index );
if ( error )
return error;
/* now we search backwards for a suitable mark glyph until a non-mark
glyph */
if ( buffer->in_pos == 0 )
return HB_Err_Not_Covered;
i = 1;
j = buffer->in_pos - 1;
while ( i <= buffer->in_pos )
{
error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ),
&property );
if ( error )
return error;
if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS )
{
if ( property == (flags & 0xFF00) )
break;
}
else
break;
i++;
j--;
}
if ( i > buffer->in_pos )
return HB_Err_Not_Covered;
error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ),
&mark2_index );
if ( error )
if ( mark1_index >= ma1->MarkCount )
return ERR(HB_Err_Invalid_SubTable);
class = ma1->MarkRecord[mark1_index].Class;
mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor;
if ( class >= mmp->ClassCount )
return ERR(HB_Err_Invalid_SubTable);
ma2 = &mmp->Mark2Array;
if ( mark2_index >= ma2->Mark2Count )
return ERR(HB_Err_Invalid_SubTable);
m2r = &ma2->Mark2Record[mark2_index];
mark2_anchor = &m2r->Mark2Anchor[class];
error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(),
&x_mark1_value, &y_mark1_value );
if ( error )
return error;
error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ),
&x_mark2_value, &y_mark2_value );
if ( error )
return error;
/* anchor points are not cumulative */
o = POSITION( buffer->in_pos );
o->x_pos = x_mark2_value - x_mark1_value;
o->y_pos = y_mark2_value - y_mark1_value;
o->x_advance = 0;
o->y_advance = 0;
o->back = 1;
(buffer->in_pos)++;
return HB_Err_Ok;
}
| 165,246 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ext4_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct inode *inode = mapping->host;
int ret, needed_blocks;
handle_t *handle;
int retries = 0;
struct page *page;
pgoff_t index;
unsigned from, to;
trace_ext4_write_begin(inode, pos, len, flags);
/*
* Reserve one block more for addition to orphan list in case
* we allocate blocks but write fails for some reason
*/
needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
index = pos >> PAGE_CACHE_SHIFT;
from = pos & (PAGE_CACHE_SIZE - 1);
to = from + len;
retry:
handle = ext4_journal_start(inode, needed_blocks);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
/* We cannot recurse into the filesystem as the transaction is already
* started */
flags |= AOP_FLAG_NOFS;
page = grab_cache_page_write_begin(mapping, index, flags);
if (!page) {
ext4_journal_stop(handle);
ret = -ENOMEM;
goto out;
}
*pagep = page;
ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
ext4_get_block);
if (!ret && ext4_should_journal_data(inode)) {
ret = walk_page_buffers(handle, page_buffers(page),
from, to, NULL, do_journal_get_write_access);
}
if (ret) {
unlock_page(page);
page_cache_release(page);
/*
* block_write_begin may have instantiated a few blocks
* outside i_size. Trim these off again. Don't need
* i_size_read because we hold i_mutex.
*
* Add inode to orphan list in case we crash before
* truncate finishes
*/
if (pos + len > inode->i_size && ext4_can_truncate(inode))
ext4_orphan_add(handle, inode);
ext4_journal_stop(handle);
if (pos + len > inode->i_size) {
ext4_truncate_failed_write(inode);
/*
* If truncate failed early the inode might
* still be on the orphan list; we need to
* make sure the inode is removed from the
* orphan list in that case.
*/
if (inode->i_nlink)
ext4_orphan_del(NULL, inode);
}
}
if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
out:
return ret;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | static int ext4_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct inode *inode = mapping->host;
int ret, needed_blocks;
handle_t *handle;
int retries = 0;
struct page *page;
pgoff_t index;
unsigned from, to;
trace_ext4_write_begin(inode, pos, len, flags);
/*
* Reserve one block more for addition to orphan list in case
* we allocate blocks but write fails for some reason
*/
needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
index = pos >> PAGE_CACHE_SHIFT;
from = pos & (PAGE_CACHE_SIZE - 1);
to = from + len;
retry:
handle = ext4_journal_start(inode, needed_blocks);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
/* We cannot recurse into the filesystem as the transaction is already
* started */
flags |= AOP_FLAG_NOFS;
page = grab_cache_page_write_begin(mapping, index, flags);
if (!page) {
ext4_journal_stop(handle);
ret = -ENOMEM;
goto out;
}
*pagep = page;
if (ext4_should_dioread_nolock(inode))
ret = block_write_begin(file, mapping, pos, len, flags, pagep,
fsdata, ext4_get_block_write);
else
ret = block_write_begin(file, mapping, pos, len, flags, pagep,
fsdata, ext4_get_block);
if (!ret && ext4_should_journal_data(inode)) {
ret = walk_page_buffers(handle, page_buffers(page),
from, to, NULL, do_journal_get_write_access);
}
if (ret) {
unlock_page(page);
page_cache_release(page);
/*
* block_write_begin may have instantiated a few blocks
* outside i_size. Trim these off again. Don't need
* i_size_read because we hold i_mutex.
*
* Add inode to orphan list in case we crash before
* truncate finishes
*/
if (pos + len > inode->i_size && ext4_can_truncate(inode))
ext4_orphan_add(handle, inode);
ext4_journal_stop(handle);
if (pos + len > inode->i_size) {
ext4_truncate_failed_write(inode);
/*
* If truncate failed early the inode might
* still be on the orphan list; we need to
* make sure the inode is removed from the
* orphan list in that case.
*/
if (inode->i_nlink)
ext4_orphan_del(NULL, inode);
}
}
if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
out:
return ret;
}
| 167,548 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string TestURLLoader::TestUntendedLoad() {
pp::URLRequestInfo request(instance_);
request.SetURL("test_url_loader_data/hello.txt");
request.SetRecordDownloadProgress(true);
TestCompletionCallback callback(instance_->pp_instance(), callback_type());
pp::URLLoader loader(instance_);
callback.WaitForResult(loader.Open(request, callback.GetCallback()));
CHECK_CALLBACK_BEHAVIOR(callback);
ASSERT_EQ(PP_OK, callback.result());
int64_t bytes_received = 0;
int64_t total_bytes_to_be_received = 0;
while (true) {
loader.GetDownloadProgress(&bytes_received, &total_bytes_to_be_received);
if (total_bytes_to_be_received <= 0)
return ReportError("URLLoader::GetDownloadProgress total size",
total_bytes_to_be_received);
if (bytes_received == total_bytes_to_be_received)
break;
if (pp::Module::Get()->core()->IsMainThread()) {
NestedEvent event(instance_->pp_instance());
event.PostSignal(10);
event.Wait();
}
}
std::string body;
std::string error = ReadEntireResponseBody(&loader, &body);
if (!error.empty())
return error;
if (body != "hello\n")
return ReportError("Couldn't read data", callback.result());
PASS();
}
Commit Message: Fix one implicit 64-bit -> 32-bit implicit conversion in a PPAPI test.
../../ppapi/tests/test_url_loader.cc:877:11: warning: implicit conversion loses integer precision: 'int64_t' (aka 'long long') to 'int32_t' (aka 'int') [-Wshorten-64-to-32]
total_bytes_to_be_received);
^~~~~~~~~~~~~~~~~~~~~~~~~~
BUG=879657
Change-Id: I152f456368131fe7a2891ff0c97bf83f26ef0906
Reviewed-on: https://chromium-review.googlesource.com/c/1220173
Commit-Queue: Raymes Khoury <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#600182}
CWE ID: CWE-284 | std::string TestURLLoader::TestUntendedLoad() {
pp::URLRequestInfo request(instance_);
request.SetURL("test_url_loader_data/hello.txt");
request.SetRecordDownloadProgress(true);
TestCompletionCallback callback(instance_->pp_instance(), callback_type());
pp::URLLoader loader(instance_);
callback.WaitForResult(loader.Open(request, callback.GetCallback()));
CHECK_CALLBACK_BEHAVIOR(callback);
ASSERT_EQ(PP_OK, callback.result());
int64_t bytes_received = 0;
int64_t total_bytes_to_be_received = 0;
while (true) {
loader.GetDownloadProgress(&bytes_received, &total_bytes_to_be_received);
if (total_bytes_to_be_received <= 0)
return ReportError("URLLoader::GetDownloadProgress total size",
static_cast<int32_t>(total_bytes_to_be_received));
if (bytes_received == total_bytes_to_be_received)
break;
if (pp::Module::Get()->core()->IsMainThread()) {
NestedEvent event(instance_->pp_instance());
event.PostSignal(10);
event.Wait();
}
}
std::string body;
std::string error = ReadEntireResponseBody(&loader, &body);
if (!error.empty())
return error;
if (body != "hello\n")
return ReportError("Couldn't read data", callback.result());
PASS();
}
| 173,279 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: process_secondary_order(STREAM s)
{
/* The length isn't calculated correctly by the server.
* For very compact orders the length becomes negative
* so a signed integer must be used. */
uint16 length;
uint16 flags;
uint8 type;
uint8 *next_order;
in_uint16_le(s, length);
in_uint16_le(s, flags); /* used by bmpcache2 */
in_uint8(s, type);
next_order = s->p + (sint16) length + 7;
switch (type)
{
case RDP_ORDER_RAW_BMPCACHE:
process_raw_bmpcache(s);
break;
case RDP_ORDER_COLCACHE:
process_colcache(s);
break;
case RDP_ORDER_BMPCACHE:
process_bmpcache(s);
break;
case RDP_ORDER_FONTCACHE:
process_fontcache(s);
break;
case RDP_ORDER_RAW_BMPCACHE2:
process_bmpcache2(s, flags, False); /* uncompressed */
break;
case RDP_ORDER_BMPCACHE2:
process_bmpcache2(s, flags, True); /* compressed */
break;
case RDP_ORDER_BRUSHCACHE:
process_brushcache(s, flags);
break;
default:
logger(Graphics, Warning,
"process_secondary_order(), unhandled secondary order %d", type);
}
s->p = next_order;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | process_secondary_order(STREAM s)
{
/* The length isn't calculated correctly by the server.
* For very compact orders the length becomes negative
* so a signed integer must be used. */
uint16 length;
uint16 flags;
uint8 type;
uint8 *next_order;
struct stream packet = *s;
in_uint16_le(s, length);
in_uint16_le(s, flags); /* used by bmpcache2 */
in_uint8(s, type);
if (!s_check_rem(s, length + 7))
{
rdp_protocol_error("process_secondary_order(), next order pointer would overrun stream", &packet);
}
next_order = s->p + (sint16) length + 7;
switch (type)
{
case RDP_ORDER_RAW_BMPCACHE:
process_raw_bmpcache(s);
break;
case RDP_ORDER_COLCACHE:
process_colcache(s);
break;
case RDP_ORDER_BMPCACHE:
process_bmpcache(s);
break;
case RDP_ORDER_FONTCACHE:
process_fontcache(s);
break;
case RDP_ORDER_RAW_BMPCACHE2:
process_bmpcache2(s, flags, False); /* uncompressed */
break;
case RDP_ORDER_BMPCACHE2:
process_bmpcache2(s, flags, True); /* compressed */
break;
case RDP_ORDER_BRUSHCACHE:
process_brushcache(s, flags);
break;
default:
logger(Graphics, Warning,
"process_secondary_order(), unhandled secondary order %d", type);
}
s->p = next_order;
}
| 169,801 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_decode_gaps_in_frame_num(dec_struct_t *ps_dec,
UWORD16 u2_frame_num)
{
UWORD32 u4_next_frm_num, u4_start_frm_num;
UWORD32 u4_max_frm_num;
pocstruct_t s_tmp_poc;
WORD32 i4_poc;
dec_slice_params_t *ps_cur_slice;
dec_pic_params_t *ps_pic_params;
WORD8 i1_gap_idx;
WORD32 *i4_gaps_start_frm_num;
dpb_manager_t *ps_dpb_mgr;
WORD32 i4_frame_gaps;
WORD8 *pi1_gaps_per_seq;
WORD32 ret;
ps_cur_slice = ps_dec->ps_cur_slice;
if(ps_cur_slice->u1_field_pic_flag)
{
if(ps_dec->u2_prev_ref_frame_num == u2_frame_num)
return 0;
}
u4_next_frm_num = ps_dec->u2_prev_ref_frame_num + 1;
u4_max_frm_num = ps_dec->ps_cur_sps->u2_u4_max_pic_num_minus1 + 1;
if(u4_next_frm_num >= u4_max_frm_num)
{
u4_next_frm_num -= u4_max_frm_num;
}
if(u4_next_frm_num == u2_frame_num)
{
return (0);
}
if((ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
&& (u4_next_frm_num >= u2_frame_num))
{
return (0);
}
u4_start_frm_num = u4_next_frm_num;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
s_tmp_poc.i4_delta_pic_order_cnt[0] = 0;
s_tmp_poc.i4_delta_pic_order_cnt[1] = 0;
ps_cur_slice = ps_dec->ps_cur_slice;
ps_pic_params = ps_dec->ps_cur_pps;
ps_cur_slice->u1_field_pic_flag = 0;
i4_frame_gaps = 0;
ps_dpb_mgr = ps_dec->ps_dpb_mgr;
/* Find a empty slot to store gap seqn info */
i4_gaps_start_frm_num = ps_dpb_mgr->ai4_gaps_start_frm_num;
for(i1_gap_idx = 0; i1_gap_idx < MAX_FRAMES; i1_gap_idx++)
{
if(INVALID_FRAME_NUM == i4_gaps_start_frm_num[i1_gap_idx])
break;
}
if(MAX_FRAMES == i1_gap_idx)
{
UWORD32 i4_error_code;
i4_error_code = ERROR_DBP_MANAGER_T;
return i4_error_code;
}
i4_poc = 0;
i4_gaps_start_frm_num[i1_gap_idx] = u4_start_frm_num;
ps_dpb_mgr->ai4_gaps_end_frm_num[i1_gap_idx] = u2_frame_num - 1;
pi1_gaps_per_seq = ps_dpb_mgr->ai1_gaps_per_seq;
pi1_gaps_per_seq[i1_gap_idx] = 0;
while(u4_next_frm_num != u2_frame_num)
{
ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr);
if(ps_pic_params->ps_sps->u1_pic_order_cnt_type)
{
/* allocate a picture buffer and insert it as ST node */
ret = ih264d_decode_pic_order_cnt(0, u4_next_frm_num,
&ps_dec->s_prev_pic_poc,
&s_tmp_poc, ps_cur_slice,
ps_pic_params, 1, 0, 0,
&i4_poc);
if(ret != OK)
return ret;
/* Display seq no calculations */
if(i4_poc >= ps_dec->i4_max_poc)
ps_dec->i4_max_poc = i4_poc;
/* IDR Picture or POC wrap around */
if(i4_poc == 0)
{
ps_dec->i4_prev_max_display_seq =
ps_dec->i4_prev_max_display_seq
+ ps_dec->i4_max_poc
+ ps_dec->u1_max_dec_frame_buffering
+ 1;
ps_dec->i4_max_poc = 0;
}
ps_cur_slice->u1_mmco_equalto5 = 0;
ps_cur_slice->u2_frame_num = u4_next_frm_num;
}
if(ps_dpb_mgr->i1_poc_buf_id_entries
>= ps_dec->u1_max_dec_frame_buffering)
{
ret = ih264d_assign_display_seq(ps_dec);
if(ret != OK)
return ret;
}
ret = ih264d_insert_pic_in_display_list(
ps_dec->ps_dpb_mgr, (WORD8) DO_NOT_DISP,
(WORD32)(ps_dec->i4_prev_max_display_seq + i4_poc),
u4_next_frm_num);
if(ret != OK)
return ret;
pi1_gaps_per_seq[i1_gap_idx]++;
ret = ih264d_do_mmco_for_gaps(ps_dpb_mgr,
ps_dec->ps_cur_sps->u1_num_ref_frames);
if(ret != OK)
return ret;
ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr);
u4_next_frm_num++;
if(u4_next_frm_num >= u4_max_frm_num)
{
u4_next_frm_num -= u4_max_frm_num;
}
i4_frame_gaps++;
}
return OK;
}
Commit Message: Decoder: Fixed error handling for dangling fields
In case of dangling fields with gaps in frames enabled,
field pic in cur_slice was wrongly set to 0.
This would cause dangling field to be concealed as a frame, which would
result in a number of MB mismatch and hence a hang.
Bug: 34097672
Change-Id: Ia9b7f72c4676188c45790b2dfbb4fe2c2d2c01f8
(cherry picked from commit 1a13168ca3510ba91274d10fdee46b3642cc9554)
CWE ID: CWE-119 | WORD32 ih264d_decode_gaps_in_frame_num(dec_struct_t *ps_dec,
UWORD16 u2_frame_num)
{
UWORD32 u4_next_frm_num, u4_start_frm_num;
UWORD32 u4_max_frm_num;
pocstruct_t s_tmp_poc;
WORD32 i4_poc;
dec_slice_params_t *ps_cur_slice;
dec_pic_params_t *ps_pic_params;
WORD8 i1_gap_idx;
WORD32 *i4_gaps_start_frm_num;
dpb_manager_t *ps_dpb_mgr;
WORD32 i4_frame_gaps;
WORD8 *pi1_gaps_per_seq;
WORD32 ret;
ps_cur_slice = ps_dec->ps_cur_slice;
if(ps_cur_slice->u1_field_pic_flag)
{
if(ps_dec->u2_prev_ref_frame_num == u2_frame_num)
return 0;
}
u4_next_frm_num = ps_dec->u2_prev_ref_frame_num + 1;
u4_max_frm_num = ps_dec->ps_cur_sps->u2_u4_max_pic_num_minus1 + 1;
if(u4_next_frm_num >= u4_max_frm_num)
{
u4_next_frm_num -= u4_max_frm_num;
}
if(u4_next_frm_num == u2_frame_num)
{
return (0);
}
if((ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
&& (u4_next_frm_num >= u2_frame_num))
{
return (0);
}
u4_start_frm_num = u4_next_frm_num;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
s_tmp_poc.i4_delta_pic_order_cnt[0] = 0;
s_tmp_poc.i4_delta_pic_order_cnt[1] = 0;
ps_cur_slice = ps_dec->ps_cur_slice;
ps_pic_params = ps_dec->ps_cur_pps;
i4_frame_gaps = 0;
ps_dpb_mgr = ps_dec->ps_dpb_mgr;
/* Find a empty slot to store gap seqn info */
i4_gaps_start_frm_num = ps_dpb_mgr->ai4_gaps_start_frm_num;
for(i1_gap_idx = 0; i1_gap_idx < MAX_FRAMES; i1_gap_idx++)
{
if(INVALID_FRAME_NUM == i4_gaps_start_frm_num[i1_gap_idx])
break;
}
if(MAX_FRAMES == i1_gap_idx)
{
UWORD32 i4_error_code;
i4_error_code = ERROR_DBP_MANAGER_T;
return i4_error_code;
}
i4_poc = 0;
i4_gaps_start_frm_num[i1_gap_idx] = u4_start_frm_num;
ps_dpb_mgr->ai4_gaps_end_frm_num[i1_gap_idx] = u2_frame_num - 1;
pi1_gaps_per_seq = ps_dpb_mgr->ai1_gaps_per_seq;
pi1_gaps_per_seq[i1_gap_idx] = 0;
while(u4_next_frm_num != u2_frame_num)
{
ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr);
if(ps_pic_params->ps_sps->u1_pic_order_cnt_type)
{
/* allocate a picture buffer and insert it as ST node */
ret = ih264d_decode_pic_order_cnt(0, u4_next_frm_num,
&ps_dec->s_prev_pic_poc,
&s_tmp_poc, ps_cur_slice,
ps_pic_params, 1, 0, 0,
&i4_poc);
if(ret != OK)
return ret;
/* Display seq no calculations */
if(i4_poc >= ps_dec->i4_max_poc)
ps_dec->i4_max_poc = i4_poc;
/* IDR Picture or POC wrap around */
if(i4_poc == 0)
{
ps_dec->i4_prev_max_display_seq =
ps_dec->i4_prev_max_display_seq
+ ps_dec->i4_max_poc
+ ps_dec->u1_max_dec_frame_buffering
+ 1;
ps_dec->i4_max_poc = 0;
}
ps_cur_slice->u1_mmco_equalto5 = 0;
ps_cur_slice->u2_frame_num = u4_next_frm_num;
}
if(ps_dpb_mgr->i1_poc_buf_id_entries
>= ps_dec->u1_max_dec_frame_buffering)
{
ret = ih264d_assign_display_seq(ps_dec);
if(ret != OK)
return ret;
}
ret = ih264d_insert_pic_in_display_list(
ps_dec->ps_dpb_mgr, (WORD8) DO_NOT_DISP,
(WORD32)(ps_dec->i4_prev_max_display_seq + i4_poc),
u4_next_frm_num);
if(ret != OK)
return ret;
pi1_gaps_per_seq[i1_gap_idx]++;
ret = ih264d_do_mmco_for_gaps(ps_dpb_mgr,
ps_dec->ps_cur_sps->u1_num_ref_frames);
if(ret != OK)
return ret;
ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr);
u4_next_frm_num++;
if(u4_next_frm_num >= u4_max_frm_num)
{
u4_next_frm_num -= u4_max_frm_num;
}
i4_frame_gaps++;
}
return OK;
}
| 174,027 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FindBarController::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
FindManager* find_manager = tab_contents_->GetFindManager();
if (type == NotificationType::FIND_RESULT_AVAILABLE) {
if (Source<TabContents>(source).ptr() == tab_contents_->tab_contents()) {
UpdateFindBarForCurrentResult();
if (find_manager->find_result().final_update() &&
find_manager->find_result().number_of_matches() == 0) {
const string16& last_search = find_manager->previous_find_text();
const string16& current_search = find_manager->find_text();
if (last_search.find(current_search) != 0)
find_bar_->AudibleAlert();
}
}
} else if (type == NotificationType::NAV_ENTRY_COMMITTED) {
NavigationController* source_controller =
Source<NavigationController>(source).ptr();
if (source_controller == &tab_contents_->controller()) {
NavigationController::LoadCommittedDetails* commit_details =
Details<NavigationController::LoadCommittedDetails>(details).ptr();
PageTransition::Type transition_type =
commit_details->entry->transition_type();
if (find_bar_->IsFindBarVisible()) {
if (PageTransition::StripQualifier(transition_type) !=
PageTransition::RELOAD) {
EndFindSession(kKeepSelection);
} else {
find_manager->set_find_op_aborted(true);
}
}
}
}
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void FindBarController::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper();
if (type == NotificationType::FIND_RESULT_AVAILABLE) {
if (Source<TabContents>(source).ptr() == tab_contents_->tab_contents()) {
UpdateFindBarForCurrentResult();
if (find_tab_helper->find_result().final_update() &&
find_tab_helper->find_result().number_of_matches() == 0) {
const string16& last_search = find_tab_helper->previous_find_text();
const string16& current_search = find_tab_helper->find_text();
if (last_search.find(current_search) != 0)
find_bar_->AudibleAlert();
}
}
} else if (type == NotificationType::NAV_ENTRY_COMMITTED) {
NavigationController* source_controller =
Source<NavigationController>(source).ptr();
if (source_controller == &tab_contents_->controller()) {
NavigationController::LoadCommittedDetails* commit_details =
Details<NavigationController::LoadCommittedDetails>(details).ptr();
PageTransition::Type transition_type =
commit_details->entry->transition_type();
if (find_bar_->IsFindBarVisible()) {
if (PageTransition::StripQualifier(transition_type) !=
PageTransition::RELOAD) {
EndFindSession(kKeepSelection);
} else {
find_tab_helper->set_find_op_aborted(true);
}
}
}
}
}
| 170,660 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth("kadm5_modify_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_modify_principal((void *)handle, &arg->rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_modify_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth("kadm5_modify_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_modify_principal((void *)handle, &arg->rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_modify_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
Commit Message: Fixed bug where PlzNavigate CSP in a iframe did not get the inherited CSP
When inheriting the CSP from a parent document to a local-scheme CSP,
it does not always get propagated to the PlzNavigate CSP. This means
that PlzNavigate CSP checks (like `frame-src`) would be ran against
a blank policy instead of the proper inherited policy.
Bug: 778658
Change-Id: I61bb0d432e1cea52f199e855624cb7b3078f56a9
Reviewed-on: https://chromium-review.googlesource.com/765969
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#518245}
CWE ID: CWE-732 | void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
GetContentSecurityPolicy()->BindToExecutionContext(this);
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
| 172,683 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WaitForCallback() {
if (!use_audio_thread_) {
base::RunLoop().RunUntilIdle();
return;
}
media::WaitableMessageLoopEvent event;
audio_thread_.task_runner()->PostTaskAndReply(
FROM_HERE, base::Bind(&base::DoNothing), event.GetClosure());
event.RunAndWait();
base::RunLoop().RunUntilIdle();
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | void WaitForCallback() {
if (!use_audio_thread_) {
base::RunLoop().RunUntilIdle();
return;
}
WaitableMessageLoopEvent event;
audio_thread_.task_runner()->PostTaskAndReply(
FROM_HERE, base::Bind(&base::DoNothing), event.GetClosure());
event.RunAndWait();
base::RunLoop().RunUntilIdle();
}
| 171,990 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionOptionsGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached()) {
auto guest_zoom_controller =
ui_zoom::ZoomController::FromWebContents(web_contents());
guest_zoom_controller->SetZoomMode(
ui_zoom::ZoomController::ZOOM_MODE_ISOLATED);
SetGuestZoomLevelToMatchEmbedder();
if (params.url.GetOrigin() != options_page_.GetOrigin()) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EOG_BAD_ORIGIN);
}
}
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
CWE ID: CWE-284 | void ExtensionOptionsGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached()) {
auto guest_zoom_controller =
ui_zoom::ZoomController::FromWebContents(web_contents());
guest_zoom_controller->SetZoomMode(
ui_zoom::ZoomController::ZOOM_MODE_ISOLATED);
SetGuestZoomLevelToMatchEmbedder();
if (!url::IsSameOriginWith(params.url, options_page_)) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EOG_BAD_ORIGIN);
}
}
}
| 172,282 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields)
{
if (fields)
{
if (fields->Buffer)
{
free(fields->Buffer);
fields->Len = 0;
fields->MaxLen = 0;
fields->Buffer = NULL;
fields->BufferOffset = 0;
}
}
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125 | void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields)
static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields)
{
if (fields)
{
if (fields->Buffer)
{
free(fields->Buffer);
fields->Len = 0;
fields->MaxLen = 0;
fields->Buffer = NULL;
fields->BufferOffset = 0;
}
}
}
| 169,272 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport int LocaleUppercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l(c,c_locale));
#endif
return(toupper(c));
}
Commit Message: ...
CWE ID: CWE-125 | MagickExport int LocaleUppercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
| 170,234 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame)
{
const uint8_t* as_pack;
int freq, stype, smpls, quant, i, ach;
as_pack = dv_extract_pack(frame, dv_audio_source);
if (!as_pack || !c->sys) { /* No audio ? */
c->ach = 0;
return 0;
}
smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */
quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
/* note: ach counts PAIRS of channels (i.e. stereo channels) */
ach = ((int[4]){ 1, 0, 2, 4})[stype];
if (ach == 1 && quant && freq == 2)
if (!c->ast[i])
break;
avpriv_set_pts_info(c->ast[i], 64, 1, 30000);
c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO;
c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE;
av_init_packet(&c->audio_pkt[i]);
c->audio_pkt[i].size = 0;
c->audio_pkt[i].data = c->audio_buf[i];
c->audio_pkt[i].stream_index = c->ast[i]->index;
c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY;
}
Commit Message:
CWE ID: CWE-20 | static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame)
{
const uint8_t* as_pack;
int freq, stype, smpls, quant, i, ach;
as_pack = dv_extract_pack(frame, dv_audio_source);
if (!as_pack || !c->sys) { /* No audio ? */
c->ach = 0;
return 0;
}
smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */
quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
if (stype > 3) {
av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype);
c->ach = 0;
return 0;
}
/* note: ach counts PAIRS of channels (i.e. stereo channels) */
ach = ((int[4]){ 1, 0, 2, 4})[stype];
if (ach == 1 && quant && freq == 2)
if (!c->ast[i])
break;
avpriv_set_pts_info(c->ast[i], 64, 1, 30000);
c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO;
c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE;
av_init_packet(&c->audio_pkt[i]);
c->audio_pkt[i].size = 0;
c->audio_pkt[i].data = c->audio_buf[i];
c->audio_pkt[i].stream_index = c->ast[i]->index;
c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY;
}
| 165,243 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long ContentEncoding::ParseEncryptionEntry(long long start, long long size,
IMkvReader* pReader,
ContentEncryption* encryption) {
assert(pReader);
assert(encryption);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E1) {
encryption->algo = UnserializeUInt(pReader, pos, size);
if (encryption->algo != 5)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x7E2) {
delete[] encryption -> key_id;
encryption->key_id = NULL;
encryption->key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->key_id = buf;
encryption->key_id_len = buflen;
} else if (id == 0x7E3) {
delete[] encryption -> signature;
encryption->signature = NULL;
encryption->signature_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->signature = buf;
encryption->signature_len = buflen;
} else if (id == 0x7E4) {
delete[] encryption -> sig_key_id;
encryption->sig_key_id = NULL;
encryption->sig_key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->sig_key_id = buf;
encryption->sig_key_id_len = buflen;
} else if (id == 0x7E5) {
encryption->sig_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E6) {
encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E7) {
const long status = ParseContentEncAESSettingsEntry(
pos, size, pReader, &encryption->aes_settings);
if (status)
return status;
}
pos += size; // consume payload
assert(pos <= stop);
}
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long ContentEncoding::ParseEncryptionEntry(long long start, long long size,
IMkvReader* pReader,
ContentEncryption* encryption) {
assert(pReader);
assert(encryption);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E1) {
encryption->algo = UnserializeUInt(pReader, pos, size);
if (encryption->algo != 5)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x7E2) {
delete[] encryption->key_id;
encryption->key_id = NULL;
encryption->key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->key_id = buf;
encryption->key_id_len = buflen;
} else if (id == 0x7E3) {
delete[] encryption->signature;
encryption->signature = NULL;
encryption->signature_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->signature = buf;
encryption->signature_len = buflen;
} else if (id == 0x7E4) {
delete[] encryption->sig_key_id;
encryption->sig_key_id = NULL;
encryption->sig_key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->sig_key_id = buf;
encryption->sig_key_id_len = buflen;
} else if (id == 0x7E5) {
encryption->sig_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E6) {
encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E7) {
const long status = ParseContentEncAESSettingsEntry(
pos, size, pReader, &encryption->aes_settings);
if (status)
return status;
}
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
return 0;
}
| 173,854 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119 | void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
| 173,922 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
}
/* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
However, when parsing an external subset, doProlog will not accept a BOM
as valid, and report a syntax error, so we have to skip the BOM
*/
else if (tok == XML_TOK_BOM) {
s = next;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
parser->m_processor = prologProcessor;
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
}
Commit Message: xmlparse.c: Deny internal entities closing the doctype
CWE ID: CWE-611 | externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
}
/* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
However, when parsing an external subset, doProlog will not accept a BOM
as valid, and report a syntax error, so we have to skip the BOM
*/
else if (tok == XML_TOK_BOM) {
s = next;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
parser->m_processor = prologProcessor;
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE);
}
| 169,530 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect)
{
REGION16_DATA* newItems;
const RECTANGLE_16* srcPtr, *endPtr, *srcExtents;
RECTANGLE_16* dstPtr;
UINT32 nbRects, usedRects;
RECTANGLE_16 common, newExtents;
assert(src);
assert(src->data);
srcPtr = region16_rects(src, &nbRects);
if (!nbRects)
{
region16_clear(dst);
return TRUE;
}
srcExtents = region16_extents(src);
if (nbRects == 1)
{
BOOL intersects = rectangles_intersection(srcExtents, rect, &common);
region16_clear(dst);
if (intersects)
return region16_union_rect(dst, dst, &common);
return TRUE;
}
newItems = allocateRegion(nbRects);
if (!newItems)
return FALSE;
dstPtr = (RECTANGLE_16*)(&newItems[1]);
usedRects = 0;
ZeroMemory(&newExtents, sizeof(newExtents));
/* accumulate intersecting rectangles, the final region16_simplify_bands() will
* do all the bad job to recreate correct rectangles
*/
for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++)
{
if (rectangles_intersection(srcPtr, rect, &common))
{
*dstPtr = common;
usedRects++;
dstPtr++;
if (rectangle_is_empty(&newExtents))
{
/* Check if the existing newExtents is empty. If it is empty, use
* new common directly. We do not need to check common rectangle
* because the rectangles_intersection() ensures that it is not empty.
*/
newExtents = common;
}
else
{
newExtents.top = MIN(common.top, newExtents.top);
newExtents.left = MIN(common.left, newExtents.left);
newExtents.bottom = MAX(common.bottom, newExtents.bottom);
newExtents.right = MAX(common.right, newExtents.right);
}
}
}
newItems->nbRects = usedRects;
newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16));
if ((dst->data->size > 0) && (dst->data != &empty_region))
free(dst->data);
dst->data = realloc(newItems, newItems->size);
if (!dst->data)
{
free(newItems);
return FALSE;
}
dst->extents = newExtents;
return region16_simplify_bands(dst);
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772 | BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect)
{
REGION16_DATA* data;
REGION16_DATA* newItems;
const RECTANGLE_16* srcPtr, *endPtr, *srcExtents;
RECTANGLE_16* dstPtr;
UINT32 nbRects, usedRects;
RECTANGLE_16 common, newExtents;
assert(src);
assert(src->data);
srcPtr = region16_rects(src, &nbRects);
if (!nbRects)
{
region16_clear(dst);
return TRUE;
}
srcExtents = region16_extents(src);
if (nbRects == 1)
{
BOOL intersects = rectangles_intersection(srcExtents, rect, &common);
region16_clear(dst);
if (intersects)
return region16_union_rect(dst, dst, &common);
return TRUE;
}
newItems = allocateRegion(nbRects);
if (!newItems)
return FALSE;
dstPtr = (RECTANGLE_16*)(&newItems[1]);
usedRects = 0;
ZeroMemory(&newExtents, sizeof(newExtents));
/* accumulate intersecting rectangles, the final region16_simplify_bands() will
* do all the bad job to recreate correct rectangles
*/
for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++)
{
if (rectangles_intersection(srcPtr, rect, &common))
{
*dstPtr = common;
usedRects++;
dstPtr++;
if (rectangle_is_empty(&newExtents))
{
/* Check if the existing newExtents is empty. If it is empty, use
* new common directly. We do not need to check common rectangle
* because the rectangles_intersection() ensures that it is not empty.
*/
newExtents = common;
}
else
{
newExtents.top = MIN(common.top, newExtents.top);
newExtents.left = MIN(common.left, newExtents.left);
newExtents.bottom = MAX(common.bottom, newExtents.bottom);
newExtents.right = MAX(common.right, newExtents.right);
}
}
}
newItems->nbRects = usedRects;
newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16));
if ((dst->data->size > 0) && (dst->data != &empty_region))
free(dst->data);
data = realloc(newItems, newItems->size);
if (!data)
free(dst->data);
dst->data = data;
if (!dst->data)
{
free(newItems);
return FALSE;
}
dst->extents = newExtents;
return region16_simplify_bands(dst);
}
| 169,496 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GURL SanitizeFrontendURL(
const GURL& url,
const std::string& scheme,
const std::string& host,
const std::string& path,
bool allow_query) {
std::vector<std::string> query_parts;
if (allow_query) {
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()));
}
}
}
std::string query =
query_parts.empty() ? "" : "?" + base::JoinString(query_parts, "&");
std::string constructed = base::StringPrintf("%s://%s%s%s",
scheme.c_str(), host.c_str(), path.c_str(), query.c_str());
GURL result = GURL(constructed);
if (!result.is_valid())
return GURL();
return result;
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200 | GURL SanitizeFrontendURL(
| 172,460 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
struct packet_rollover *rollover = NULL;
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f, *match;
u8 type = type_flags & 0xff;
u8 flags = type_flags >> 8;
int err;
switch (type) {
case PACKET_FANOUT_ROLLOVER:
if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
return -EINVAL;
case PACKET_FANOUT_HASH:
case PACKET_FANOUT_LB:
case PACKET_FANOUT_CPU:
case PACKET_FANOUT_RND:
case PACKET_FANOUT_QM:
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
break;
default:
return -EINVAL;
}
mutex_lock(&fanout_mutex);
err = -EINVAL;
if (!po->running)
goto out;
err = -EALREADY;
if (po->fanout)
goto out;
if (type == PACKET_FANOUT_ROLLOVER ||
(type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
err = -ENOMEM;
rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
if (!rollover)
goto out;
atomic_long_set(&rollover->num, 0);
atomic_long_set(&rollover->num_huge, 0);
atomic_long_set(&rollover->num_failed, 0);
po->rollover = rollover;
}
if (type_flags & PACKET_FANOUT_FLAG_UNIQUEID) {
if (id != 0) {
err = -EINVAL;
goto out;
}
if (!fanout_find_new_id(sk, &id)) {
err = -ENOMEM;
goto out;
}
/* ephemeral flag for the first socket in the group: drop it */
flags &= ~(PACKET_FANOUT_FLAG_UNIQUEID >> 8);
}
match = NULL;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == id &&
read_pnet(&f->net) == sock_net(sk)) {
match = f;
break;
}
}
err = -EINVAL;
if (match && match->flags != flags)
goto out;
if (!match) {
err = -ENOMEM;
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
goto out;
write_pnet(&match->net, sock_net(sk));
match->id = id;
match->type = type;
match->flags = flags;
INIT_LIST_HEAD(&match->list);
spin_lock_init(&match->lock);
refcount_set(&match->sk_ref, 0);
fanout_init_data(match);
match->prot_hook.type = po->prot_hook.type;
match->prot_hook.dev = po->prot_hook.dev;
match->prot_hook.func = packet_rcv_fanout;
match->prot_hook.af_packet_priv = match;
match->prot_hook.id_match = match_fanout_group;
list_add(&match->list, &fanout_list);
}
err = -EINVAL;
if (match->type == type &&
match->prot_hook.type == po->prot_hook.type &&
match->prot_hook.dev == po->prot_hook.dev) {
err = -ENOSPC;
if (refcount_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
__dev_remove_pack(&po->prot_hook);
po->fanout = match;
refcount_set(&match->sk_ref, refcount_read(&match->sk_ref) + 1);
__fanout_link(sk, po);
err = 0;
}
}
out:
if (err && rollover) {
kfree(rollover);
po->rollover = NULL;
}
mutex_unlock(&fanout_mutex);
return err;
}
Commit Message: packet: hold bind lock when rebinding to fanout hook
Packet socket bind operations must hold the po->bind_lock. This keeps
po->running consistent with whether the socket is actually on a ptype
list to receive packets.
fanout_add unbinds a socket and its packet_rcv/tpacket_rcv call, then
binds the fanout object to receive through packet_rcv_fanout.
Make it hold the po->bind_lock when testing po->running and rebinding.
Else, it can race with other rebind operations, such as that in
packet_set_ring from packet_rcv to tpacket_rcv. Concurrent updates
can result in a socket being added to a fanout group twice, causing
use-after-free KASAN bug reports, among others.
Reported independently by both trinity and syzkaller.
Verified that the syzkaller reproducer passes after this patch.
Fixes: dc99f600698d ("packet: Add fanout support.")
Reported-by: nixioaming <[email protected]>
Signed-off-by: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
struct packet_rollover *rollover = NULL;
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f, *match;
u8 type = type_flags & 0xff;
u8 flags = type_flags >> 8;
int err;
switch (type) {
case PACKET_FANOUT_ROLLOVER:
if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
return -EINVAL;
case PACKET_FANOUT_HASH:
case PACKET_FANOUT_LB:
case PACKET_FANOUT_CPU:
case PACKET_FANOUT_RND:
case PACKET_FANOUT_QM:
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
break;
default:
return -EINVAL;
}
mutex_lock(&fanout_mutex);
err = -EALREADY;
if (po->fanout)
goto out;
if (type == PACKET_FANOUT_ROLLOVER ||
(type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
err = -ENOMEM;
rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
if (!rollover)
goto out;
atomic_long_set(&rollover->num, 0);
atomic_long_set(&rollover->num_huge, 0);
atomic_long_set(&rollover->num_failed, 0);
po->rollover = rollover;
}
if (type_flags & PACKET_FANOUT_FLAG_UNIQUEID) {
if (id != 0) {
err = -EINVAL;
goto out;
}
if (!fanout_find_new_id(sk, &id)) {
err = -ENOMEM;
goto out;
}
/* ephemeral flag for the first socket in the group: drop it */
flags &= ~(PACKET_FANOUT_FLAG_UNIQUEID >> 8);
}
match = NULL;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == id &&
read_pnet(&f->net) == sock_net(sk)) {
match = f;
break;
}
}
err = -EINVAL;
if (match && match->flags != flags)
goto out;
if (!match) {
err = -ENOMEM;
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
goto out;
write_pnet(&match->net, sock_net(sk));
match->id = id;
match->type = type;
match->flags = flags;
INIT_LIST_HEAD(&match->list);
spin_lock_init(&match->lock);
refcount_set(&match->sk_ref, 0);
fanout_init_data(match);
match->prot_hook.type = po->prot_hook.type;
match->prot_hook.dev = po->prot_hook.dev;
match->prot_hook.func = packet_rcv_fanout;
match->prot_hook.af_packet_priv = match;
match->prot_hook.id_match = match_fanout_group;
list_add(&match->list, &fanout_list);
}
err = -EINVAL;
spin_lock(&po->bind_lock);
if (po->running &&
match->type == type &&
match->prot_hook.type == po->prot_hook.type &&
match->prot_hook.dev == po->prot_hook.dev) {
err = -ENOSPC;
if (refcount_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
__dev_remove_pack(&po->prot_hook);
po->fanout = match;
refcount_set(&match->sk_ref, refcount_read(&match->sk_ref) + 1);
__fanout_link(sk, po);
err = 0;
}
}
spin_unlock(&po->bind_lock);
if (err && !refcount_read(&match->sk_ref)) {
list_del(&match->list);
kfree(match);
}
out:
if (err && rollover) {
kfree(rollover);
po->rollover = NULL;
}
mutex_unlock(&fanout_mutex);
return err;
}
| 170,015 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct packet_offload *ptype;
__be16 type = skb->protocol;
struct list_head *head = &offload_base;
int same_flow;
enum gro_result ret;
int grow;
if (!(skb->dev->features & NETIF_F_GRO))
goto normal;
if (skb_is_gso(skb) || skb_has_frag_list(skb) || skb->csum_bad)
goto normal;
gro_list_prepare(napi, skb);
rcu_read_lock();
list_for_each_entry_rcu(ptype, head, list) {
if (ptype->type != type || !ptype->callbacks.gro_receive)
continue;
skb_set_network_header(skb, skb_gro_offset(skb));
skb_reset_mac_len(skb);
NAPI_GRO_CB(skb)->same_flow = 0;
NAPI_GRO_CB(skb)->flush = 0;
NAPI_GRO_CB(skb)->free = 0;
NAPI_GRO_CB(skb)->udp_mark = 0;
NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
/* Setup for GRO checksum validation */
switch (skb->ip_summed) {
case CHECKSUM_COMPLETE:
NAPI_GRO_CB(skb)->csum = skb->csum;
NAPI_GRO_CB(skb)->csum_valid = 1;
NAPI_GRO_CB(skb)->csum_cnt = 0;
break;
case CHECKSUM_UNNECESSARY:
NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
NAPI_GRO_CB(skb)->csum_valid = 0;
break;
default:
NAPI_GRO_CB(skb)->csum_cnt = 0;
NAPI_GRO_CB(skb)->csum_valid = 0;
}
pp = ptype->callbacks.gro_receive(&napi->gro_list, skb);
break;
}
rcu_read_unlock();
if (&ptype->list == head)
goto normal;
same_flow = NAPI_GRO_CB(skb)->same_flow;
ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
if (pp) {
struct sk_buff *nskb = *pp;
*pp = nskb->next;
nskb->next = NULL;
napi_gro_complete(nskb);
napi->gro_count--;
}
if (same_flow)
goto ok;
if (NAPI_GRO_CB(skb)->flush)
goto normal;
if (unlikely(napi->gro_count >= MAX_GRO_SKBS)) {
struct sk_buff *nskb = napi->gro_list;
/* locate the end of the list to select the 'oldest' flow */
while (nskb->next) {
pp = &nskb->next;
nskb = *pp;
}
*pp = NULL;
nskb->next = NULL;
napi_gro_complete(nskb);
} else {
napi->gro_count++;
}
NAPI_GRO_CB(skb)->count = 1;
NAPI_GRO_CB(skb)->age = jiffies;
NAPI_GRO_CB(skb)->last = skb;
skb_shinfo(skb)->gso_size = skb_gro_len(skb);
skb->next = napi->gro_list;
napi->gro_list = skb;
ret = GRO_HELD;
pull:
grow = skb_gro_offset(skb) - skb_headlen(skb);
if (grow > 0)
gro_pull_from_frag0(skb, grow);
ok:
return ret;
normal:
ret = GRO_NORMAL;
goto pull;
}
Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation.
When drivers express support for TSO of encapsulated packets, they
only mean that they can do it for one layer of encapsulation.
Supporting additional levels would mean updating, at a minimum,
more IP length fields and they are unaware of this.
No encapsulation device expresses support for handling offloaded
encapsulated packets, so we won't generate these types of frames
in the transmit path. However, GRO doesn't have a check for
multiple levels of encapsulation and will attempt to build them.
UDP tunnel GRO actually does prevent this situation but it only
handles multiple UDP tunnels stacked on top of each other. This
generalizes that solution to prevent any kind of tunnel stacking
that would cause problems.
Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack")
Signed-off-by: Jesse Gross <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-400 | static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct packet_offload *ptype;
__be16 type = skb->protocol;
struct list_head *head = &offload_base;
int same_flow;
enum gro_result ret;
int grow;
if (!(skb->dev->features & NETIF_F_GRO))
goto normal;
if (skb_is_gso(skb) || skb_has_frag_list(skb) || skb->csum_bad)
goto normal;
gro_list_prepare(napi, skb);
rcu_read_lock();
list_for_each_entry_rcu(ptype, head, list) {
if (ptype->type != type || !ptype->callbacks.gro_receive)
continue;
skb_set_network_header(skb, skb_gro_offset(skb));
skb_reset_mac_len(skb);
NAPI_GRO_CB(skb)->same_flow = 0;
NAPI_GRO_CB(skb)->flush = 0;
NAPI_GRO_CB(skb)->free = 0;
NAPI_GRO_CB(skb)->encap_mark = 0;
NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
/* Setup for GRO checksum validation */
switch (skb->ip_summed) {
case CHECKSUM_COMPLETE:
NAPI_GRO_CB(skb)->csum = skb->csum;
NAPI_GRO_CB(skb)->csum_valid = 1;
NAPI_GRO_CB(skb)->csum_cnt = 0;
break;
case CHECKSUM_UNNECESSARY:
NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
NAPI_GRO_CB(skb)->csum_valid = 0;
break;
default:
NAPI_GRO_CB(skb)->csum_cnt = 0;
NAPI_GRO_CB(skb)->csum_valid = 0;
}
pp = ptype->callbacks.gro_receive(&napi->gro_list, skb);
break;
}
rcu_read_unlock();
if (&ptype->list == head)
goto normal;
same_flow = NAPI_GRO_CB(skb)->same_flow;
ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
if (pp) {
struct sk_buff *nskb = *pp;
*pp = nskb->next;
nskb->next = NULL;
napi_gro_complete(nskb);
napi->gro_count--;
}
if (same_flow)
goto ok;
if (NAPI_GRO_CB(skb)->flush)
goto normal;
if (unlikely(napi->gro_count >= MAX_GRO_SKBS)) {
struct sk_buff *nskb = napi->gro_list;
/* locate the end of the list to select the 'oldest' flow */
while (nskb->next) {
pp = &nskb->next;
nskb = *pp;
}
*pp = NULL;
nskb->next = NULL;
napi_gro_complete(nskb);
} else {
napi->gro_count++;
}
NAPI_GRO_CB(skb)->count = 1;
NAPI_GRO_CB(skb)->age = jiffies;
NAPI_GRO_CB(skb)->last = skb;
skb_shinfo(skb)->gso_size = skb_gro_len(skb);
skb->next = napi->gro_list;
napi->gro_list = skb;
ret = GRO_HELD;
pull:
grow = skb_gro_offset(skb) - skb_headlen(skb);
if (grow > 0)
gro_pull_from_frag0(skb, grow);
ok:
return ret;
normal:
ret = GRO_NORMAL;
goto pull;
}
| 166,905 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DevToolsSession::ReceivedBadMessage() {
MojoConnectionDestroyed();
if (process_) {
bad_message::ReceivedBadMessage(
process_, bad_message::RFH_INCONSISTENT_DEVTOOLS_MESSAGE);
}
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void DevToolsSession::ReceivedBadMessage() {
MojoConnectionDestroyed();
RenderProcessHost* process = RenderProcessHost::FromID(process_host_id_);
if (process) {
bad_message::ReceivedBadMessage(
process, bad_message::RFH_INCONSISTENT_DEVTOOLS_MESSAGE);
}
}
| 172,742 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,
int32_t *opcode)
{
int i;
struct rx_cache_entry *rxent;
uint32_t clip;
uint32_t sip;
UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t));
UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t));
/* Start the search where we last left off */
i = rx_cache_hint;
do {
rxent = &rx_cache[i];
if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) &&
rxent->client.s_addr == clip &&
rxent->server.s_addr == sip &&
rxent->serviceId == EXTRACT_32BITS(&rxh->serviceId) &&
rxent->dport == sport) {
/* We got a match! */
rx_cache_hint = i;
*opcode = rxent->opcode;
return(1);
}
if (++i >= RX_CACHE_SIZE)
i = 0;
} while (i != rx_cache_hint);
/* Our search failed */
return(0);
}
Commit Message: (for 4.9.3) CVE-2018-14466/Rx: fix an over-read bug
In rx_cache_insert() and rx_cache_find() properly read the serviceId
field of the rx_header structure as a 16-bit integer. When those
functions tried to read 32 bits the extra 16 bits could be outside of
the bounds checked in rx_print() for the rx_header structure, as
serviceId is the last field in that structure.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,
int32_t *opcode)
{
int i;
struct rx_cache_entry *rxent;
uint32_t clip;
uint32_t sip;
UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t));
UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t));
/* Start the search where we last left off */
i = rx_cache_hint;
do {
rxent = &rx_cache[i];
if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) &&
rxent->client.s_addr == clip &&
rxent->server.s_addr == sip &&
rxent->serviceId == EXTRACT_16BITS(&rxh->serviceId) &&
rxent->dport == sport) {
/* We got a match! */
rx_cache_hint = i;
*opcode = rxent->opcode;
return(1);
}
if (++i >= RX_CACHE_SIZE)
i = 0;
} while (i != rx_cache_hint);
/* Our search failed */
return(0);
}
| 169,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __init xfrm6_tunnel_spi_init(void)
{
xfrm6_tunnel_spi_kmem = kmem_cache_create("xfrm6_tunnel_spi",
sizeof(struct xfrm6_tunnel_spi),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!xfrm6_tunnel_spi_kmem)
return -ENOMEM;
return 0;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int __init xfrm6_tunnel_spi_init(void)
| 165,882 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
: AbstractMetadataProvider(e),
m_validate(XMLHelper::getAttrBool(e, false, validate)),
m_id(XMLHelper::getAttrString(e, "Dynamic", id)),
m_lock(RWLock::create()),
m_refreshDelayFactor(0.75),
m_minCacheDuration(XMLHelper::getAttrInt(e, 600, minCacheDuration)),
m_maxCacheDuration(XMLHelper::getAttrInt(e, 28800, maxCacheDuration)),
m_shutdown(false),
m_cleanupInterval(XMLHelper::getAttrInt(e, 1800, cleanupInterval)),
m_cleanupTimeout(XMLHelper::getAttrInt(e, 1800, cleanupTimeout)),
m_cleanup_wait(nullptr), m_cleanup_thread(nullptr)
{
if (m_minCacheDuration > m_maxCacheDuration) {
Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error(
"minCacheDuration setting exceeds maxCacheDuration setting, lowering to match it"
);
m_minCacheDuration = m_maxCacheDuration;
}
const XMLCh* delay = e ? e->getAttributeNS(nullptr, refreshDelayFactor) : nullptr;
if (delay && *delay) {
auto_ptr_char temp(delay);
m_refreshDelayFactor = atof(temp.get());
if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error(
"invalid refreshDelayFactor setting, using default"
);
m_refreshDelayFactor = 0.75;
}
}
if (m_cleanupInterval > 0) {
if (m_cleanupTimeout < 0)
m_cleanupTimeout = 0;
m_cleanup_wait = CondWait::create();
m_cleanup_thread = Thread::create(&cleanup_fn, this);
}
}
Commit Message:
CWE ID: CWE-347 | DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
: AbstractMetadataProvider(e), MetadataProvider(e),
m_validate(XMLHelper::getAttrBool(e, false, validate)),
m_id(XMLHelper::getAttrString(e, "Dynamic", id)),
m_lock(RWLock::create()),
m_refreshDelayFactor(0.75),
m_minCacheDuration(XMLHelper::getAttrInt(e, 600, minCacheDuration)),
m_maxCacheDuration(XMLHelper::getAttrInt(e, 28800, maxCacheDuration)),
m_shutdown(false),
m_cleanupInterval(XMLHelper::getAttrInt(e, 1800, cleanupInterval)),
m_cleanupTimeout(XMLHelper::getAttrInt(e, 1800, cleanupTimeout)),
m_cleanup_wait(nullptr), m_cleanup_thread(nullptr)
{
if (m_minCacheDuration > m_maxCacheDuration) {
Category::getInstance(SAML_LOGCAT ".Metadata.Dynamic").error(
"minCacheDuration setting exceeds maxCacheDuration setting, lowering to match it"
);
m_minCacheDuration = m_maxCacheDuration;
}
const XMLCh* delay = e ? e->getAttributeNS(nullptr, refreshDelayFactor) : nullptr;
if (delay && *delay) {
auto_ptr_char temp(delay);
m_refreshDelayFactor = atof(temp.get());
if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error(
"invalid refreshDelayFactor setting, using default"
);
m_refreshDelayFactor = 0.75;
}
}
if (m_cleanupInterval > 0) {
if (m_cleanupTimeout < 0)
m_cleanupTimeout = 0;
m_cleanup_wait = CondWait::create();
m_cleanup_thread = Thread::create(&cleanup_fn, this);
}
}
| 164,622 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this,
image_transform_png_set_scale_16_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
}
this->next->mod(this->next, that, pp, display);
}
| 173,646 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void become_daemon(const char *pidfile)
{
#ifndef _WIN32
pid_t pid, sid;
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
if (pidfile) {
if (!ga_open_pidfile(pidfile)) {
g_critical("failed to create pidfile");
exit(EXIT_FAILURE);
}
}
umask(0);
sid = setsid();
if (sid < 0) {
goto fail;
}
if ((chdir("/")) < 0) {
goto fail;
}
reopen_fd_to_null(STDIN_FILENO);
reopen_fd_to_null(STDOUT_FILENO);
reopen_fd_to_null(STDERR_FILENO);
return;
fail:
if (pidfile) {
unlink(pidfile);
}
g_critical("failed to daemonize");
exit(EXIT_FAILURE);
#endif
}
Commit Message:
CWE ID: CWE-264 | static void become_daemon(const char *pidfile)
{
#ifndef _WIN32
pid_t pid, sid;
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
if (pidfile) {
if (!ga_open_pidfile(pidfile)) {
g_critical("failed to create pidfile");
exit(EXIT_FAILURE);
}
}
umask(S_IRWXG | S_IRWXO);
sid = setsid();
if (sid < 0) {
goto fail;
}
if ((chdir("/")) < 0) {
goto fail;
}
reopen_fd_to_null(STDIN_FILENO);
reopen_fd_to_null(STDOUT_FILENO);
reopen_fd_to_null(STDERR_FILENO);
return;
fail:
if (pidfile) {
unlink(pidfile);
}
g_critical("failed to daemonize");
exit(EXIT_FAILURE);
#endif
}
| 164,724 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline signed short ReadProfileShort(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed short ReadProfileShort(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
| 169,946 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: modifier_current_encoding(PNG_CONST png_modifier *pm, color_encoding *ce)
{
if (pm->current_encoding != 0)
*ce = *pm->current_encoding;
else
memset(ce, 0, sizeof *ce);
ce->gamma = pm->current_gamma;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | modifier_current_encoding(PNG_CONST png_modifier *pm, color_encoding *ce)
modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
{
if (pm->current_encoding != 0)
*ce = *pm->current_encoding;
else
memset(ce, 0, sizeof *ce);
ce->gamma = pm->current_gamma;
}
| 173,669 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void usage()
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: pnm2png [options] <file>.<pnm> [<file>.png]\n");
fprintf (stderr, " or: ... | pnm2png [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -i[nterlace] write png-file with interlacing on\n");
fprintf (stderr, " -a[lpha] <file>.pgm read PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | void usage()
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: pnm2png [options] <file>.<pnm> [<file>.png]\n");
fprintf (stderr, " or: ... | pnm2png [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -i[nterlace] write png-file with interlacing on\n");
fprintf (stderr,
" -a[lpha] <file>.pgm read PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
| 173,726 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int php_stream_memory_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */
{
php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract;
size_t newsize;
switch(option) {
case PHP_STREAM_OPTION_TRUNCATE_API:
switch (value) {
case PHP_STREAM_TRUNCATE_SUPPORTED:
return PHP_STREAM_OPTION_RETURN_OK;
case PHP_STREAM_TRUNCATE_SET_SIZE:
if (ms->mode & TEMP_STREAM_READONLY) {
return PHP_STREAM_OPTION_RETURN_ERR;
}
newsize = *(size_t*)ptrparam;
if (newsize <= ms->fsize) {
if (newsize < ms->fpos) {
ms->fpos = newsize;
}
} else {
ms->data = erealloc(ms->data, newsize);
memset(ms->data+ms->fsize, 0, newsize - ms->fsize);
ms->fsize = newsize;
}
ms->fsize = newsize;
return PHP_STREAM_OPTION_RETURN_OK;
}
default:
return PHP_STREAM_OPTION_RETURN_NOTIMPL;
}
}
/* }}} */
Commit Message:
CWE ID: CWE-20 | static int php_stream_memory_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */
{
php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract;
size_t newsize;
switch(option) {
case PHP_STREAM_OPTION_TRUNCATE_API:
switch (value) {
case PHP_STREAM_TRUNCATE_SUPPORTED:
return PHP_STREAM_OPTION_RETURN_OK;
case PHP_STREAM_TRUNCATE_SET_SIZE:
if (ms->mode & TEMP_STREAM_READONLY) {
return PHP_STREAM_OPTION_RETURN_ERR;
}
newsize = *(size_t*)ptrparam;
if (newsize <= ms->fsize) {
if (newsize < ms->fpos) {
ms->fpos = newsize;
}
} else {
ms->data = erealloc(ms->data, newsize);
memset(ms->data+ms->fsize, 0, newsize - ms->fsize);
ms->fsize = newsize;
}
ms->fsize = newsize;
return PHP_STREAM_OPTION_RETURN_OK;
}
default:
return PHP_STREAM_OPTION_RETURN_NOTIMPL;
}
}
/* }}} */
| 165,476 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::CancelPairing() {
if (!RunPairingCallbacks(CANCELLED)) {
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
CancelPairing(
object_path_,
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError,
weak_ptr_factory_.GetWeakPtr()));
UnregisterAgent();
}
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::CancelPairing() {
if (!pairing_context_.get() || !pairing_context_->CancelPairing()) {
VLOG(1) << object_path_.value() << ": No pairing context or callback. "
<< "Sending explicit cancel";
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
CancelPairing(
object_path_,
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError,
weak_ptr_factory_.GetWeakPtr()));
// delegate is going to be freed before things complete, so clear out the
// context holding it.
pairing_context_.reset();
}
}
| 171,219 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gsm_xsmp_client_disconnect (GsmXSMPClient *client)
{
if (client->priv->watch_id > 0) {
g_source_remove (client->priv->watch_id);
}
if (client->priv->conn != NULL) {
SmsCleanUp (client->priv->conn);
}
if (client->priv->ice_connection != NULL) {
IceSetShutdownNegotiation (client->priv->ice_connection, FALSE);
IceCloseConnection (client->priv->ice_connection);
}
if (client->priv->protocol_timeout > 0) {
g_source_remove (client->priv->protocol_timeout);
}
}
Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211
CWE ID: CWE-835 | gsm_xsmp_client_disconnect (GsmXSMPClient *client)
{
if (client->priv->watch_id > 0) {
g_source_remove (client->priv->watch_id);
}
if (client->priv->conn != NULL) {
SmsCleanUp (client->priv->conn);
}
if (client->priv->ice_connection != NULL) {
IceSetShutdownNegotiation (client->priv->ice_connection, FALSE);
IceCloseConnection (client->priv->ice_connection);
}
}
| 168,050 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gplotMakeOutput(GPLOT *gplot)
{
char buf[L_BUF_SIZE];
char *cmdname;
l_int32 ignore;
PROCNAME("gplotMakeOutput");
if (!gplot)
return ERROR_INT("gplot not defined", procName, 1);
gplotGenCommandFile(gplot);
gplotGenDataFiles(gplot);
cmdname = genPathname(gplot->cmdname, NULL);
#ifndef _WIN32
snprintf(buf, L_BUF_SIZE, "gnuplot %s", cmdname);
#else
snprintf(buf, L_BUF_SIZE, "wgnuplot %s", cmdname);
#endif /* _WIN32 */
#ifndef OS_IOS /* iOS 11 does not support system() */
ignore = system(buf); /* gnuplot || wgnuplot */
#endif /* !OS_IOS */
LEPT_FREE(cmdname);
return 0;
}
Commit Message: Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().
CWE ID: CWE-119 | gplotMakeOutput(GPLOT *gplot)
{
char buf[L_BUFSIZE];
char *cmdname;
l_int32 ignore;
PROCNAME("gplotMakeOutput");
if (!gplot)
return ERROR_INT("gplot not defined", procName, 1);
gplotGenCommandFile(gplot);
gplotGenDataFiles(gplot);
cmdname = genPathname(gplot->cmdname, NULL);
#ifndef _WIN32
snprintf(buf, L_BUFSIZE, "gnuplot %s", cmdname);
#else
snprintf(buf, L_BUFSIZE, "wgnuplot %s", cmdname);
#endif /* _WIN32 */
#ifndef OS_IOS /* iOS 11 does not support system() */
ignore = system(buf); /* gnuplot || wgnuplot */
#endif /* !OS_IOS */
LEPT_FREE(cmdname);
return 0;
}
| 169,326 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int btif_hl_select_wake_reset(void){
char sig_recv = 0;
BTIF_TRACE_DEBUG("btif_hl_select_wake_reset");
recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL);
return(int)sig_recv;
}
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 inline int btif_hl_select_wake_reset(void){
char sig_recv = 0;
BTIF_TRACE_DEBUG("btif_hl_select_wake_reset");
TEMP_FAILURE_RETRY(recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL));
return(int)sig_recv;
}
| 173,443 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(imagegammacorrect)
{
zval *IM;
gdImagePtr im;
int i;
double input, output;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (gdImageTrueColor(im)) {
int x, y, c;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
c = gdImageGetPixel(im, x, y);
gdImageSetPixel(im, x, y,
gdTrueColorAlpha(
(int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5),
gdTrueColorGetAlpha(c)
)
);
}
}
RETURN_TRUE;
}
for (i = 0; i < gdImageColorsTotal(im); i++) {
im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5);
}
RETURN_TRUE;
}
Commit Message: Fix bug #72730 - imagegammacorrect allows arbitrary write access
CWE ID: CWE-787 | PHP_FUNCTION(imagegammacorrect)
{
zval *IM;
gdImagePtr im;
int i;
double input, output;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) {
return;
}
if ( input <= 0.0 || output <= 0.0 ) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Gamma values should be positive");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (gdImageTrueColor(im)) {
int x, y, c;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
c = gdImageGetPixel(im, x, y);
gdImageSetPixel(im, x, y,
gdTrueColorAlpha(
(int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5),
gdTrueColorGetAlpha(c)
)
);
}
}
RETURN_TRUE;
}
for (i = 0; i < gdImageColorsTotal(im); i++) {
im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5);
}
RETURN_TRUE;
}
| 166,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: hstore_recv(PG_FUNCTION_ARGS)
{
int32 buflen;
HStore *out;
Pairs *pairs;
int32 i;
int32 pcount;
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
pcount = pq_getmsgint(buf, 4);
if (pcount == 0)
{
out = hstorePairs(NULL, 0, 0);
PG_RETURN_POINTER(out);
}
pairs = palloc(pcount * sizeof(Pairs));
for (i = 0; i < pcount; ++i)
{
int rawlen = pq_getmsgint(buf, 4);
int len;
if (rawlen < 0)
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null value not allowed for hstore key")));
pairs[i].key = pq_getmsgtext(buf, rawlen, &len);
pairs[i].keylen = hstoreCheckKeyLen(len);
pairs[i].needfree = true;
rawlen = pq_getmsgint(buf, 4);
if (rawlen < 0)
{
pairs[i].val = NULL;
pairs[i].vallen = 0;
pairs[i].isnull = true;
}
else
{
pairs[i].val = pq_getmsgtext(buf, rawlen, &len);
pairs[i].vallen = hstoreCheckValLen(len);
pairs[i].isnull = false;
}
}
pcount = hstoreUniquePairs(pairs, pcount, &buflen);
out = hstorePairs(pairs, pcount, buflen);
PG_RETURN_POINTER(out);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | hstore_recv(PG_FUNCTION_ARGS)
{
int32 buflen;
HStore *out;
Pairs *pairs;
int32 i;
int32 pcount;
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
pcount = pq_getmsgint(buf, 4);
if (pcount == 0)
{
out = hstorePairs(NULL, 0, 0);
PG_RETURN_POINTER(out);
}
if (pcount < 0 || pcount > MaxAllocSize / sizeof(Pairs))
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
pcount, (int) (MaxAllocSize / sizeof(Pairs)))));
pairs = palloc(pcount * sizeof(Pairs));
for (i = 0; i < pcount; ++i)
{
int rawlen = pq_getmsgint(buf, 4);
int len;
if (rawlen < 0)
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null value not allowed for hstore key")));
pairs[i].key = pq_getmsgtext(buf, rawlen, &len);
pairs[i].keylen = hstoreCheckKeyLen(len);
pairs[i].needfree = true;
rawlen = pq_getmsgint(buf, 4);
if (rawlen < 0)
{
pairs[i].val = NULL;
pairs[i].vallen = 0;
pairs[i].isnull = true;
}
else
{
pairs[i].val = pq_getmsgtext(buf, rawlen, &len);
pairs[i].vallen = hstoreCheckValLen(len);
pairs[i].isnull = false;
}
}
pcount = hstoreUniquePairs(pairs, pcount, &buflen);
out = hstorePairs(pairs, pcount, buflen);
PG_RETURN_POINTER(out);
}
| 166,399 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t optsize (lua_State *L, char opt, const char **fmt) {
switch (opt) {
case 'B': case 'b': return sizeof(char);
case 'H': case 'h': return sizeof(short);
case 'L': case 'l': return sizeof(long);
case 'T': return sizeof(size_t);
case 'f': return sizeof(float);
case 'd': return sizeof(double);
case 'x': return 1;
case 'c': return getnum(L, fmt, 1);
case 'i': case 'I': {
int sz = getnum(L, fmt, sizeof(int));
if (sz > MAXINTSIZE)
luaL_error(L, "integral size %d is larger than limit of %d",
sz, MAXINTSIZE);
return sz;
}
default: return 0; /* other cases do not need alignment */
}
}
Commit Message: Security: update Lua struct package for security.
During an auditing Apple found that the "struct" Lua package
we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains
a security problem. A bound-checking statement fails because of integer
overflow. The bug exists since we initially integrated this package with
Lua, when scripting was introduced, so every version of Redis with
EVAL/EVALSHA capabilities exposed is affected.
Instead of just fixing the bug, the library was updated to the latest
version shipped by the author.
CWE ID: CWE-190 | static size_t optsize (lua_State *L, char opt, const char **fmt) {
switch (opt) {
case 'B': case 'b': return sizeof(char);
case 'H': case 'h': return sizeof(short);
case 'L': case 'l': return sizeof(long);
case 'T': return sizeof(size_t);
case 'f': return sizeof(float);
case 'd': return sizeof(double);
case 'x': return 1;
case 'c': return getnum(fmt, 1);
case 'i': case 'I': {
int sz = getnum(fmt, sizeof(int));
if (sz > MAXINTSIZE)
luaL_error(L, "integral size %d is larger than limit of %d",
sz, MAXINTSIZE);
return sz;
}
default: return 0; /* other cases do not need alignment */
}
}
| 170,166 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ClearActiveTab() {
active_tab_->permissions_data()->ClearTabSpecificPermissions(kTabId);
}
Commit Message: Call CanCaptureVisiblePage in page capture API.
Currently the pageCapture permission allows access
to arbitrary local files and chrome:// pages which
can be a security concern. In order to address this,
the page capture API needs to be changed similar to
the captureVisibleTab API. The API will now only allow
extensions to capture otherwise-restricted URLs if the
user has granted activeTab. In addition, file:// URLs are
only capturable with the "Allow on file URLs" option enabled.
Bug: 893087
Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624
Reviewed-on: https://chromium-review.googlesource.com/c/1330689
Commit-Queue: Bettina Dea <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Varun Khaneja <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615248}
CWE ID: CWE-20 | void ClearActiveTab() {
void ClearActiveTab(const Extension& extension) {
extension.permissions_data()->ClearTabSpecificPermissions(kTabId);
}
| 173,007 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(DirectoryIterator, valid)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0');
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(DirectoryIterator, valid)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0');
}
| 167,030 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NavigateToUrlWithEdge(const base::string16& url) {
base::string16 protocol_url = L"microsoft-edge:" + url;
SHELLEXECUTEINFO info = { sizeof(info) };
info.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI;
info.lpVerb = L"open";
info.lpFile = protocol_url.c_str();
info.nShow = SW_SHOWNORMAL;
if (::ShellExecuteEx(&info))
return true;
PLOG(ERROR) << "Failed to launch Edge for uninstall survey";
return false;
}
Commit Message: Remove use of SEE_MASK_FLAG_NO_UI from Chrome Windows installer.
This flag was originally added to ui::base::win to suppress a specific
error message when attempting to open a file via the shell using the
"open" verb. The flag has additional side-effects and shouldn't be used
when invoking ShellExecute().
[email protected]
Bug: 819809
Change-Id: I7db2344982dd206c85a73928e906c21e06a47a9e
Reviewed-on: https://chromium-review.googlesource.com/966964
Commit-Queue: Greg Thompson <[email protected]>
Reviewed-by: Greg Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#544012}
CWE ID: CWE-20 | bool NavigateToUrlWithEdge(const base::string16& url) {
base::string16 protocol_url = L"microsoft-edge:" + url;
SHELLEXECUTEINFO info = { sizeof(info) };
info.fMask = SEE_MASK_NOASYNC;
info.lpVerb = L"open";
info.lpFile = protocol_url.c_str();
info.nShow = SW_SHOWNORMAL;
if (::ShellExecuteEx(&info))
return true;
PLOG(ERROR) << "Failed to launch Edge for uninstall survey";
return false;
}
| 172,793 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ResourceLoader::WillFollowRedirect(
const WebURL& new_url,
const WebURL& new_site_for_cookies,
const WebString& new_referrer,
WebReferrerPolicy new_referrer_policy,
const WebString& new_method,
const WebURLResponse& passed_redirect_response,
bool& report_raw_headers) {
DCHECK(!passed_redirect_response.IsNull());
if (is_cache_aware_loading_activated_) {
HandleError(
ResourceError::CacheMissError(resource_->LastResourceRequest().Url()));
return false;
}
const ResourceRequest& last_request = resource_->LastResourceRequest();
ResourceRequest new_request(new_url);
new_request.SetSiteForCookies(new_site_for_cookies);
new_request.SetDownloadToFile(last_request.DownloadToFile());
new_request.SetUseStreamOnResponse(last_request.UseStreamOnResponse());
new_request.SetRequestContext(last_request.GetRequestContext());
new_request.SetFrameType(last_request.GetFrameType());
new_request.SetServiceWorkerMode(
passed_redirect_response.WasFetchedViaServiceWorker()
? WebURLRequest::ServiceWorkerMode::kAll
: WebURLRequest::ServiceWorkerMode::kNone);
new_request.SetShouldResetAppCache(last_request.ShouldResetAppCache());
new_request.SetFetchRequestMode(last_request.GetFetchRequestMode());
new_request.SetFetchCredentialsMode(last_request.GetFetchCredentialsMode());
new_request.SetKeepalive(last_request.GetKeepalive());
String referrer =
new_referrer.IsEmpty() ? Referrer::NoReferrer() : String(new_referrer);
new_request.SetHTTPReferrer(
Referrer(referrer, static_cast<ReferrerPolicy>(new_referrer_policy)));
new_request.SetPriority(last_request.Priority());
new_request.SetHTTPMethod(new_method);
if (new_request.HttpMethod() == last_request.HttpMethod())
new_request.SetHTTPBody(last_request.HttpBody());
new_request.SetCheckForBrowserSideNavigation(
last_request.CheckForBrowserSideNavigation());
Resource::Type resource_type = resource_->GetType();
const ResourceRequest& initial_request = resource_->GetResourceRequest();
WebURLRequest::RequestContext request_context =
initial_request.GetRequestContext();
WebURLRequest::FrameType frame_type = initial_request.GetFrameType();
WebURLRequest::FetchRequestMode fetch_request_mode =
initial_request.GetFetchRequestMode();
WebURLRequest::FetchCredentialsMode fetch_credentials_mode =
initial_request.GetFetchCredentialsMode();
const ResourceLoaderOptions& options = resource_->Options();
const ResourceResponse& redirect_response(
passed_redirect_response.ToResourceResponse());
new_request.SetRedirectStatus(
ResourceRequest::RedirectStatus::kFollowedRedirect);
if (!IsManualRedirectFetchRequest(initial_request)) {
bool unused_preload = resource_->IsUnusedPreload();
SecurityViolationReportingPolicy reporting_policy =
unused_preload ? SecurityViolationReportingPolicy::kSuppressReporting
: SecurityViolationReportingPolicy::kReport;
Context().CheckCSPForRequest(
request_context, new_url, options, reporting_policy,
ResourceRequest::RedirectStatus::kFollowedRedirect);
ResourceRequestBlockedReason blocked_reason = Context().CanRequest(
resource_type, new_request, new_url, options, reporting_policy,
FetchParameters::kUseDefaultOriginRestrictionForType,
ResourceRequest::RedirectStatus::kFollowedRedirect);
if (blocked_reason != ResourceRequestBlockedReason::kNone) {
CancelForRedirectAccessCheckError(new_url, blocked_reason);
return false;
}
if (options.cors_handling_by_resource_fetcher ==
kEnableCORSHandlingByResourceFetcher &&
fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) {
RefPtr<SecurityOrigin> source_origin = options.security_origin;
if (!source_origin.get())
source_origin = Context().GetSecurityOrigin();
WebSecurityOrigin source_web_origin(source_origin.get());
WrappedResourceRequest new_request_wrapper(new_request);
WebString cors_error_msg;
if (!WebCORS::HandleRedirect(
source_web_origin, new_request_wrapper, redirect_response.Url(),
redirect_response.HttpStatusCode(),
redirect_response.HttpHeaderFields(), fetch_credentials_mode,
resource_->MutableOptions(), cors_error_msg)) {
resource_->SetCORSStatus(CORSStatus::kFailed);
if (!unused_preload) {
Context().AddErrorConsoleMessage(cors_error_msg,
FetchContext::kJSSource);
}
CancelForRedirectAccessCheckError(new_url,
ResourceRequestBlockedReason::kOther);
return false;
}
source_origin = source_web_origin;
}
if (resource_type == Resource::kImage &&
fetcher_->ShouldDeferImageLoad(new_url)) {
CancelForRedirectAccessCheckError(new_url,
ResourceRequestBlockedReason::kOther);
return false;
}
}
bool cross_origin =
!SecurityOrigin::AreSameSchemeHostPort(redirect_response.Url(), new_url);
fetcher_->RecordResourceTimingOnRedirect(resource_.Get(), redirect_response,
cross_origin);
if (options.cors_handling_by_resource_fetcher ==
kEnableCORSHandlingByResourceFetcher &&
fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) {
bool allow_stored_credentials = false;
switch (fetch_credentials_mode) {
case WebURLRequest::kFetchCredentialsModeOmit:
break;
case WebURLRequest::kFetchCredentialsModeSameOrigin:
allow_stored_credentials = !options.cors_flag;
break;
case WebURLRequest::kFetchCredentialsModeInclude:
case WebURLRequest::kFetchCredentialsModePassword:
allow_stored_credentials = true;
break;
}
new_request.SetAllowStoredCredentials(allow_stored_credentials);
}
Context().PrepareRequest(new_request,
FetchContext::RedirectType::kForRedirect);
Context().DispatchWillSendRequest(resource_->Identifier(), new_request,
redirect_response, options.initiator_info);
DCHECK(KURL(new_site_for_cookies) == new_request.SiteForCookies());
DCHECK_EQ(new_request.GetRequestContext(), request_context);
DCHECK_EQ(new_request.GetFrameType(), frame_type);
DCHECK_EQ(new_request.GetFetchRequestMode(), fetch_request_mode);
DCHECK_EQ(new_request.GetFetchCredentialsMode(), fetch_credentials_mode);
if (new_request.Url() != KURL(new_url)) {
CancelForRedirectAccessCheckError(new_request.Url(),
ResourceRequestBlockedReason::kOther);
return false;
}
if (!resource_->WillFollowRedirect(new_request, redirect_response)) {
CancelForRedirectAccessCheckError(new_request.Url(),
ResourceRequestBlockedReason::kOther);
return false;
}
report_raw_headers = new_request.ReportRawHeaders();
return true;
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | bool ResourceLoader::WillFollowRedirect(
const WebURL& new_url,
const WebURL& new_site_for_cookies,
const WebString& new_referrer,
WebReferrerPolicy new_referrer_policy,
const WebString& new_method,
const WebURLResponse& passed_redirect_response,
bool& report_raw_headers) {
DCHECK(!passed_redirect_response.IsNull());
if (is_cache_aware_loading_activated_) {
HandleError(
ResourceError::CacheMissError(resource_->LastResourceRequest().Url()));
return false;
}
const ResourceRequest& last_request = resource_->LastResourceRequest();
ResourceRequest new_request(new_url);
new_request.SetSiteForCookies(new_site_for_cookies);
new_request.SetDownloadToFile(last_request.DownloadToFile());
new_request.SetUseStreamOnResponse(last_request.UseStreamOnResponse());
new_request.SetRequestContext(last_request.GetRequestContext());
new_request.SetFrameType(last_request.GetFrameType());
new_request.SetServiceWorkerMode(
passed_redirect_response.WasFetchedViaServiceWorker()
? WebURLRequest::ServiceWorkerMode::kAll
: WebURLRequest::ServiceWorkerMode::kNone);
new_request.SetShouldResetAppCache(last_request.ShouldResetAppCache());
new_request.SetFetchRequestMode(last_request.GetFetchRequestMode());
new_request.SetFetchCredentialsMode(last_request.GetFetchCredentialsMode());
new_request.SetKeepalive(last_request.GetKeepalive());
String referrer =
new_referrer.IsEmpty() ? Referrer::NoReferrer() : String(new_referrer);
new_request.SetHTTPReferrer(
Referrer(referrer, static_cast<ReferrerPolicy>(new_referrer_policy)));
new_request.SetPriority(last_request.Priority());
new_request.SetHTTPMethod(new_method);
if (new_request.HttpMethod() == last_request.HttpMethod())
new_request.SetHTTPBody(last_request.HttpBody());
new_request.SetCheckForBrowserSideNavigation(
last_request.CheckForBrowserSideNavigation());
Resource::Type resource_type = resource_->GetType();
const ResourceRequest& initial_request = resource_->GetResourceRequest();
WebURLRequest::RequestContext request_context =
initial_request.GetRequestContext();
WebURLRequest::FrameType frame_type = initial_request.GetFrameType();
WebURLRequest::FetchRequestMode fetch_request_mode =
initial_request.GetFetchRequestMode();
WebURLRequest::FetchCredentialsMode fetch_credentials_mode =
initial_request.GetFetchCredentialsMode();
const ResourceLoaderOptions& options = resource_->Options();
const ResourceResponse& redirect_response(
passed_redirect_response.ToResourceResponse());
new_request.SetRedirectStatus(
ResourceRequest::RedirectStatus::kFollowedRedirect);
if (!IsManualRedirectFetchRequest(initial_request)) {
bool unused_preload = resource_->IsUnusedPreload();
SecurityViolationReportingPolicy reporting_policy =
unused_preload ? SecurityViolationReportingPolicy::kSuppressReporting
: SecurityViolationReportingPolicy::kReport;
Context().CheckCSPForRequest(
request_context, new_url, options, reporting_policy,
ResourceRequest::RedirectStatus::kFollowedRedirect);
ResourceRequestBlockedReason blocked_reason = Context().CanRequest(
resource_type, new_request, new_url, options, reporting_policy,
FetchParameters::kUseDefaultOriginRestrictionForType,
ResourceRequest::RedirectStatus::kFollowedRedirect);
if (blocked_reason != ResourceRequestBlockedReason::kNone) {
CancelForRedirectAccessCheckError(new_url, blocked_reason);
return false;
}
if (options.cors_handling_by_resource_fetcher ==
kEnableCORSHandlingByResourceFetcher &&
fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) {
RefPtr<SecurityOrigin> source_origin = options.security_origin;
if (!source_origin.get())
source_origin = Context().GetSecurityOrigin();
WebSecurityOrigin source_web_origin(source_origin.get());
WrappedResourceRequest new_request_wrapper(new_request);
WebString cors_error_msg;
if (!WebCORS::HandleRedirect(
source_web_origin, new_request_wrapper, redirect_response.Url(),
redirect_response.HttpStatusCode(),
redirect_response.HttpHeaderFields(), fetch_credentials_mode,
resource_->MutableOptions(), cors_error_msg)) {
resource_->SetCORSStatus(CORSStatus::kFailed);
if (!unused_preload) {
Context().AddErrorConsoleMessage(cors_error_msg,
FetchContext::kJSSource);
}
CancelForRedirectAccessCheckError(new_url,
ResourceRequestBlockedReason::kOther);
return false;
}
source_origin = source_web_origin;
}
if (resource_type == Resource::kImage &&
fetcher_->ShouldDeferImageLoad(new_url)) {
CancelForRedirectAccessCheckError(new_url,
ResourceRequestBlockedReason::kOther);
return false;
}
}
bool cross_origin =
!SecurityOrigin::AreSameSchemeHostPort(redirect_response.Url(), new_url);
fetcher_->RecordResourceTimingOnRedirect(resource_.Get(), redirect_response,
cross_origin);
if (options.cors_handling_by_resource_fetcher ==
kEnableCORSHandlingByResourceFetcher &&
fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) {
bool allow_stored_credentials = false;
switch (fetch_credentials_mode) {
case WebURLRequest::kFetchCredentialsModeOmit:
break;
case WebURLRequest::kFetchCredentialsModeSameOrigin:
allow_stored_credentials = !options.cors_flag;
break;
case WebURLRequest::kFetchCredentialsModeInclude:
case WebURLRequest::kFetchCredentialsModePassword:
allow_stored_credentials = true;
break;
}
new_request.SetAllowStoredCredentials(allow_stored_credentials);
}
Context().PrepareRequest(new_request,
FetchContext::RedirectType::kForRedirect);
Context().DispatchWillSendRequest(resource_->Identifier(), new_request,
redirect_response, resource_->GetType(),
options.initiator_info);
DCHECK(KURL(new_site_for_cookies) == new_request.SiteForCookies());
DCHECK_EQ(new_request.GetRequestContext(), request_context);
DCHECK_EQ(new_request.GetFrameType(), frame_type);
DCHECK_EQ(new_request.GetFetchRequestMode(), fetch_request_mode);
DCHECK_EQ(new_request.GetFetchCredentialsMode(), fetch_credentials_mode);
if (new_request.Url() != KURL(new_url)) {
CancelForRedirectAccessCheckError(new_request.Url(),
ResourceRequestBlockedReason::kOther);
return false;
}
if (!resource_->WillFollowRedirect(new_request, redirect_response)) {
CancelForRedirectAccessCheckError(new_request.Url(),
ResourceRequestBlockedReason::kOther);
return false;
}
report_raw_headers = new_request.ReportRawHeaders();
return true;
}
| 172,480 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TestFeaturesNativeHandler::TestFeaturesNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("GetAPIFeatures",
base::Bind(&TestFeaturesNativeHandler::GetAPIFeatures,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | TestFeaturesNativeHandler::TestFeaturesNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("GetAPIFeatures", "test",
base::Bind(&TestFeaturesNativeHandler::GetAPIFeatures,
base::Unretained(this)));
}
| 172,254 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION( msgfmt_format_message )
{
zval *args;
UChar *spattern = NULL;
int spattern_len = 0;
char *pattern = NULL;
int pattern_len = 0;
const char *slocale = NULL;
int slocale_len = 0;
MessageFormatter_object mf = {0};
MessageFormatter_object *mfo = &mf;
/* Parse parameters. */
if( zend_parse_method_parameters( ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "ssa",
&slocale, &slocale_len, &pattern, &pattern_len, &args ) == FAILURE )
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"msgfmt_format_message: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
msgformat_data_init(&mfo->mf_data TSRMLS_CC);
if(pattern && pattern_len) {
intl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo));
if( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) )
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"msgfmt_format_message: error converting pattern to UTF-16", 0 TSRMLS_CC );
RETURN_FALSE;
}
} else {
spattern_len = 0;
spattern = NULL;
}
if(slocale_len == 0) {
slocale = intl_locale_get_default(TSRMLS_C);
}
#ifdef MSG_FORMAT_QUOTE_APOS
if(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) {
intl_error_set( NULL, U_INVALID_FORMAT_ERROR,
"msgfmt_format_message: error converting pattern to quote-friendly format", 0 TSRMLS_CC );
RETURN_FALSE;
}
#endif
/* Create an ICU message formatter. */
MSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo));
if(spattern && spattern_len) {
efree(spattern);
}
INTL_METHOD_CHECK_STATUS(mfo, "Creating message formatter failed");
msgfmt_do_format(mfo, args, return_value TSRMLS_CC);
/* drop the temporary formatter */
msgformat_data_free(&mfo->mf_data TSRMLS_CC);
}
Commit Message: Fix bug #73007: add locale length check
CWE ID: CWE-119 | PHP_FUNCTION( msgfmt_format_message )
{
zval *args;
UChar *spattern = NULL;
int spattern_len = 0;
char *pattern = NULL;
int pattern_len = 0;
const char *slocale = NULL;
int slocale_len = 0;
MessageFormatter_object mf = {0};
MessageFormatter_object *mfo = &mf;
/* Parse parameters. */
if( zend_parse_method_parameters( ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "ssa",
&slocale, &slocale_len, &pattern, &pattern_len, &args ) == FAILURE )
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"msgfmt_format_message: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
INTL_CHECK_LOCALE_LEN(slocale_len);
msgformat_data_init(&mfo->mf_data TSRMLS_CC);
if(pattern && pattern_len) {
intl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo));
if( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) )
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"msgfmt_format_message: error converting pattern to UTF-16", 0 TSRMLS_CC );
RETURN_FALSE;
}
} else {
spattern_len = 0;
spattern = NULL;
}
if(slocale_len == 0) {
slocale = intl_locale_get_default(TSRMLS_C);
}
#ifdef MSG_FORMAT_QUOTE_APOS
if(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) {
intl_error_set( NULL, U_INVALID_FORMAT_ERROR,
"msgfmt_format_message: error converting pattern to quote-friendly format", 0 TSRMLS_CC );
RETURN_FALSE;
}
#endif
/* Create an ICU message formatter. */
MSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo));
if(spattern && spattern_len) {
efree(spattern);
}
INTL_METHOD_CHECK_STATUS(mfo, "Creating message formatter failed");
msgfmt_do_format(mfo, args, return_value TSRMLS_CC);
/* drop the temporary formatter */
msgformat_data_free(&mfo->mf_data TSRMLS_CC);
}
| 166,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: VOID ixheaacd_esbr_radix4bfly(const WORD32 *w, WORD32 *x, WORD32 index1,
WORD32 index) {
int i;
WORD32 l1, l2, h2, fft_jmp;
WORD32 xt0_0, yt0_0, xt1_0, yt1_0, xt2_0, yt2_0;
WORD32 xh0_0, xh1_0, xh20_0, xh21_0, xl0_0, xl1_0, xl20_0, xl21_0;
WORD32 x_0, x_1, x_l1_0, x_l1_1, x_l2_0, x_l2_1;
WORD32 x_h2_0, x_h2_1;
WORD32 si10, si20, si30, co10, co20, co30;
WORD64 mul_1, mul_2, mul_3, mul_4, mul_5, mul_6;
WORD64 mul_7, mul_8, mul_9, mul_10, mul_11, mul_12;
WORD32 *x_l1;
WORD32 *x_l2;
WORD32 *x_h2;
const WORD32 *w_ptr = w;
WORD32 i1;
h2 = index << 1;
l1 = index << 2;
l2 = (index << 2) + (index << 1);
x_l1 = &(x[l1]);
x_l2 = &(x[l2]);
x_h2 = &(x[h2]);
fft_jmp = 6 * (index);
for (i1 = 0; i1 < index1; i1++) {
for (i = 0; i < index; i++) {
si10 = (*w_ptr++);
co10 = (*w_ptr++);
si20 = (*w_ptr++);
co20 = (*w_ptr++);
si30 = (*w_ptr++);
co30 = (*w_ptr++);
x_0 = x[0];
x_h2_0 = x[h2];
x_l1_0 = x[l1];
x_l2_0 = x[l2];
xh0_0 = x_0 + x_l1_0;
xl0_0 = x_0 - x_l1_0;
xh20_0 = x_h2_0 + x_l2_0;
xl20_0 = x_h2_0 - x_l2_0;
x[0] = xh0_0 + xh20_0;
xt0_0 = xh0_0 - xh20_0;
x_1 = x[1];
x_h2_1 = x[h2 + 1];
x_l1_1 = x[l1 + 1];
x_l2_1 = x[l2 + 1];
xh1_0 = x_1 + x_l1_1;
xl1_0 = x_1 - x_l1_1;
xh21_0 = x_h2_1 + x_l2_1;
xl21_0 = x_h2_1 - x_l2_1;
x[1] = xh1_0 + xh21_0;
yt0_0 = xh1_0 - xh21_0;
xt1_0 = xl0_0 + xl21_0;
xt2_0 = xl0_0 - xl21_0;
yt2_0 = xl1_0 + xl20_0;
yt1_0 = xl1_0 - xl20_0;
mul_11 = ixheaacd_mult64(xt2_0, co30);
mul_3 = ixheaacd_mult64(yt2_0, si30);
x[l2] = (WORD32)((mul_3 + mul_11) >> 32) << RADIXSHIFT;
mul_5 = ixheaacd_mult64(xt2_0, si30);
mul_9 = ixheaacd_mult64(yt2_0, co30);
x[l2 + 1] = (WORD32)((mul_9 - mul_5) >> 32) << RADIXSHIFT;
mul_12 = ixheaacd_mult64(xt0_0, co20);
mul_2 = ixheaacd_mult64(yt0_0, si20);
x[l1] = (WORD32)((mul_2 + mul_12) >> 32) << RADIXSHIFT;
mul_6 = ixheaacd_mult64(xt0_0, si20);
mul_8 = ixheaacd_mult64(yt0_0, co20);
x[l1 + 1] = (WORD32)((mul_8 - mul_6) >> 32) << RADIXSHIFT;
mul_4 = ixheaacd_mult64(xt1_0, co10);
mul_1 = ixheaacd_mult64(yt1_0, si10);
x[h2] = (WORD32)((mul_1 + mul_4) >> 32) << RADIXSHIFT;
mul_10 = ixheaacd_mult64(xt1_0, si10);
mul_7 = ixheaacd_mult64(yt1_0, co10);
x[h2 + 1] = (WORD32)((mul_7 - mul_10) >> 32) << RADIXSHIFT;
x += 2;
}
x += fft_jmp;
w_ptr = w_ptr - fft_jmp;
}
}
Commit Message: Fix for stack corruption in esbr
Bug: 110769924
Test: poc from bug before/after
Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e
(cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a)
(cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50)
CWE ID: CWE-787 | VOID ixheaacd_esbr_radix4bfly(const WORD32 *w, WORD32 *x, WORD32 index1,
WORD32 index) {
int i;
WORD32 l1, l2, h2, fft_jmp;
WORD64 xt0_0, yt0_0, xt1_0, yt1_0, xt2_0, yt2_0;
WORD64 xh0_0, xh1_0, xh20_0, xh21_0, xl0_0, xl1_0, xl20_0, xl21_0;
WORD32 x_0, x_1, x_l1_0, x_l1_1, x_l2_0, x_l2_1;
WORD32 x_h2_0, x_h2_1;
WORD32 si10, si20, si30, co10, co20, co30;
WORD64 mul_1, mul_2, mul_3, mul_4, mul_5, mul_6;
WORD64 mul_7, mul_8, mul_9, mul_10, mul_11, mul_12;
WORD32 *x_l1;
WORD32 *x_l2;
WORD32 *x_h2;
const WORD32 *w_ptr = w;
WORD32 i1;
h2 = index << 1;
l1 = index << 2;
l2 = (index << 2) + (index << 1);
x_l1 = &(x[l1]);
x_l2 = &(x[l2]);
x_h2 = &(x[h2]);
fft_jmp = 6 * (index);
for (i1 = 0; i1 < index1; i1++) {
for (i = 0; i < index; i++) {
si10 = (*w_ptr++);
co10 = (*w_ptr++);
si20 = (*w_ptr++);
co20 = (*w_ptr++);
si30 = (*w_ptr++);
co30 = (*w_ptr++);
x_0 = x[0];
x_h2_0 = x[h2];
x_l1_0 = x[l1];
x_l2_0 = x[l2];
xh0_0 = (WORD64)x_0 + (WORD64)x_l1_0;
xl0_0 = (WORD64)x_0 - (WORD64)x_l1_0;
xh20_0 = (WORD64)x_h2_0 + (WORD64)x_l2_0;
xl20_0 = (WORD64)x_h2_0 - (WORD64)x_l2_0;
x[0] = (WORD32)ixheaacd_add64_sat(xh0_0, xh20_0);
xt0_0 = (WORD64)xh0_0 - (WORD64)xh20_0;
x_1 = x[1];
x_h2_1 = x[h2 + 1];
x_l1_1 = x[l1 + 1];
x_l2_1 = x[l2 + 1];
xh1_0 = (WORD64)x_1 + (WORD64)x_l1_1;
xl1_0 = (WORD64)x_1 - (WORD64)x_l1_1;
xh21_0 = (WORD64)x_h2_1 + (WORD64)x_l2_1;
xl21_0 = (WORD64)x_h2_1 - (WORD64)x_l2_1;
x[1] = (WORD32)ixheaacd_add64_sat(xh1_0, xh21_0);
yt0_0 = (WORD64)xh1_0 - (WORD64)xh21_0;
xt1_0 = (WORD64)xl0_0 + (WORD64)xl21_0;
xt2_0 = (WORD64)xl0_0 - (WORD64)xl21_0;
yt2_0 = (WORD64)xl1_0 + (WORD64)xl20_0;
yt1_0 = (WORD64)xl1_0 - (WORD64)xl20_0;
mul_11 = ixheaacd_mult64(xt2_0, co30);
mul_3 = ixheaacd_mult64(yt2_0, si30);
x[l2] = (WORD32)((mul_3 + mul_11) >> 32) << RADIXSHIFT;
mul_5 = ixheaacd_mult64(xt2_0, si30);
mul_9 = ixheaacd_mult64(yt2_0, co30);
x[l2 + 1] = (WORD32)((mul_9 - mul_5) >> 32) << RADIXSHIFT;
mul_12 = ixheaacd_mult64(xt0_0, co20);
mul_2 = ixheaacd_mult64(yt0_0, si20);
x[l1] = (WORD32)((mul_2 + mul_12) >> 32) << RADIXSHIFT;
mul_6 = ixheaacd_mult64(xt0_0, si20);
mul_8 = ixheaacd_mult64(yt0_0, co20);
x[l1 + 1] = (WORD32)((mul_8 - mul_6) >> 32) << RADIXSHIFT;
mul_4 = ixheaacd_mult64(xt1_0, co10);
mul_1 = ixheaacd_mult64(yt1_0, si10);
x[h2] = (WORD32)((mul_1 + mul_4) >> 32) << RADIXSHIFT;
mul_10 = ixheaacd_mult64(xt1_0, si10);
mul_7 = ixheaacd_mult64(yt1_0, co10);
x[h2 + 1] = (WORD32)((mul_7 - mul_10) >> 32) << RADIXSHIFT;
x += 2;
}
x += fft_jmp;
w_ptr = w_ptr - fft_jmp;
}
}
| 174,088 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProxyChannelDelegate::ProxyChannelDelegate()
: shutdown_event_(true, false) {
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | ProxyChannelDelegate::ProxyChannelDelegate()
| 170,737 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_get_uint_32(png_bytep buf)
{
png_uint_32 i = ((png_uint_32)(*buf) << 24) +
((png_uint_32)(*(buf + 1)) << 16) +
((png_uint_32)(*(buf + 2)) << 8) +
(png_uint_32)(*(buf + 3));
return (i);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_get_uint_32(png_bytep buf)
{
png_uint_32 i = ((png_uint_32)((*(buf )) & 0xff) << 24) +
((png_uint_32)((*(buf + 1)) & 0xff) << 16) +
((png_uint_32)((*(buf + 2)) & 0xff) << 8) +
((png_uint_32)((*(buf + 3)) & 0xff) );
return (i);
}
| 172,176 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: atol8(const char *p, size_t char_cnt)
{
int64_t l;
int digit;
l = 0;
while (char_cnt-- > 0) {
if (*p >= '0' && *p <= '7')
digit = *p - '0';
else
break;
p++;
l <<= 3;
l |= digit;
}
return (l);
}
Commit Message: Do something sensible for empty strings to make fuzzers happy.
CWE ID: CWE-125 | atol8(const char *p, size_t char_cnt)
{
int64_t l;
int digit;
if (char_cnt == 0)
return (0);
l = 0;
while (char_cnt-- > 0) {
if (*p >= '0' && *p <= '7')
digit = *p - '0';
else
break;
p++;
l <<= 3;
l |= digit;
}
return (l);
}
| 167,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct file *get_empty_filp(void)
{
const struct cred *cred = current_cred();
static long old_max;
struct file *f;
int error;
/*
* Privileged users can go above max_files
*/
if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
/*
* percpu_counters are inaccurate. Do an expensive check before
* we go and fail.
*/
if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
goto over;
}
f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
if (unlikely(!f))
return ERR_PTR(-ENOMEM);
percpu_counter_inc(&nr_files);
f->f_cred = get_cred(cred);
error = security_file_alloc(f);
if (unlikely(error)) {
file_free(f);
return ERR_PTR(error);
}
INIT_LIST_HEAD(&f->f_u.fu_list);
atomic_long_set(&f->f_count, 1);
rwlock_init(&f->f_owner.lock);
spin_lock_init(&f->f_lock);
eventpoll_init_file(f);
/* f->f_version: 0 */
return f;
over:
/* Ran out of filps - report that */
if (get_nr_files() > old_max) {
pr_info("VFS: file-max limit %lu reached\n", get_max_files());
old_max = get_nr_files();
}
return ERR_PTR(-ENFILE);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | struct file *get_empty_filp(void)
{
const struct cred *cred = current_cred();
static long old_max;
struct file *f;
int error;
/*
* Privileged users can go above max_files
*/
if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
/*
* percpu_counters are inaccurate. Do an expensive check before
* we go and fail.
*/
if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
goto over;
}
f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
if (unlikely(!f))
return ERR_PTR(-ENOMEM);
percpu_counter_inc(&nr_files);
f->f_cred = get_cred(cred);
error = security_file_alloc(f);
if (unlikely(error)) {
file_free(f);
return ERR_PTR(error);
}
atomic_long_set(&f->f_count, 1);
rwlock_init(&f->f_owner.lock);
spin_lock_init(&f->f_lock);
eventpoll_init_file(f);
/* f->f_version: 0 */
return f;
over:
/* Ran out of filps - report that */
if (get_nr_files() > old_max) {
pr_info("VFS: file-max limit %lu reached\n", get_max_files());
old_max = get_nr_files();
}
return ERR_PTR(-ENFILE);
}
| 166,802 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static __u8 *sp_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 107 && rdesc[104] == 0x26 && rdesc[105] == 0x80 &&
rdesc[106] == 0x03) {
hid_info(hdev, "fixing up Sunplus Wireless Desktop report descriptor\n");
rdesc[105] = rdesc[110] = 0x03;
rdesc[106] = rdesc[111] = 0x21;
}
return rdesc;
}
Commit Message: HID: fix a couple of off-by-ones
There are a few very theoretical off-by-one bugs in report descriptor size
checking when performing a pre-parsing fixup. Fix those.
Cc: [email protected]
Reported-by: Ben Hawkes <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-119 | static __u8 *sp_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 112 && rdesc[104] == 0x26 && rdesc[105] == 0x80 &&
rdesc[106] == 0x03) {
hid_info(hdev, "fixing up Sunplus Wireless Desktop report descriptor\n");
rdesc[105] = rdesc[110] = 0x03;
rdesc[106] = rdesc[111] = 0x21;
}
return rdesc;
}
| 166,375 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BnCrypto::readVector(const Parcel &data, Vector<uint8_t> &vector) const {
uint32_t size = data.readInt32();
vector.insertAt((size_t)0, size);
data.read(vector.editArray(), size);
}
Commit Message: Fix information disclosure in mediadrmserver
Test:POC provided in bug
Bug:79218474
Change-Id: Iba12c07a5e615f8ed234b01ac53e3559ba9ac12e
(cherry picked from commit c1bf68a8d1321d7cdf7da6933f0b89b171d251c6)
CWE ID: CWE-200 | void BnCrypto::readVector(const Parcel &data, Vector<uint8_t> &vector) const {
uint32_t size = data.readInt32();
if (vector.insertAt((size_t)0, size) < 0) {
vector.clear();
}
if (data.read(vector.editArray(), size) != NO_ERROR) {
vector.clear();
android_errorWriteWithInfoLog(0x534e4554, "62872384", -1, NULL, 0);
}
}
| 174,083 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_exceptions(struct pstore *ps,
int (*callback)(void *callback_context, chunk_t old,
chunk_t new),
void *callback_context)
{
int r, full = 1;
/*
* Keeping reading chunks and inserting exceptions until
* we find a partially full area.
*/
for (ps->current_area = 0; full; ps->current_area++) {
r = area_io(ps, READ);
if (r)
return r;
r = insert_exceptions(ps, callback, callback_context, &full);
if (r)
return r;
}
ps->current_area--;
return 0;
}
Commit Message: dm snapshot: fix data corruption
This patch fixes a particular type of data corruption that has been
encountered when loading a snapshot's metadata from disk.
When we allocate a new chunk in persistent_prepare, we increment
ps->next_free and we make sure that it doesn't point to a metadata area
by further incrementing it if necessary.
When we load metadata from disk on device activation, ps->next_free is
positioned after the last used data chunk. However, if this last used
data chunk is followed by a metadata area, ps->next_free is positioned
erroneously to the metadata area. A newly-allocated chunk is placed at
the same location as the metadata area, resulting in data or metadata
corruption.
This patch changes the code so that ps->next_free skips the metadata
area when metadata are loaded in function read_exceptions.
The patch also moves a piece of code from persistent_prepare_exception
to a separate function skip_metadata to avoid code duplication.
CVE-2013-4299
Signed-off-by: Mikulas Patocka <[email protected]>
Cc: [email protected]
Cc: Mike Snitzer <[email protected]>
Signed-off-by: Alasdair G Kergon <[email protected]>
CWE ID: CWE-264 | static int read_exceptions(struct pstore *ps,
int (*callback)(void *callback_context, chunk_t old,
chunk_t new),
void *callback_context)
{
int r, full = 1;
/*
* Keeping reading chunks and inserting exceptions until
* we find a partially full area.
*/
for (ps->current_area = 0; full; ps->current_area++) {
r = area_io(ps, READ);
if (r)
return r;
r = insert_exceptions(ps, callback, callback_context, &full);
if (r)
return r;
}
ps->current_area--;
skip_metadata(ps);
return 0;
}
| 165,993 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms,
int clrspc)
{
jas_image_t *image;
uint_fast32_t rawsize;
uint_fast32_t inmem;
int cmptno;
jas_image_cmptparm_t *cmptparm;
if (!(image = jas_image_create0())) {
return 0;
}
image->clrspc_ = clrspc;
image->maxcmpts_ = numcmpts;
image->inmem_ = true;
//// image->inmem_ = true;
/* Allocate memory for the per-component information. */
if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_,
sizeof(jas_image_cmpt_t *)))) {
jas_image_destroy(image);
return 0;
}
/* Initialize in case of failure. */
for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {
image->cmpts_[cmptno] = 0;
}
/* Compute the approximate raw size of the image. */
rawsize = 0;
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
rawsize += cmptparm->width * cmptparm->height *
(cmptparm->prec + 7) / 8;
}
/* Decide whether to buffer the image data in memory, based on the
raw size of the image. */
inmem = (rawsize < JAS_IMAGE_INMEMTHRESH);
/* Create the individual image components. */
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,
cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
cmptparm->width, cmptparm->height, cmptparm->prec,
cmptparm->sgnd, inmem))) {
jas_image_destroy(image);
return 0;
}
++image->numcmpts_;
}
/* Determine the bounding box for all of the components on the
reference grid (i.e., the image area) */
jas_image_setbbox(image);
return image;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms,
int clrspc)
{
jas_image_t *image;
size_t rawsize;
uint_fast32_t inmem;
int cmptno;
jas_image_cmptparm_t *cmptparm;
image = 0;
JAS_DBGLOG(100, ("jas_image_create(%d, %p, %d)\n", numcmpts, cmptparms,
clrspc));
if (!(image = jas_image_create0())) {
goto error;
}
image->clrspc_ = clrspc;
image->maxcmpts_ = numcmpts;
//// image->inmem_ = true;
/* Allocate memory for the per-component information. */
if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_,
sizeof(jas_image_cmpt_t *)))) {
goto error;
}
/* Initialize in case of failure. */
for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {
image->cmpts_[cmptno] = 0;
}
#if 0
/* Compute the approximate raw size of the image. */
rawsize = 0;
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
rawsize += cmptparm->width * cmptparm->height *
(cmptparm->prec + 7) / 8;
}
/* Decide whether to buffer the image data in memory, based on the
raw size of the image. */
inmem = (rawsize < JAS_IMAGE_INMEMTHRESH);
#endif
/* Create the individual image components. */
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
if (!jas_safe_size_mul3(cmptparm->width, cmptparm->height,
(cmptparm->prec + 7), &rawsize)) {
goto error;
}
rawsize /= 8;
inmem = (rawsize < JAS_IMAGE_INMEMTHRESH);
if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,
cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
cmptparm->width, cmptparm->height, cmptparm->prec,
cmptparm->sgnd, inmem))) {
goto error;
}
++image->numcmpts_;
}
/* Determine the bounding box for all of the components on the
reference grid (i.e., the image area) */
jas_image_setbbox(image);
return image;
error:
if (image) {
jas_image_destroy(image);
}
return 0;
}
| 168,694 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cib_tls_signon(cib_t * cib, struct remote_connection_s *connection)
{
int sock;
cib_remote_opaque_t *private = cib->variant_opaque;
struct sockaddr_in addr;
int rc = 0;
char *server = private->server;
int ret_ga;
struct addrinfo *res;
struct addrinfo hints;
xmlNode *answer = NULL;
xmlNode *login = NULL;
static struct mainloop_fd_callbacks cib_fd_callbacks =
{
.dispatch = cib_remote_dispatch,
.destroy = cib_remote_connection_destroy,
};
connection->socket = 0;
connection->session = NULL;
/* create socket */
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) {
crm_perror(LOG_ERR, "Socket creation failed");
return -1;
}
/* getaddrinfo */
bzero(&hints, sizeof(struct addrinfo));
hints.ai_flags = AI_CANONNAME;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_RAW;
if (hints.ai_family == AF_INET6) {
hints.ai_protocol = IPPROTO_ICMPV6;
} else {
hints.ai_protocol = IPPROTO_ICMP;
}
crm_debug("Looking up %s", server);
ret_ga = getaddrinfo(server, NULL, &hints, &res);
if (ret_ga) {
crm_err("getaddrinfo: %s", gai_strerror(ret_ga));
close(sock);
return -1;
}
if (res->ai_canonname) {
server = res->ai_canonname;
}
crm_debug("Got address %s for %s", server, private->server);
if (!res->ai_addr) {
fprintf(stderr, "getaddrinfo failed");
crm_exit(1);
}
#if 1
memcpy(&addr, res->ai_addr, res->ai_addrlen);
#else
/* connect to server */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(server);
#endif
addr.sin_port = htons(private->port);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
crm_perror(LOG_ERR, "Connection to %s:%d failed", server, private->port);
close(sock);
return -1;
}
if (connection->encrypted) {
/* initialize GnuTls lib */
#ifdef HAVE_GNUTLS_GNUTLS_H
gnutls_global_init();
gnutls_anon_allocate_client_credentials(&anon_cred_c);
/* bind the socket to GnuTls lib */
connection->session = create_tls_session(sock, GNUTLS_CLIENT);
if (connection->session == NULL) {
crm_perror(LOG_ERR, "Session creation for %s:%d failed", server, private->port);
close(sock);
cib_tls_close(cib);
return -1;
}
#else
return -EPROTONOSUPPORT;
#endif
} else {
connection->session = GUINT_TO_POINTER(sock);
}
/* login to server */
login = create_xml_node(NULL, "cib_command");
crm_xml_add(login, "op", "authenticate");
crm_xml_add(login, "user", private->user);
crm_xml_add(login, "password", private->passwd);
crm_xml_add(login, "hidden", "password");
crm_send_remote_msg(connection->session, login, connection->encrypted);
free_xml(login);
answer = crm_recv_remote_msg(connection->session, connection->encrypted);
crm_log_xml_trace(answer, "Reply");
if (answer == NULL) {
rc = -EPROTO;
} else {
/* grab the token */
const char *msg_type = crm_element_value(answer, F_CIB_OPERATION);
const char *tmp_ticket = crm_element_value(answer, F_CIB_CLIENTID);
if (safe_str_neq(msg_type, CRM_OP_REGISTER)) {
crm_err("Invalid registration message: %s", msg_type);
rc = -EPROTO;
} else if (tmp_ticket == NULL) {
rc = -EPROTO;
} else {
connection->token = strdup(tmp_ticket);
}
}
if (rc != 0) {
cib_tls_close(cib);
}
connection->socket = sock;
connection->source = mainloop_add_fd("cib-remote", G_PRIORITY_HIGH, connection->socket, cib, &cib_fd_callbacks);
return rc;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_tls_signon(cib_t * cib, struct remote_connection_s *connection)
cib_tls_signon(cib_t * cib, struct remote_connection_s *connection, gboolean event_channel)
{
int sock;
cib_remote_opaque_t *private = cib->variant_opaque;
int rc = 0;
int disconnected = 0;
xmlNode *answer = NULL;
xmlNode *login = NULL;
static struct mainloop_fd_callbacks cib_fd_callbacks = { 0, };
cib_fd_callbacks.dispatch = event_channel ? cib_remote_callback_dispatch : cib_remote_command_dispatch;
cib_fd_callbacks.destroy = cib_remote_connection_destroy;
connection->socket = 0;
connection->session = NULL;
sock = crm_remote_tcp_connect(private->server, private->port);
if (sock <= 0) {
crm_perror(LOG_ERR, "remote tcp connection to %s:%d failed", private->server, private->port);
}
connection->socket = sock;
if (connection->encrypted) {
/* initialize GnuTls lib */
#ifdef HAVE_GNUTLS_GNUTLS_H
if (remote_gnutls_credentials_init == FALSE) {
gnutls_global_init();
gnutls_anon_allocate_client_credentials(&anon_cred_c);
remote_gnutls_credentials_init = TRUE;
}
/* bind the socket to GnuTls lib */
connection->session = crm_create_anon_tls_session(sock, GNUTLS_CLIENT, anon_cred_c);
if (crm_initiate_client_tls_handshake(connection->session, DEFAULT_CLIENT_HANDSHAKE_TIMEOUT) != 0) {
crm_err("Session creation for %s:%d failed", private->server, private->port);
gnutls_deinit(*connection->session);
gnutls_free(connection->session);
connection->session = NULL;
cib_tls_close(cib);
return -1;
}
#else
return -EPROTONOSUPPORT;
#endif
} else {
connection->session = GUINT_TO_POINTER(sock);
}
/* login to server */
login = create_xml_node(NULL, "cib_command");
crm_xml_add(login, "op", "authenticate");
crm_xml_add(login, "user", private->user);
crm_xml_add(login, "password", private->passwd);
crm_xml_add(login, "hidden", "password");
crm_send_remote_msg(connection->session, login, connection->encrypted);
free_xml(login);
crm_recv_remote_msg(connection->session, &connection->recv_buf, connection->encrypted, -1, &disconnected);
if (disconnected) {
rc = -ENOTCONN;
}
answer = crm_parse_remote_buffer(&connection->recv_buf);
crm_log_xml_trace(answer, "Reply");
if (answer == NULL) {
rc = -EPROTO;
} else {
/* grab the token */
const char *msg_type = crm_element_value(answer, F_CIB_OPERATION);
const char *tmp_ticket = crm_element_value(answer, F_CIB_CLIENTID);
if (safe_str_neq(msg_type, CRM_OP_REGISTER)) {
crm_err("Invalid registration message: %s", msg_type);
rc = -EPROTO;
} else if (tmp_ticket == NULL) {
rc = -EPROTO;
} else {
connection->token = strdup(tmp_ticket);
}
}
free_xml(answer);
answer = NULL;
if (rc != 0) {
cib_tls_close(cib);
return rc;
}
crm_trace("remote client connection established");
connection->source = mainloop_add_fd("cib-remote", G_PRIORITY_HIGH, connection->socket, cib, &cib_fd_callbacks);
return rc;
}
| 166,156 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1)
: mIsValid(false),
mData(NULL),
mSize(0),
mFirstFrameOffset(0),
mVersion(ID3_UNKNOWN),
mRawSize(0) {
sp<MemorySource> source = new MemorySource(data, size);
mIsValid = parseV2(source, 0);
if (!mIsValid && !ignoreV1) {
mIsValid = parseV1(source);
}
}
Commit Message: better validation lengths of strings in ID3 tags
Validate lengths on strings in ID3 tags, particularly around 0.
Also added code to handle cases when we can't get memory for
copies of strings we want to extract from these tags.
Affects L/M/N/master, same patch for all of them.
Bug: 30744884
Change-Id: I2675a817a39f0927ec1f7e9f9c09f2e61020311e
Test: play mp3 file which caused a <0 length.
(cherry picked from commit d23c01546c4f82840a01a380def76ab6cae5d43f)
CWE ID: CWE-20 | ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1)
: mIsValid(false),
mData(NULL),
mSize(0),
mFirstFrameOffset(0),
mVersion(ID3_UNKNOWN),
mRawSize(0) {
sp<MemorySource> source = new (std::nothrow) MemorySource(data, size);
if (source == NULL)
return;
mIsValid = parseV2(source, 0);
if (!mIsValid && !ignoreV1) {
mIsValid = parseV1(source);
}
}
| 173,392 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static gboolean irssi_ssl_verify(SSL *ssl, SSL_CTX *ctx, X509 *cert)
{
if (SSL_get_verify_result(ssl) != X509_V_OK) {
unsigned char md[EVP_MAX_MD_SIZE];
unsigned int n;
char *str;
g_warning("Could not verify SSL servers certificate:");
if ((str = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0)) == NULL)
g_warning(" Could not get subject-name from peer certificate");
else {
g_warning(" Subject : %s", str);
free(str);
}
if ((str = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0)) == NULL)
g_warning(" Could not get issuer-name from peer certificate");
else {
g_warning(" Issuer : %s", str);
free(str);
}
if (! X509_digest(cert, EVP_md5(), md, &n))
g_warning(" Could not get fingerprint from peer certificate");
else {
char hex[] = "0123456789ABCDEF";
char fp[EVP_MAX_MD_SIZE*3];
if (n < sizeof(fp)) {
unsigned int i;
for (i = 0; i < n; i++) {
fp[i*3+0] = hex[(md[i] >> 4) & 0xF];
fp[i*3+1] = hex[(md[i] >> 0) & 0xF];
fp[i*3+2] = i == n - 1 ? '\0' : ':';
}
g_warning(" MD5 Fingerprint : %s", fp);
}
}
return FALSE;
}
return TRUE;
}
Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to
git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564
CWE ID: CWE-20 | static gboolean irssi_ssl_verify(SSL *ssl, SSL_CTX *ctx, X509 *cert)
/* Checks if the given string has internal NUL characters. */
static gboolean has_internal_nul(const char* str, int len) {
/* Remove trailing nul characters. They would give false alarms */
while (len > 0 && str[len-1] == 0)
len--;
return strlen(str) != len;
}
/* tls_dns_name - Extract valid DNS name from subjectAltName value */
static const char *tls_dns_name(const GENERAL_NAME * gn)
{
const char *dnsname;
/* We expect the OpenSSL library to construct GEN_DNS extension objects as
ASN1_IA5STRING values. Check we got the right union member. */
if (ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING) {
g_warning("Invalid ASN1 value type in subjectAltName");
return NULL;
}
/* Safe to treat as an ASCII string possibly holding a DNS name */
dnsname = (char *) ASN1_STRING_data(gn->d.ia5);
if (has_internal_nul(dnsname, ASN1_STRING_length(gn->d.ia5))) {
g_warning("Internal NUL in subjectAltName");
return NULL;
}
return dnsname;
}
/* tls_text_name - extract certificate property value by name */
static char *tls_text_name(X509_NAME *name, int nid)
{
int pos;
X509_NAME_ENTRY *entry;
ASN1_STRING *entry_str;
int utf8_length;
unsigned char *utf8_value;
char *result;
if (name == 0 || (pos = X509_NAME_get_index_by_NID(name, nid, -1)) < 0) {
return NULL;
}
entry = X509_NAME_get_entry(name, pos);
g_return_val_if_fail(entry != NULL, NULL);
entry_str = X509_NAME_ENTRY_get_data(entry);
g_return_val_if_fail(entry_str != NULL, NULL);
/* Convert everything into UTF-8. It's up to OpenSSL to do something
reasonable when converting ASCII formats that contain non-ASCII
content. */
if ((utf8_length = ASN1_STRING_to_UTF8(&utf8_value, entry_str)) < 0) {
g_warning("Error decoding ASN.1 type=%d", ASN1_STRING_type(entry_str));
return NULL;
}
if (has_internal_nul((char *)utf8_value, utf8_length)) {
g_warning("NUL character in hostname in certificate");
OPENSSL_free(utf8_value);
return NULL;
}
result = g_strdup((char *) utf8_value);
OPENSSL_free(utf8_value);
return result;
}
/** check if a hostname in the certificate matches the hostname we used for the connection */
static gboolean match_hostname(const char *cert_hostname, const char *hostname)
{
const char *hostname_left;
if (!strcasecmp(cert_hostname, hostname)) { /* exact match */
return TRUE;
} else if (cert_hostname[0] == '*' && cert_hostname[1] == '.' && cert_hostname[2] != 0) { /* wildcard match */
/* The initial '*' matches exactly one hostname component */
hostname_left = strchr(hostname, '.');
if (hostname_left != NULL && ! strcasecmp(hostname_left + 1, cert_hostname + 2)) {
return TRUE;
}
}
return FALSE;
}
/* based on verify_extract_name from tls_client.c in postfix */
static gboolean irssi_ssl_verify_hostname(X509 *cert, const char *hostname)
{
int gen_index, gen_count;
gboolean matched = FALSE, has_dns_name = FALSE;
const char *cert_dns_name;
char *cert_subject_cn;
const GENERAL_NAME *gn;
STACK_OF(GENERAL_NAME) * gens;
/* Verify the dNSName(s) in the peer certificate against the hostname. */
gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
if (gens) {
gen_count = sk_GENERAL_NAME_num(gens);
for (gen_index = 0; gen_index < gen_count && !matched; ++gen_index) {
gn = sk_GENERAL_NAME_value(gens, gen_index);
if (gn->type != GEN_DNS)
continue;
/* Even if we have an invalid DNS name, we still ultimately
ignore the CommonName, because subjectAltName:DNS is
present (though malformed). */
has_dns_name = TRUE;
cert_dns_name = tls_dns_name(gn);
if (cert_dns_name && *cert_dns_name) {
matched = match_hostname(cert_dns_name, hostname);
}
}
/* Free stack *and* member GENERAL_NAME objects */
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
}
if (has_dns_name) {
if (! matched) {
/* The CommonName in the issuer DN is obsolete when SubjectAltName is available. */
g_warning("None of the Subject Alt Names in the certificate match hostname '%s'", hostname);
}
return matched;
} else { /* No subjectAltNames, look at CommonName */
cert_subject_cn = tls_text_name(X509_get_subject_name(cert), NID_commonName);
if (cert_subject_cn && *cert_subject_cn) {
matched = match_hostname(cert_subject_cn, hostname);
if (! matched) {
g_warning("SSL certificate common name '%s' doesn't match host name '%s'", cert_subject_cn, hostname);
}
} else {
g_warning("No subjectAltNames and no valid common name in certificate");
}
free(cert_subject_cn);
}
return matched;
}
static gboolean irssi_ssl_verify(SSL *ssl, SSL_CTX *ctx, const char* hostname, X509 *cert)
{
if (SSL_get_verify_result(ssl) != X509_V_OK) {
unsigned char md[EVP_MAX_MD_SIZE];
unsigned int n;
char *str;
g_warning("Could not verify SSL servers certificate:");
if ((str = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0)) == NULL)
g_warning(" Could not get subject-name from peer certificate");
else {
g_warning(" Subject : %s", str);
free(str);
}
if ((str = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0)) == NULL)
g_warning(" Could not get issuer-name from peer certificate");
else {
g_warning(" Issuer : %s", str);
free(str);
}
if (! X509_digest(cert, EVP_md5(), md, &n))
g_warning(" Could not get fingerprint from peer certificate");
else {
char hex[] = "0123456789ABCDEF";
char fp[EVP_MAX_MD_SIZE*3];
if (n < sizeof(fp)) {
unsigned int i;
for (i = 0; i < n; i++) {
fp[i*3+0] = hex[(md[i] >> 4) & 0xF];
fp[i*3+1] = hex[(md[i] >> 0) & 0xF];
fp[i*3+2] = i == n - 1 ? '\0' : ':';
}
g_warning(" MD5 Fingerprint : %s", fp);
}
}
return FALSE;
} else if (! irssi_ssl_verify_hostname(cert, hostname)){
return FALSE;
}
return TRUE;
}
| 165,518 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool asn1_write_BOOLEAN_context(struct asn1_data *data, bool v, int context)
{
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(context));
asn1_write_uint8(data, v ? 0xFF : 0);
asn1_pop_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399 | bool asn1_write_BOOLEAN_context(struct asn1_data *data, bool v, int context)
{
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(context))) return false;
if (!asn1_write_uint8(data, v ? 0xFF : 0)) return false;
return asn1_pop_tag(data);
}
| 164,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_uids_guids(long long *table_start)
{
int res, i;
int bytes = SQUASHFS_ID_BYTES(sBlk.s.no_ids);
int indexes = SQUASHFS_ID_BLOCKS(sBlk.s.no_ids);
long long id_index_table[indexes];
TRACE("read_uids_guids: no_ids %d\n", sBlk.s.no_ids);
id_table = malloc(bytes);
if(id_table == NULL) {
ERROR("read_uids_guids: failed to allocate id table\n");
return FALSE;
}
res = read_fs_bytes(fd, sBlk.s.id_table_start,
SQUASHFS_ID_BLOCK_BYTES(sBlk.s.no_ids), id_index_table);
if(res == FALSE) {
ERROR("read_uids_guids: failed to read id index table\n");
return FALSE;
}
SQUASHFS_INSWAP_ID_BLOCKS(id_index_table, indexes);
/*
* id_index_table[0] stores the start of the compressed id blocks.
* This by definition is also the end of the previous filesystem
* table - this may be the exports table if it is present, or the
* fragments table if it isn't.
*/
*table_start = id_index_table[0];
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
res = read_block(fd, id_index_table[i], NULL, expected,
((char *) id_table) + i * SQUASHFS_METADATA_SIZE);
if(res == FALSE) {
ERROR("read_uids_guids: failed to read id table block"
"\n");
return FALSE;
}
}
SQUASHFS_INSWAP_INTS(id_table, sBlk.s.no_ids);
return TRUE;
}
Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <[email protected]>
CWE ID: CWE-190 | static int read_uids_guids(long long *table_start)
static int read_id_table(long long *table_start)
{
/*
* Note on overflow limits:
* Size of SBlk.s.no_ids is 2^16 (unsigned short)
* Max size of bytes is 2^16*4 or 256K
* Max indexes is (2^16*4)/8K or 32
* Max length is ((2^16*4)/8K)*8 or 256
*/
int res, i;
int bytes = SQUASHFS_ID_BYTES(sBlk.s.no_ids);
int indexes = SQUASHFS_ID_BLOCKS(sBlk.s.no_ids);
int length = SQUASHFS_ID_BLOCK_BYTES(sBlk.s.no_ids);
long long *id_index_table;
/*
* The size of the index table (length bytes) should match the
* table start and end points
*/
if(length != (*table_start - sBlk.s.id_table_start)) {
ERROR("read_id_table: Bad id count in super block\n");
return FALSE;
}
TRACE("read_id_table: no_ids %d\n", sBlk.s.no_ids);
id_index_table = alloc_index_table(indexes);
id_table = malloc(bytes);
if(id_table == NULL) {
ERROR("read_id_table: failed to allocate id table\n");
return FALSE;
}
res = read_fs_bytes(fd, sBlk.s.id_table_start, length, id_index_table);
if(res == FALSE) {
ERROR("read_id_table: failed to read id index table\n");
return FALSE;
}
SQUASHFS_INSWAP_ID_BLOCKS(id_index_table, indexes);
/*
* id_index_table[0] stores the start of the compressed id blocks.
* This by definition is also the end of the previous filesystem
* table - this may be the exports table if it is present, or the
* fragments table if it isn't.
*/
*table_start = id_index_table[0];
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
res = read_block(fd, id_index_table[i], NULL, expected,
((char *) id_table) + i * SQUASHFS_METADATA_SIZE);
if(res == FALSE) {
ERROR("read_id_table: failed to read id table block"
"\n");
return FALSE;
}
}
SQUASHFS_INSWAP_INTS(id_table, sBlk.s.no_ids);
return TRUE;
}
| 168,882 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
vstart += verdef->vd_aux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
Commit Message: Fix #8743 - Crash in ELF version parser on 32bit systems
CWE ID: CWE-125 | static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
| 167,711 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_attr3_leaf_clearflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
xfs_attr_leaf_name_local_t *name_loc;
int namelen;
char *name;
#endif /* DEBUG */
trace_xfs_attr_leaf_clearflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return(error);
leaf = bp->b_addr;
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(entry->flags & XFS_ATTR_INCOMPLETE);
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
namelen = name_loc->namelen;
name = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
namelen = name_rmt->namelen;
name = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry->hashval) == args->hashval);
ASSERT(namelen == args->namelen);
ASSERT(memcmp(name, args->name, namelen) == 0);
#endif /* DEBUG */
entry->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if (args->rmtblkno) {
ASSERT((entry->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->valuelen);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll(&args->trans, args->dp);
}
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_clearflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
xfs_attr_leaf_name_local_t *name_loc;
int namelen;
char *name;
#endif /* DEBUG */
trace_xfs_attr_leaf_clearflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return(error);
leaf = bp->b_addr;
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(entry->flags & XFS_ATTR_INCOMPLETE);
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
namelen = name_loc->namelen;
name = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
namelen = name_rmt->namelen;
name = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry->hashval) == args->hashval);
ASSERT(namelen == args->namelen);
ASSERT(memcmp(name, args->name, namelen) == 0);
#endif /* DEBUG */
entry->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if (args->rmtblkno) {
ASSERT((entry->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll(&args->trans, args->dp);
}
| 166,734 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static IMFSample* CreateSampleFromInputBuffer(
const media::BitstreamBuffer& bitstream_buffer,
base::ProcessHandle renderer_process,
DWORD stream_size,
DWORD alignment) {
HANDLE shared_memory_handle = NULL;
RETURN_ON_FAILURE(::DuplicateHandle(renderer_process,
bitstream_buffer.handle(),
base::GetCurrentProcessHandle(),
&shared_memory_handle,
0,
FALSE,
DUPLICATE_SAME_ACCESS),
"Duplicate handle failed", NULL);
base::SharedMemory shm(shared_memory_handle, true);
RETURN_ON_FAILURE(shm.Map(bitstream_buffer.size()),
"Failed in base::SharedMemory::Map", NULL);
return CreateInputSample(reinterpret_cast<const uint8*>(shm.memory()),
bitstream_buffer.size(),
stream_size,
alignment);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | static IMFSample* CreateSampleFromInputBuffer(
const media::BitstreamBuffer& bitstream_buffer,
DWORD stream_size,
DWORD alignment) {
base::SharedMemory shm(bitstream_buffer.handle(), true);
RETURN_ON_FAILURE(shm.Map(bitstream_buffer.size()),
"Failed in base::SharedMemory::Map", NULL);
return CreateInputSample(reinterpret_cast<const uint8*>(shm.memory()),
bitstream_buffer.size(),
stream_size,
alignment);
}
| 170,939 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DataReductionProxyConfigServiceClient::RetrieveRemoteConfig() {
DCHECK(thread_checker_.CalledOnValidThread());
CreateClientConfigRequest request;
std::string serialized_request;
#if defined(OS_ANDROID)
request.set_telephony_network_operator(
net::android::GetTelephonyNetworkOperator());
#endif
data_reduction_proxy::ConfigDeviceInfo* device_info =
request.mutable_device_info();
device_info->set_total_device_memory_kb(
base::SysInfo::AmountOfPhysicalMemory() / 1024);
const std::string& session_key = request_options_->GetSecureSession();
if (!session_key.empty())
request.set_session_key(request_options_->GetSecureSession());
request.set_dogfood_group(
base::FeatureList::IsEnabled(features::kDogfood)
? CreateClientConfigRequest_DogfoodGroup_DOGFOOD
: CreateClientConfigRequest_DogfoodGroup_NONDOGFOOD);
data_reduction_proxy::VersionInfo* version_info =
request.mutable_version_info();
uint32_t build;
uint32_t patch;
util::GetChromiumBuildAndPatchAsInts(util::ChromiumVersion(), &build, &patch);
version_info->set_client(util::GetStringForClient(io_data_->client()));
version_info->set_build(build);
version_info->set_patch(patch);
version_info->set_channel(io_data_->channel());
request.SerializeToString(&serialized_request);
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("data_reduction_proxy_config", R"(
semantics {
sender: "Data Reduction Proxy"
description:
"Requests a configuration that specifies how to connect to the "
"data reduction proxy."
trigger:
"Requested when Data Saver is enabled and the browser does not "
"have a configuration that is not older than a threshold set by "
"the server."
data: "None."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Data Saver on Android via 'Data Saver' setting. "
"Data Saver is not available on iOS, and on desktop it is enabled "
"by insalling the Data Saver extension."
policy_exception_justification: "Not implemented."
})");
fetch_in_progress_ = true;
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = config_service_url_;
resource_request->method = "POST";
resource_request->load_flags = net::LOAD_BYPASS_PROXY;
resource_request->allow_credentials = false;
url_loader_ = variations::CreateSimpleURLLoaderWithVariationsHeader(
std::move(resource_request), variations::InIncognito::kNo,
variations::SignedIn::kNo, traffic_annotation);
url_loader_->AttachStringForUpload(serialized_request,
"application/x-protobuf");
static const int kMaxRetries = 5;
url_loader_->SetRetryOptions(
kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE);
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory_.get(),
base::BindOnce(&DataReductionProxyConfigServiceClient::OnURLLoadComplete,
base::Unretained(this)));
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | void DataReductionProxyConfigServiceClient::RetrieveRemoteConfig() {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!params::IsIncludedInHoldbackFieldTrial());
CreateClientConfigRequest request;
std::string serialized_request;
#if defined(OS_ANDROID)
request.set_telephony_network_operator(
net::android::GetTelephonyNetworkOperator());
#endif
data_reduction_proxy::ConfigDeviceInfo* device_info =
request.mutable_device_info();
device_info->set_total_device_memory_kb(
base::SysInfo::AmountOfPhysicalMemory() / 1024);
const std::string& session_key = request_options_->GetSecureSession();
if (!session_key.empty())
request.set_session_key(request_options_->GetSecureSession());
request.set_dogfood_group(
base::FeatureList::IsEnabled(features::kDogfood)
? CreateClientConfigRequest_DogfoodGroup_DOGFOOD
: CreateClientConfigRequest_DogfoodGroup_NONDOGFOOD);
data_reduction_proxy::VersionInfo* version_info =
request.mutable_version_info();
uint32_t build;
uint32_t patch;
util::GetChromiumBuildAndPatchAsInts(util::ChromiumVersion(), &build, &patch);
version_info->set_client(util::GetStringForClient(io_data_->client()));
version_info->set_build(build);
version_info->set_patch(patch);
version_info->set_channel(io_data_->channel());
request.SerializeToString(&serialized_request);
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("data_reduction_proxy_config", R"(
semantics {
sender: "Data Reduction Proxy"
description:
"Requests a configuration that specifies how to connect to the "
"data reduction proxy."
trigger:
"Requested when Data Saver is enabled and the browser does not "
"have a configuration that is not older than a threshold set by "
"the server."
data: "None."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Data Saver on Android via 'Data Saver' setting. "
"Data Saver is not available on iOS, and on desktop it is enabled "
"by insalling the Data Saver extension."
policy_exception_justification: "Not implemented."
})");
fetch_in_progress_ = true;
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = config_service_url_;
resource_request->method = "POST";
resource_request->load_flags = net::LOAD_BYPASS_PROXY;
resource_request->allow_credentials = false;
url_loader_ = variations::CreateSimpleURLLoaderWithVariationsHeader(
std::move(resource_request), variations::InIncognito::kNo,
variations::SignedIn::kNo, traffic_annotation);
url_loader_->AttachStringForUpload(serialized_request,
"application/x-protobuf");
static const int kMaxRetries = 5;
url_loader_->SetRetryOptions(
kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE);
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory_.get(),
base::BindOnce(&DataReductionProxyConfigServiceClient::OnURLLoadComplete,
base::Unretained(this)));
}
| 172,420 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: txid_current_snapshot(PG_FUNCTION_ARGS)
{
TxidSnapshot *snap;
uint32 nxip,
i,
size;
TxidEpoch state;
Snapshot cur;
cur = GetActiveSnapshot();
if (cur == NULL)
elog(ERROR, "no active snapshot set");
load_xid_epoch(&state);
/* allocate */
nxip = cur->xcnt;
size = TXID_SNAPSHOT_SIZE(nxip);
snap = palloc(size);
SET_VARSIZE(snap, size);
/* fill */
snap->xmin = convert_xid(cur->xmin, &state);
snap->xmax = convert_xid(cur->xmax, &state);
snap->nxip = nxip;
for (i = 0; i < nxip; i++)
snap->xip[i] = convert_xid(cur->xip[i], &state);
/* we want them guaranteed to be in ascending order */
sort_snapshot(snap);
PG_RETURN_POINTER(snap);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | txid_current_snapshot(PG_FUNCTION_ARGS)
{
TxidSnapshot *snap;
uint32 nxip,
i,
size;
TxidEpoch state;
Snapshot cur;
cur = GetActiveSnapshot();
if (cur == NULL)
elog(ERROR, "no active snapshot set");
load_xid_epoch(&state);
/*
* Compile-time limits on the procarray (MAX_BACKENDS processes plus
* MAX_BACKENDS prepared transactions) guarantee nxip won't be too large.
*/
StaticAssertStmt(MAX_BACKENDS * 2 <= TXID_SNAPSHOT_MAX_NXIP,
"possible overflow in txid_current_snapshot()");
/* allocate */
nxip = cur->xcnt;
size = TXID_SNAPSHOT_SIZE(nxip);
snap = palloc(size);
SET_VARSIZE(snap, size);
/* fill */
snap->xmin = convert_xid(cur->xmin, &state);
snap->xmax = convert_xid(cur->xmax, &state);
snap->nxip = nxip;
for (i = 0; i < nxip; i++)
snap->xip[i] = convert_xid(cur->xip[i], &state);
/* we want them guaranteed to be in ascending order */
sort_snapshot(snap);
PG_RETURN_POINTER(snap);
}
| 166,415 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tight_detect_smooth_image(VncState *vs, int w, int h)
{
unsigned int errors;
int compression = vs->tight.compression;
int quality = vs->tight.quality;
if (!vs->vd->lossy) {
return 0;
}
if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
vs->clientds.pf.bytes_per_pixel == 1 ||
w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) {
return 0;
}
if (vs->tight.quality != (uint8_t)-1) {
if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) {
return 0;
}
} else {
if (w * h < tight_conf[compression].gradient_min_rect_size) {
return 0;
}
}
if (vs->clientds.pf.bytes_per_pixel == 4) {
if (vs->tight.pixel24) {
errors = tight_detect_smooth_image24(vs, w, h);
if (vs->tight.quality != (uint8_t)-1) {
return (errors < tight_conf[quality].jpeg_threshold24);
}
return (errors < tight_conf[compression].gradient_threshold24);
} else {
errors = tight_detect_smooth_image32(vs, w, h);
}
} else {
errors = tight_detect_smooth_image16(vs, w, h);
}
if (quality != -1) {
return (errors < tight_conf[quality].jpeg_threshold);
}
return (errors < tight_conf[compression].gradient_threshold);
}
Commit Message:
CWE ID: CWE-125 | tight_detect_smooth_image(VncState *vs, int w, int h)
{
unsigned int errors;
int compression = vs->tight.compression;
int quality = vs->tight.quality;
if (!vs->vd->lossy) {
return 0;
}
if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
vs->client_pf.bytes_per_pixel == 1 ||
w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) {
return 0;
}
if (vs->tight.quality != (uint8_t)-1) {
if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) {
return 0;
}
} else {
if (w * h < tight_conf[compression].gradient_min_rect_size) {
return 0;
}
}
if (vs->client_pf.bytes_per_pixel == 4) {
if (vs->tight.pixel24) {
errors = tight_detect_smooth_image24(vs, w, h);
if (vs->tight.quality != (uint8_t)-1) {
return (errors < tight_conf[quality].jpeg_threshold24);
}
return (errors < tight_conf[compression].gradient_threshold24);
} else {
errors = tight_detect_smooth_image32(vs, w, h);
}
} else {
errors = tight_detect_smooth_image16(vs, w, h);
}
if (quality != -1) {
return (errors < tight_conf[quality].jpeg_threshold);
}
return (errors < tight_conf[compression].gradient_threshold);
}
| 165,464 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs)
{
FILE *fp = fopen(dest_filename, "w");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
fclose(fp);
return true;
}
Commit Message: ccpp: fix symlink race conditions
Fix copy & chown race conditions
Related: #1211835
Signed-off-by: Jakub Filak <[email protected]>
CWE ID: CWE-59 | static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs)
static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid)
{
FILE *fp = fopen(dest_filename, "w");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
const int dest_fd = fileno(fp);
if (fchown(dest_fd, uid, gid) < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
fclose(fp);
unlink(dest_filename);
return false;
}
fclose(fp);
return true;
}
| 170,136 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
{
/* Reuse the standard stuff as appropriate. */
standard_info_part1(&dp->this, pp, pi);
/* Now set the list of transforms. */
dp->transform_list->set(dp->transform_list, dp, pp, pi);
/* Update the info structure for these transforms: */
{
int i = dp->this.use_update_info;
/* Always do one call, even if use_update_info is 0. */
do
png_read_update_info(pp, pi);
while (--i > 0);
}
/* And get the output information into the standard_display */
standard_info_part2(&dp->this, pp, pi, 1/*images*/);
/* Plus the extra stuff we need for the transform tests: */
dp->output_colour_type = png_get_color_type(pp, pi);
dp->output_bit_depth = png_get_bit_depth(pp, pi);
/* Validate the combination of colour type and bit depth that we are getting
* out of libpng; the semantics of something not in the PNG spec are, at
* best, unclear.
*/
switch (dp->output_colour_type)
{
case PNG_COLOR_TYPE_PALETTE:
if (dp->output_bit_depth > 8) goto error;
/*FALL THROUGH*/
case PNG_COLOR_TYPE_GRAY:
if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
dp->output_bit_depth == 4)
break;
/*FALL THROUGH*/
default:
if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
break;
/*FALL THROUGH*/
error:
{
char message[128];
size_t pos;
pos = safecat(message, sizeof message, 0,
"invalid final bit depth: colour type(");
pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
pos = safecat(message, sizeof message, pos, ") with bit depth: ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
png_error(pp, message);
}
}
/* Use a test pixel to check that the output agrees with what we expect -
* this avoids running the whole test if the output is unexpected.
*/
{
image_pixel test_pixel;
memset(&test_pixel, 0, sizeof test_pixel);
test_pixel.colour_type = dp->this.colour_type; /* input */
test_pixel.bit_depth = dp->this.bit_depth;
if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
test_pixel.sample_depth = 8;
else
test_pixel.sample_depth = test_pixel.bit_depth;
/* Don't need sBIT here, but it must be set to non-zero to avoid
* arithmetic overflows.
*/
test_pixel.have_tRNS = dp->this.is_transparent;
test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
test_pixel.alpha_sBIT = test_pixel.sample_depth;
dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
if (test_pixel.colour_type != dp->output_colour_type)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0, "colour type ");
pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
png_error(pp, message);
}
if (test_pixel.bit_depth != dp->output_bit_depth)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0, "bit depth ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
png_error(pp, message);
}
/* If both bit depth and colour type are correct check the sample depth.
* I believe these are both internal errors.
*/
if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
{
if (test_pixel.sample_depth != 8) /* oops - internal error! */
png_error(pp, "pngvalid: internal: palette sample depth not 8");
}
else if (test_pixel.sample_depth != dp->output_bit_depth)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0,
"internal: sample depth ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
png_error(pp, message);
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
{
/* Reuse the standard stuff as appropriate. */
standard_info_part1(&dp->this, pp, pi);
/* Now set the list of transforms. */
dp->transform_list->set(dp->transform_list, dp, pp, pi);
/* Update the info structure for these transforms: */
{
int i = dp->this.use_update_info;
/* Always do one call, even if use_update_info is 0. */
do
png_read_update_info(pp, pi);
while (--i > 0);
}
/* And get the output information into the standard_display */
standard_info_part2(&dp->this, pp, pi, 1/*images*/);
/* Plus the extra stuff we need for the transform tests: */
dp->output_colour_type = png_get_color_type(pp, pi);
dp->output_bit_depth = png_get_bit_depth(pp, pi);
/* If png_set_filler is in action then fake the output color type to include
* an alpha channel where appropriate.
*/
if (dp->output_bit_depth >= 8 &&
(dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
dp->output_colour_type |= 4;
/* Validate the combination of colour type and bit depth that we are getting
* out of libpng; the semantics of something not in the PNG spec are, at
* best, unclear.
*/
switch (dp->output_colour_type)
{
case PNG_COLOR_TYPE_PALETTE:
if (dp->output_bit_depth > 8) goto error;
/*FALL THROUGH*/
case PNG_COLOR_TYPE_GRAY:
if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
dp->output_bit_depth == 4)
break;
/*FALL THROUGH*/
default:
if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
break;
/*FALL THROUGH*/
error:
{
char message[128];
size_t pos;
pos = safecat(message, sizeof message, 0,
"invalid final bit depth: colour type(");
pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
pos = safecat(message, sizeof message, pos, ") with bit depth: ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
png_error(pp, message);
}
}
/* Use a test pixel to check that the output agrees with what we expect -
* this avoids running the whole test if the output is unexpected. This also
* checks for internal errors.
*/
{
image_pixel test_pixel;
memset(&test_pixel, 0, sizeof test_pixel);
test_pixel.colour_type = dp->this.colour_type; /* input */
test_pixel.bit_depth = dp->this.bit_depth;
if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
test_pixel.sample_depth = 8;
else
test_pixel.sample_depth = test_pixel.bit_depth;
/* Don't need sBIT here, but it must be set to non-zero to avoid
* arithmetic overflows.
*/
test_pixel.have_tRNS = dp->this.is_transparent != 0;
test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
test_pixel.alpha_sBIT = test_pixel.sample_depth;
dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
if (test_pixel.colour_type != dp->output_colour_type)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0, "colour type ");
pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
png_error(pp, message);
}
if (test_pixel.bit_depth != dp->output_bit_depth)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0, "bit depth ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
png_error(pp, message);
}
/* If both bit depth and colour type are correct check the sample depth.
*/
if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
test_pixel.sample_depth != 8) /* oops - internal error! */
png_error(pp, "pngvalid: internal: palette sample depth not 8");
else if (dp->unpacked && test_pixel.bit_depth != 8)
png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
&& test_pixel.bit_depth != test_pixel.sample_depth)
{
char message[128];
size_t pos = safecat(message, sizeof message, 0,
"internal: sample depth ");
/* Because unless something has set 'unpacked' or the image is palette
* mapped we expect the transform to keep sample depth and bit depth
* the same.
*/
pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
png_error(pp, message);
}
else if (test_pixel.bit_depth != dp->output_bit_depth)
{
/* This could be a libpng error too; libpng has not produced what we
* expect for the output bit depth.
*/
char message[128];
size_t pos = safecat(message, sizeof message, 0,
"internal: bit depth ");
pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
pos = safecat(message, sizeof message, pos, " expected ");
pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
png_error(pp, message);
}
}
}
| 173,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: string_modifier_check(struct magic_set *ms, struct magic *m)
{
if ((ms->flags & MAGIC_CHECK) == 0)
return 0;
if (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0) {
file_magwarn(ms,
"'/BHhLl' modifiers are only allowed for pascal strings\n");
return -1;
}
switch (m->type) {
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->str_flags != 0) {
file_magwarn(ms,
"no modifiers allowed for 16-bit strings\n");
return -1;
}
break;
case FILE_STRING:
case FILE_PSTRING:
if ((m->str_flags & REGEX_OFFSET_START) != 0) {
file_magwarn(ms,
"'/%c' only allowed on regex and search\n",
CHAR_REGEX_OFFSET_START);
return -1;
}
break;
case FILE_SEARCH:
if (m->str_range == 0) {
file_magwarn(ms,
"missing range; defaulting to %d\n",
STRING_DEFAULT_RANGE);
m->str_range = STRING_DEFAULT_RANGE;
return -1;
}
break;
case FILE_REGEX:
if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
file_magwarn(ms, "'/%c' not allowed on regex\n",
CHAR_COMPACT_WHITESPACE);
return -1;
}
if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
file_magwarn(ms, "'/%c' not allowed on regex\n",
CHAR_COMPACT_OPTIONAL_WHITESPACE);
return -1;
}
break;
default:
file_magwarn(ms, "coding error: m->type=%d\n",
m->type);
return -1;
}
return 0;
}
Commit Message: * Enforce limit of 8K on regex searches that have no limits
* Allow the l modifier for regex to mean line count. Default
to byte count. If line count is specified, assume a max
of 80 characters per line to limit the byte count.
* Don't allow conversions to be used for dates, allowing
the mask field to be used as an offset.
* Bump the version of the magic format so that regex changes
are visible.
CWE ID: CWE-399 | string_modifier_check(struct magic_set *ms, struct magic *m)
{
if ((ms->flags & MAGIC_CHECK) == 0)
return 0;
if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
(m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
file_magwarn(ms,
"'/BHhLl' modifiers are only allowed for pascal strings\n");
return -1;
}
switch (m->type) {
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->str_flags != 0) {
file_magwarn(ms,
"no modifiers allowed for 16-bit strings\n");
return -1;
}
break;
case FILE_STRING:
case FILE_PSTRING:
if ((m->str_flags & REGEX_OFFSET_START) != 0) {
file_magwarn(ms,
"'/%c' only allowed on regex and search\n",
CHAR_REGEX_OFFSET_START);
return -1;
}
break;
case FILE_SEARCH:
if (m->str_range == 0) {
file_magwarn(ms,
"missing range; defaulting to %d\n",
STRING_DEFAULT_RANGE);
m->str_range = STRING_DEFAULT_RANGE;
return -1;
}
break;
case FILE_REGEX:
if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
file_magwarn(ms, "'/%c' not allowed on regex\n",
CHAR_COMPACT_WHITESPACE);
return -1;
}
if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
file_magwarn(ms, "'/%c' not allowed on regex\n",
CHAR_COMPACT_OPTIONAL_WHITESPACE);
return -1;
}
break;
default:
file_magwarn(ms, "coding error: m->type=%d\n",
m->type);
return -1;
}
return 0;
}
| 166,356 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data)
{
int ret;
ret = usb_control_msg(pegasus->usb, usb_rcvctrlpipe(pegasus->usb, 0),
PEGASUS_REQ_GET_REGS, PEGASUS_REQT_READ, 0,
indx, data, size, 1000);
if (ret < 0)
netif_dbg(pegasus, drv, pegasus->net,
"%s returned %d\n", __func__, ret);
return ret;
}
Commit Message: pegasus: Use heap buffers for all register access
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
References: https://bugs.debian.org/852556
Reported-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]>
Tested-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int get_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data)
{
u8 *buf;
int ret;
buf = kmalloc(size, GFP_NOIO);
if (!buf)
return -ENOMEM;
ret = usb_control_msg(pegasus->usb, usb_rcvctrlpipe(pegasus->usb, 0),
PEGASUS_REQ_GET_REGS, PEGASUS_REQT_READ, 0,
indx, buf, size, 1000);
if (ret < 0)
netif_dbg(pegasus, drv, pegasus->net,
"%s returned %d\n", __func__, ret);
else if (ret <= size)
memcpy(data, buf, ret);
kfree(buf);
return ret;
}
| 168,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int walk_hugetlb_range(unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct hstate *h = hstate_vma(vma);
unsigned long next;
unsigned long hmask = huge_page_mask(h);
unsigned long sz = huge_page_size(h);
pte_t *pte;
int err = 0;
do {
next = hugetlb_entry_end(h, addr, end);
pte = huge_pte_offset(walk->mm, addr & hmask, sz);
if (pte && walk->hugetlb_entry)
err = walk->hugetlb_entry(pte, hmask, addr, next, walk);
if (err)
break;
} while (addr = next, addr != end);
return err;
}
Commit Message: mm/pagewalk.c: report holes in hugetlb ranges
This matters at least for the mincore syscall, which will otherwise copy
uninitialized memory from the page allocator to userspace. It is
probably also a correctness error for /proc/$pid/pagemap, but I haven't
tested that.
Removing the `walk->hugetlb_entry` condition in walk_hugetlb_range() has
no effect because the caller already checks for that.
This only reports holes in hugetlb ranges to callers who have specified
a hugetlb_entry callback.
This issue was found using an AFL-based fuzzer.
v2:
- don't crash on ->pte_hole==NULL (Andrew Morton)
- add Cc stable (Andrew Morton)
Fixes: 1e25a271c8ac ("mincore: apply page table walker on do_mincore()")
Signed-off-by: Jann Horn <[email protected]>
Cc: <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | static int walk_hugetlb_range(unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct hstate *h = hstate_vma(vma);
unsigned long next;
unsigned long hmask = huge_page_mask(h);
unsigned long sz = huge_page_size(h);
pte_t *pte;
int err = 0;
do {
next = hugetlb_entry_end(h, addr, end);
pte = huge_pte_offset(walk->mm, addr & hmask, sz);
if (pte)
err = walk->hugetlb_entry(pte, hmask, addr, next, walk);
else if (walk->pte_hole)
err = walk->pte_hole(addr, next, walk);
if (err)
break;
} while (addr = next, addr != end);
return err;
}
| 167,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: enum nss_status _nss_mymachines_getgrnam_r(
const char *name,
struct group *gr,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t gid;
size_t l;
int r;
assert(name);
assert(gr);
p = startswith(name, "vg-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
r = parse_gid(e + 1, &gid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineGroup",
&error,
&reply,
"su",
machine, (uint32_t) gid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_GROUP_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = sizeof(char*) + strlen(name) + 1;
if (buflen < l) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memzero(buffer, sizeof(char*));
strcpy(buffer + sizeof(char*), name);
gr->gr_name = buffer + sizeof(char*);
gr->gr_gid = gid;
gr->gr_passwd = (char*) "*"; /* locked */
gr->gr_mem = (char**) buffer;
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
Commit Message: nss-mymachines: do not allow overlong machine names
https://github.com/systemd/systemd/issues/2002
CWE ID: CWE-119 | enum nss_status _nss_mymachines_getgrnam_r(
const char *name,
struct group *gr,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t gid;
size_t l;
int r;
assert(name);
assert(gr);
p = startswith(name, "vg-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */
goto not_found;
r = parse_gid(e + 1, &gid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineGroup",
&error,
&reply,
"su",
machine, (uint32_t) gid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_GROUP_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = sizeof(char*) + strlen(name) + 1;
if (buflen < l) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memzero(buffer, sizeof(char*));
strcpy(buffer + sizeof(char*), name);
gr->gr_name = buffer + sizeof(char*);
gr->gr_gid = gid;
gr->gr_passwd = (char*) "*"; /* locked */
gr->gr_mem = (char**) buffer;
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
| 168,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
{
struct file *eventfp, *filep = NULL;
struct eventfd_ctx *ctx = NULL;
u64 p;
long r;
int i, fd;
/* If you are not the owner, you can become one */
if (ioctl == VHOST_SET_OWNER) {
r = vhost_dev_set_owner(d);
goto done;
}
/* You must be the owner to do anything else */
r = vhost_dev_check_owner(d);
if (r)
goto done;
switch (ioctl) {
case VHOST_SET_MEM_TABLE:
r = vhost_set_memory(d, argp);
break;
case VHOST_SET_LOG_BASE:
if (copy_from_user(&p, argp, sizeof p)) {
r = -EFAULT;
break;
}
if ((u64)(unsigned long)p != p) {
r = -EFAULT;
break;
}
for (i = 0; i < d->nvqs; ++i) {
struct vhost_virtqueue *vq;
void __user *base = (void __user *)(unsigned long)p;
vq = d->vqs[i];
mutex_lock(&vq->mutex);
/* If ring is inactive, will check when it's enabled. */
if (vq->private_data && !vq_log_access_ok(vq, base))
r = -EFAULT;
else
vq->log_base = base;
mutex_unlock(&vq->mutex);
}
break;
case VHOST_SET_LOG_FD:
r = get_user(fd, (int __user *)argp);
if (r < 0)
break;
eventfp = fd == -1 ? NULL : eventfd_fget(fd);
if (IS_ERR(eventfp)) {
r = PTR_ERR(eventfp);
break;
}
if (eventfp != d->log_file) {
filep = d->log_file;
ctx = d->log_ctx;
d->log_ctx = eventfp ?
eventfd_ctx_fileget(eventfp) : NULL;
} else
filep = eventfp;
for (i = 0; i < d->nvqs; ++i) {
mutex_lock(&d->vqs[i]->mutex);
d->vqs[i]->log_ctx = d->log_ctx;
mutex_unlock(&d->vqs[i]->mutex);
}
if (ctx)
eventfd_ctx_put(ctx);
if (filep)
fput(filep);
break;
default:
r = -ENOIOCTLCMD;
break;
}
done:
return r;
}
Commit Message: vhost: actually track log eventfd file
While reviewing vhost log code, I found out that log_file is never
set. Note: I haven't tested the change (QEMU doesn't use LOG_FD yet).
Cc: [email protected]
Signed-off-by: Marc-André Lureau <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
CWE ID: CWE-399 | long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
{
struct file *eventfp, *filep = NULL;
struct eventfd_ctx *ctx = NULL;
u64 p;
long r;
int i, fd;
/* If you are not the owner, you can become one */
if (ioctl == VHOST_SET_OWNER) {
r = vhost_dev_set_owner(d);
goto done;
}
/* You must be the owner to do anything else */
r = vhost_dev_check_owner(d);
if (r)
goto done;
switch (ioctl) {
case VHOST_SET_MEM_TABLE:
r = vhost_set_memory(d, argp);
break;
case VHOST_SET_LOG_BASE:
if (copy_from_user(&p, argp, sizeof p)) {
r = -EFAULT;
break;
}
if ((u64)(unsigned long)p != p) {
r = -EFAULT;
break;
}
for (i = 0; i < d->nvqs; ++i) {
struct vhost_virtqueue *vq;
void __user *base = (void __user *)(unsigned long)p;
vq = d->vqs[i];
mutex_lock(&vq->mutex);
/* If ring is inactive, will check when it's enabled. */
if (vq->private_data && !vq_log_access_ok(vq, base))
r = -EFAULT;
else
vq->log_base = base;
mutex_unlock(&vq->mutex);
}
break;
case VHOST_SET_LOG_FD:
r = get_user(fd, (int __user *)argp);
if (r < 0)
break;
eventfp = fd == -1 ? NULL : eventfd_fget(fd);
if (IS_ERR(eventfp)) {
r = PTR_ERR(eventfp);
break;
}
if (eventfp != d->log_file) {
filep = d->log_file;
d->log_file = eventfp;
ctx = d->log_ctx;
d->log_ctx = eventfp ?
eventfd_ctx_fileget(eventfp) : NULL;
} else
filep = eventfp;
for (i = 0; i < d->nvqs; ++i) {
mutex_lock(&d->vqs[i]->mutex);
d->vqs[i]->log_ctx = d->log_ctx;
mutex_unlock(&d->vqs[i]->mutex);
}
if (ctx)
eventfd_ctx_put(ctx);
if (filep)
fput(filep);
break;
default:
r = -ENOIOCTLCMD;
break;
}
done:
return r;
}
| 166,591 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: QualifyIpPacket(IPHeader *pIpHeader, ULONG len)
{
tTcpIpPacketParsingResult res;
res.value = 0;
if (len < 4)
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR ver_len = pIpHeader->v4.ip_verlen;
UCHAR ip_version = (ver_len & 0xF0) >> 4;
USHORT ipHeaderSize = 0;
USHORT fullLength = 0;
res.value = 0;
if (ip_version == 4)
{
if (len < sizeof(IPv4Header))
{
res.ipStatus = ppresNotIP;
return res;
}
ipHeaderSize = (ver_len & 0xF) << 2;
fullLength = swap_short(pIpHeader->v4.ip_length);
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;
if (res.ipStatus == ppresNotIP)
{
return res;
}
if (ipHeaderSize >= fullLength || len < fullLength)
{
DPrintf(2, ("[%s] - truncated packet - ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n", __FUNCTION__,
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipCheckSum = ppresIPTooShort;
return res;
}
}
else if (ip_version == 6)
{
if (len < sizeof(IPv6Header))
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR nextHeader = pIpHeader->v6.ip6_next_header;
BOOLEAN bParsingDone = FALSE;
ipHeaderSize = sizeof(pIpHeader->v6);
res.ipStatus = ppresIPV6;
res.ipCheckSum = ppresCSOK;
fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
fullLength += ipHeaderSize;
if (len < fullLength)
{
res.ipStatus = ppresNotIP;
return res;
}
while (nextHeader != 59)
{
IPv6ExtHeader *pExt;
switch (nextHeader)
{
case PROTOCOL_TCP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsTCP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case PROTOCOL_UDP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsUDP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case 0:
case 60:
case 43:
case 44:
case 51:
case 50:
case 135:
if (len >= ((ULONG)ipHeaderSize + 8))
{
pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);
nextHeader = pExt->ip6ext_next_header;
ipHeaderSize += 8;
ipHeaderSize += pExt->ip6ext_hdr_len * 8;
}
else
{
DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize));
res.ipStatus = ppresNotIP;
bParsingDone = TRUE;
}
break;
default:
res.xxpStatus = ppresXxpOther;
bParsingDone = TRUE;
break;
}
if (bParsingDone)
break;
}
if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)
{
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, nextHeader, fullLength));
res.ipHeaderSize = ipHeaderSize;
}
else
{
DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize));
res.ipStatus = ppresNotIP;
}
}
if (res.ipStatus == ppresIPV4)
{
res.ipHeaderSize = ipHeaderSize;
res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;
switch (pIpHeader->v4.ip_protocol)
{
case PROTOCOL_TCP:
{
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
case PROTOCOL_UDP:
{
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
default:
res.xxpStatus = ppresXxpOther;
break;
}
}
return res;
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | QualifyIpPacket(IPHeader *pIpHeader, ULONG len)
QualifyIpPacket(IPHeader *pIpHeader, ULONG len, BOOLEAN verifyLength)
{
tTcpIpPacketParsingResult res;
res.value = 0;
if (len < 4)
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR ver_len = pIpHeader->v4.ip_verlen;
UCHAR ip_version = (ver_len & 0xF0) >> 4;
USHORT ipHeaderSize = 0;
USHORT fullLength = 0;
res.value = 0;
if (ip_version == 4)
{
if (len < sizeof(IPv4Header))
{
res.ipStatus = ppresNotIP;
return res;
}
ipHeaderSize = (ver_len & 0xF) << 2;
fullLength = swap_short(pIpHeader->v4.ip_length);
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;
if (res.ipStatus == ppresNotIP)
{
return res;
}
if (ipHeaderSize >= fullLength || ( verifyLength && len < fullLength))
{
DPrintf(2, ("[%s] - truncated packet - ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d, verify = %s\n", __FUNCTION__,
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len, (verifyLength ? "true" : "false")));
res.ipCheckSum = ppresIPTooShort;
return res;
}
}
else if (ip_version == 6)
{
if (len < sizeof(IPv6Header))
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR nextHeader = pIpHeader->v6.ip6_next_header;
BOOLEAN bParsingDone = FALSE;
ipHeaderSize = sizeof(pIpHeader->v6);
res.ipStatus = ppresIPV6;
res.ipCheckSum = ppresCSOK;
fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
fullLength += ipHeaderSize;
if (verifyLength && (len < fullLength))
{
res.ipStatus = ppresNotIP;
return res;
}
while (nextHeader != 59)
{
IPv6ExtHeader *pExt;
switch (nextHeader)
{
case PROTOCOL_TCP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsTCP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case PROTOCOL_UDP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsUDP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case 0:
case 60:
case 43:
case 44:
case 51:
case 50:
case 135:
if (len >= ((ULONG)ipHeaderSize + 8))
{
pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);
nextHeader = pExt->ip6ext_next_header;
ipHeaderSize += 8;
ipHeaderSize += pExt->ip6ext_hdr_len * 8;
}
else
{
DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize));
res.ipStatus = ppresNotIP;
bParsingDone = TRUE;
}
break;
default:
res.xxpStatus = ppresXxpOther;
bParsingDone = TRUE;
break;
}
if (bParsingDone)
break;
}
if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)
{
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, nextHeader, fullLength));
res.ipHeaderSize = ipHeaderSize;
}
else
{
DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize));
res.ipStatus = ppresNotIP;
}
}
if (res.ipStatus == ppresIPV4)
{
res.ipHeaderSize = ipHeaderSize;
res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;
switch (pIpHeader->v4.ip_protocol)
{
case PROTOCOL_TCP:
{
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
case PROTOCOL_UDP:
{
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
default:
res.xxpStatus = ppresXxpOther;
break;
}
}
return res;
}
| 170,145 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SVGFEColorMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
{
FEColorMatrix* colorMatrix = static_cast<FEColorMatrix*>(effect);
if (attrName == SVGNames::typeAttr)
return colorMatrix->setType(m_type->currentValue()->enumValue());
if (attrName == SVGNames::valuesAttr)
return colorMatrix->setValues(m_values->currentValue()->toFloatVector());
ASSERT_NOT_REACHED();
return false;
}
Commit Message: Explicitly enforce values size in feColorMatrix.
[email protected]
BUG=468519
Review URL: https://codereview.chromium.org/1075413002
git-svn-id: svn://svn.chromium.org/blink/trunk@193571 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | bool SVGFEColorMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
{
FEColorMatrix* colorMatrix = static_cast<FEColorMatrix*>(effect);
if (attrName == SVGNames::typeAttr)
return colorMatrix->setType(m_type->currentValue()->enumValue());
if (attrName == SVGNames::valuesAttr) {
Vector<float> values = m_values->currentValue()->toFloatVector();
if (values.size() == 20)
return colorMatrix->setValues(m_values->currentValue()->toFloatVector());
return false;
}
ASSERT_NOT_REACHED();
return false;
}
| 171,979 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,
Buffer* buf, int *err, gchar **err_info)
{
guint8 *pd;
gchar line[COSINE_LINE_LENGTH];
int i, hex_lines, n, caplen = 0;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, COSINE_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Merge the header and packet data parsing routines while we're at it.
Bug: 12395
Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2
Reviewed-on: https://code.wireshark.org/review/15172
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-119 | parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
| 169,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: eap_print(netdissect_options *ndo,
register const u_char *cp,
u_int length)
{
const struct eap_frame_t *eap;
const u_char *tptr;
u_int tlen, type, subtype;
int count=0, len;
tptr = cp;
tlen = length;
eap = (const struct eap_frame_t *)cp;
ND_TCHECK(*eap);
/* in non-verbose mode just lets print the basic info */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s (%u) v%u, len %u",
tok2str(eap_frame_type_values, "unknown", eap->type),
eap->type,
eap->version,
EXTRACT_16BITS(eap->length)));
return;
}
ND_PRINT((ndo, "%s (%u) v%u, len %u",
tok2str(eap_frame_type_values, "unknown", eap->type),
eap->type,
eap->version,
EXTRACT_16BITS(eap->length)));
tptr += sizeof(const struct eap_frame_t);
tlen -= sizeof(const struct eap_frame_t);
switch (eap->type) {
case EAP_FRAME_TYPE_PACKET:
type = *(tptr);
len = EXTRACT_16BITS(tptr+2);
ND_PRINT((ndo, ", %s (%u), id %u, len %u",
tok2str(eap_code_values, "unknown", type),
type,
*(tptr+1),
len));
ND_TCHECK2(*tptr, len);
if (type <= 2) { /* For EAP_REQUEST and EAP_RESPONSE only */
subtype = *(tptr+4);
ND_PRINT((ndo, "\n\t\t Type %s (%u)",
tok2str(eap_type_values, "unknown", *(tptr+4)),
*(tptr + 4)));
switch (subtype) {
case EAP_TYPE_IDENTITY:
if (len - 5 > 0) {
ND_PRINT((ndo, ", Identity: "));
safeputs(ndo, tptr + 5, len - 5);
}
break;
case EAP_TYPE_NOTIFICATION:
if (len - 5 > 0) {
ND_PRINT((ndo, ", Notification: "));
safeputs(ndo, tptr + 5, len - 5);
}
break;
case EAP_TYPE_NAK:
count = 5;
/*
* one or more octets indicating
* the desired authentication
* type one octet per type
*/
while (count < len) {
ND_PRINT((ndo, " %s (%u),",
tok2str(eap_type_values, "unknown", *(tptr+count)),
*(tptr + count)));
count++;
}
break;
case EAP_TYPE_TTLS:
ND_PRINT((ndo, " TTLSv%u",
EAP_TTLS_VERSION(*(tptr + 5)))); /* fall through */
case EAP_TYPE_TLS:
ND_PRINT((ndo, " flags [%s] 0x%02x,",
bittok2str(eap_tls_flags_values, "none", *(tptr+5)),
*(tptr + 5)));
if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) {
ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6)));
}
break;
case EAP_TYPE_FAST:
ND_PRINT((ndo, " FASTv%u",
EAP_TTLS_VERSION(*(tptr + 5))));
ND_PRINT((ndo, " flags [%s] 0x%02x,",
bittok2str(eap_tls_flags_values, "none", *(tptr+5)),
*(tptr + 5)));
if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) {
ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6)));
}
/* FIXME - TLV attributes follow */
break;
case EAP_TYPE_AKA:
case EAP_TYPE_SIM:
ND_PRINT((ndo, " subtype [%s] 0x%02x,",
tok2str(eap_aka_subtype_values, "unknown", *(tptr+5)),
*(tptr + 5)));
/* FIXME - TLV attributes follow */
break;
case EAP_TYPE_MD5_CHALLENGE:
case EAP_TYPE_OTP:
case EAP_TYPE_GTC:
case EAP_TYPE_EXPANDED_TYPES:
case EAP_TYPE_EXPERIMENTAL:
default:
break;
}
}
break;
case EAP_FRAME_TYPE_LOGOFF:
case EAP_FRAME_TYPE_ENCAP_ASF_ALERT:
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|EAP]"));
}
Commit Message: CVE-2017-13015/EAP: Add more bounds checks.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | eap_print(netdissect_options *ndo,
register const u_char *cp,
u_int length)
{
const struct eap_frame_t *eap;
const u_char *tptr;
u_int tlen, type, subtype;
int count=0, len;
tptr = cp;
tlen = length;
eap = (const struct eap_frame_t *)cp;
ND_TCHECK(*eap);
/* in non-verbose mode just lets print the basic info */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s (%u) v%u, len %u",
tok2str(eap_frame_type_values, "unknown", eap->type),
eap->type,
eap->version,
EXTRACT_16BITS(eap->length)));
return;
}
ND_PRINT((ndo, "%s (%u) v%u, len %u",
tok2str(eap_frame_type_values, "unknown", eap->type),
eap->type,
eap->version,
EXTRACT_16BITS(eap->length)));
tptr += sizeof(const struct eap_frame_t);
tlen -= sizeof(const struct eap_frame_t);
switch (eap->type) {
case EAP_FRAME_TYPE_PACKET:
ND_TCHECK_8BITS(tptr);
type = *(tptr);
ND_TCHECK_16BITS(tptr+2);
len = EXTRACT_16BITS(tptr+2);
ND_PRINT((ndo, ", %s (%u), id %u, len %u",
tok2str(eap_code_values, "unknown", type),
type,
*(tptr+1),
len));
ND_TCHECK2(*tptr, len);
if (type <= 2) { /* For EAP_REQUEST and EAP_RESPONSE only */
ND_TCHECK_8BITS(tptr+4);
subtype = *(tptr+4);
ND_PRINT((ndo, "\n\t\t Type %s (%u)",
tok2str(eap_type_values, "unknown", subtype),
subtype));
switch (subtype) {
case EAP_TYPE_IDENTITY:
if (len - 5 > 0) {
ND_PRINT((ndo, ", Identity: "));
safeputs(ndo, tptr + 5, len - 5);
}
break;
case EAP_TYPE_NOTIFICATION:
if (len - 5 > 0) {
ND_PRINT((ndo, ", Notification: "));
safeputs(ndo, tptr + 5, len - 5);
}
break;
case EAP_TYPE_NAK:
count = 5;
/*
* one or more octets indicating
* the desired authentication
* type one octet per type
*/
while (count < len) {
ND_TCHECK_8BITS(tptr+count);
ND_PRINT((ndo, " %s (%u),",
tok2str(eap_type_values, "unknown", *(tptr+count)),
*(tptr + count)));
count++;
}
break;
case EAP_TYPE_TTLS:
case EAP_TYPE_TLS:
ND_TCHECK_8BITS(tptr + 5);
if (subtype == EAP_TYPE_TTLS)
ND_PRINT((ndo, " TTLSv%u",
EAP_TTLS_VERSION(*(tptr + 5))));
ND_PRINT((ndo, " flags [%s] 0x%02x,",
bittok2str(eap_tls_flags_values, "none", *(tptr+5)),
*(tptr + 5)));
if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) {
ND_TCHECK_32BITS(tptr + 6);
ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6)));
}
break;
case EAP_TYPE_FAST:
ND_TCHECK_8BITS(tptr + 5);
ND_PRINT((ndo, " FASTv%u",
EAP_TTLS_VERSION(*(tptr + 5))));
ND_PRINT((ndo, " flags [%s] 0x%02x,",
bittok2str(eap_tls_flags_values, "none", *(tptr+5)),
*(tptr + 5)));
if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) {
ND_TCHECK_32BITS(tptr + 6);
ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6)));
}
/* FIXME - TLV attributes follow */
break;
case EAP_TYPE_AKA:
case EAP_TYPE_SIM:
ND_TCHECK_8BITS(tptr + 5);
ND_PRINT((ndo, " subtype [%s] 0x%02x,",
tok2str(eap_aka_subtype_values, "unknown", *(tptr+5)),
*(tptr + 5)));
/* FIXME - TLV attributes follow */
break;
case EAP_TYPE_MD5_CHALLENGE:
case EAP_TYPE_OTP:
case EAP_TYPE_GTC:
case EAP_TYPE_EXPANDED_TYPES:
case EAP_TYPE_EXPERIMENTAL:
default:
break;
}
}
break;
case EAP_FRAME_TYPE_LOGOFF:
case EAP_FRAME_TYPE_ENCAP_ASF_ALERT:
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|EAP]"));
}
| 167,877 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct ip_options *ip_options_get_alloc(const int optlen)
{
return kzalloc(sizeof(struct ip_options) + ((optlen + 3) & ~3),
GFP_KERNEL);
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static struct ip_options *ip_options_get_alloc(const int optlen)
static struct ip_options_rcu *ip_options_get_alloc(const int optlen)
{
return kzalloc(sizeof(struct ip_options_rcu) + ((optlen + 3) & ~3),
GFP_KERNEL);
}
| 165,559 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void virtio_gpu_set_scanout(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_simple_resource *res;
struct virtio_gpu_scanout *scanout;
pixman_format_code_t format;
uint32_t offset;
int bpp;
struct virtio_gpu_set_scanout ss;
VIRTIO_GPU_FILL_CMD(ss);
trace_virtio_gpu_cmd_set_scanout(ss.scanout_id, ss.resource_id,
ss.r.width, ss.r.height, ss.r.x, ss.r.y);
if (ss.scanout_id >= g->conf.max_outputs) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
g->enable = 1;
if (ss.resource_id == 0) {
scanout = &g->scanout[ss.scanout_id];
if (scanout->resource_id) {
res = virtio_gpu_find_resource(g, scanout->resource_id);
if (res) {
res->scanout_bitmask &= ~(1 << ss.scanout_id);
}
}
if (ss.scanout_id == 0) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, NULL);
scanout->ds = NULL;
scanout->width = 0;
scanout->height = 0;
return;
}
/* create a surface for this scanout */
res = virtio_gpu_find_resource(g, ss.resource_id);
if (!res) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n",
__func__, ss.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
if (ss.r.x > res->width ||
ss.r.y > res->height ||
ss.r.width > res->width ||
ss.r.height > res->height ||
ss.r.x + ss.r.width > res->width ||
ss.r.y + ss.r.height > res->height) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout %d bounds for"
" resource %d, (%d,%d)+%d,%d vs %d %d\n",
__func__, ss.scanout_id, ss.resource_id, ss.r.x, ss.r.y,
ss.r.width, ss.r.height, res->width, res->height);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
scanout = &g->scanout[ss.scanout_id];
format = pixman_image_get_format(res->image);
bpp = (PIXMAN_FORMAT_BPP(format) + 7) / 8;
offset = (ss.r.x * bpp) + ss.r.y * pixman_image_get_stride(res->image);
if (!scanout->ds || surface_data(scanout->ds)
!= ((uint8_t *)pixman_image_get_data(res->image) + offset) ||
scanout->width != ss.r.width ||
scanout->height != ss.r.height) {
pixman_image_t *rect;
void *ptr = (uint8_t *)pixman_image_get_data(res->image) + offset;
rect = pixman_image_create_bits(format, ss.r.width, ss.r.height, ptr,
pixman_image_get_stride(res->image));
pixman_image_ref(res->image);
pixman_image_set_destroy_function(rect, virtio_unref_resource,
res->image);
/* realloc the surface ptr */
scanout->ds = qemu_create_displaysurface_pixman(rect);
if (!scanout->ds) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
return;
}
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, scanout->ds);
}
scanout->resource_id = ss.resource_id;
scanout->x = ss.r.x;
scanout->y = ss.r.y;
scanout->width = ss.r.width;
scanout->height = ss.r.height;
}
Commit Message:
CWE ID: CWE-772 | static void virtio_gpu_set_scanout(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_simple_resource *res;
struct virtio_gpu_scanout *scanout;
pixman_format_code_t format;
uint32_t offset;
int bpp;
struct virtio_gpu_set_scanout ss;
VIRTIO_GPU_FILL_CMD(ss);
trace_virtio_gpu_cmd_set_scanout(ss.scanout_id, ss.resource_id,
ss.r.width, ss.r.height, ss.r.x, ss.r.y);
if (ss.scanout_id >= g->conf.max_outputs) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
g->enable = 1;
if (ss.resource_id == 0) {
scanout = &g->scanout[ss.scanout_id];
if (scanout->resource_id) {
res = virtio_gpu_find_resource(g, scanout->resource_id);
if (res) {
res->scanout_bitmask &= ~(1 << ss.scanout_id);
}
}
if (ss.scanout_id == 0) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, NULL);
scanout->ds = NULL;
scanout->width = 0;
scanout->height = 0;
return;
}
/* create a surface for this scanout */
res = virtio_gpu_find_resource(g, ss.resource_id);
if (!res) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n",
__func__, ss.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
if (ss.r.x > res->width ||
ss.r.y > res->height ||
ss.r.width > res->width ||
ss.r.height > res->height ||
ss.r.x + ss.r.width > res->width ||
ss.r.y + ss.r.height > res->height) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout %d bounds for"
" resource %d, (%d,%d)+%d,%d vs %d %d\n",
__func__, ss.scanout_id, ss.resource_id, ss.r.x, ss.r.y,
ss.r.width, ss.r.height, res->width, res->height);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
scanout = &g->scanout[ss.scanout_id];
format = pixman_image_get_format(res->image);
bpp = (PIXMAN_FORMAT_BPP(format) + 7) / 8;
offset = (ss.r.x * bpp) + ss.r.y * pixman_image_get_stride(res->image);
if (!scanout->ds || surface_data(scanout->ds)
!= ((uint8_t *)pixman_image_get_data(res->image) + offset) ||
scanout->width != ss.r.width ||
scanout->height != ss.r.height) {
pixman_image_t *rect;
void *ptr = (uint8_t *)pixman_image_get_data(res->image) + offset;
rect = pixman_image_create_bits(format, ss.r.width, ss.r.height, ptr,
pixman_image_get_stride(res->image));
pixman_image_ref(res->image);
pixman_image_set_destroy_function(rect, virtio_unref_resource,
res->image);
/* realloc the surface ptr */
scanout->ds = qemu_create_displaysurface_pixman(rect);
if (!scanout->ds) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
return;
}
pixman_image_unref(rect);
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, scanout->ds);
}
scanout->resource_id = ss.resource_id;
scanout->x = ss.r.x;
scanout->y = ss.r.y;
scanout->width = ss.r.width;
scanout->height = ss.r.height;
}
| 164,813 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response StorageHandler::UntrackCacheStorageForOrigin(
const std::string& origin) {
if (!process_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&CacheStorageObserver::UntrackOriginOnIOThread,
base::Unretained(GetCacheStorageObserver()),
url::Origin::Create(origin_url)));
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 StorageHandler::UntrackCacheStorageForOrigin(
const std::string& origin) {
if (!storage_partition_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&CacheStorageObserver::UntrackOriginOnIOThread,
base::Unretained(GetCacheStorageObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
| 172,778 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_nal_unit(iv_obj_t *dec_hdl,
ivd_video_decode_op_t *ps_dec_op,
UWORD8 *pu1_buf,
UWORD32 u4_length)
{
dec_bit_stream_t *ps_bitstrm;
dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle;
ivd_video_decode_ip_t *ps_dec_in =
(ivd_video_decode_ip_t *)ps_dec->pv_dec_in;
dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice;
UWORD8 u1_first_byte, u1_nal_ref_idc;
UWORD8 u1_nal_unit_type;
WORD32 i_status = OK;
ps_bitstrm = ps_dec->ps_bitstrm;
if(pu1_buf)
{
if(u4_length)
{
ps_dec_op->u4_frame_decoded_flag = 0;
ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf,
u4_length);
SWITCHOFFTRACE;
u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8);
if(NAL_FORBIDDEN_BIT(u1_first_byte))
{
H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n");
}
u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte);
if ((ps_dec->u4_slice_start_code_found == 1)
&& (ps_dec->u1_pic_decode_done != 1)
&& (u1_nal_unit_type > IDR_SLICE_NAL))
{
return ERROR_INCOMPLETE_FRAME;
}
ps_dec->u1_nal_unit_type = u1_nal_unit_type;
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte));
switch(u1_nal_unit_type)
{
case SLICE_DATA_PARTITION_A_NAL:
case SLICE_DATA_PARTITION_B_NAL:
case SLICE_DATA_PARTITION_C_NAL:
if(!ps_dec->i4_decode_header)
ih264d_parse_slice_partition(ps_dec, ps_bitstrm);
break;
case IDR_SLICE_NAL:
case SLICE_NAL:
/* ! */
DEBUG_THREADS_PRINTF("Decoding a slice NAL\n");
if(!ps_dec->i4_decode_header)
{
if(ps_dec->i4_header_decoded == 3)
{
/* ! */
ps_dec->u4_slice_start_code_found = 1;
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_decode_slice(
(UWORD8)(u1_nal_unit_type
== IDR_SLICE_NAL),
u1_nal_ref_idc, ps_dec);
if((ps_dec->u4_first_slice_in_pic != 0)&&
((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0))
{
/* if the first slice header was not valid set to 1 */
ps_dec->u4_first_slice_in_pic = 1;
}
if(i_status != OK)
{
return i_status;
}
}
else
{
H264_DEC_DEBUG_PRINT(
"\nSlice NAL Supplied but no header has been supplied\n");
}
}
break;
case SEI_NAL:
if(!ps_dec->i4_decode_header)
{
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm);
if(i_status != OK)
return i_status;
ih264d_parse_sei(ps_dec, ps_bitstrm);
}
break;
case SEQ_PARAM_NAL:
/* ! */
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_sps(ps_dec, ps_bitstrm);
if(i_status == ERROR_INV_SPS_PPS_T)
return i_status;
if(!i_status)
ps_dec->i4_header_decoded |= 0x1;
break;
case PIC_PARAM_NAL:
/* ! */
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_pps(ps_dec, ps_bitstrm);
if(i_status == ERROR_INV_SPS_PPS_T)
return i_status;
if(!i_status)
ps_dec->i4_header_decoded |= 0x2;
break;
case ACCESS_UNIT_DELIMITER_RBSP:
if(!ps_dec->i4_decode_header)
{
ih264d_access_unit_delimiter_rbsp(ps_dec);
}
break;
case END_OF_STREAM_RBSP:
if(!ps_dec->i4_decode_header)
{
ih264d_parse_end_of_stream(ps_dec);
}
break;
case FILLER_DATA_NAL:
if(!ps_dec->i4_decode_header)
{
ih264d_parse_filler_data(ps_dec, ps_bitstrm);
}
break;
default:
H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type);
break;
}
}
}
return i_status;
}
Commit Message: Decoder: Fixed initialization of first_slice_in_pic
To handle some errors, first_slice_in_pic was being set to 2.
This is now cleaned up and first_slice_in_pic is set to 1 only once per pic.
This will ensure picture level initializations are done only once even in case
of error clips
Bug: 33717589
Bug: 33551775
Bug: 33716442
Bug: 33677995
Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba
CWE ID: CWE-200 | WORD32 ih264d_parse_nal_unit(iv_obj_t *dec_hdl,
ivd_video_decode_op_t *ps_dec_op,
UWORD8 *pu1_buf,
UWORD32 u4_length)
{
dec_bit_stream_t *ps_bitstrm;
dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle;
ivd_video_decode_ip_t *ps_dec_in =
(ivd_video_decode_ip_t *)ps_dec->pv_dec_in;
dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice;
UWORD8 u1_first_byte, u1_nal_ref_idc;
UWORD8 u1_nal_unit_type;
WORD32 i_status = OK;
ps_bitstrm = ps_dec->ps_bitstrm;
if(pu1_buf)
{
if(u4_length)
{
ps_dec_op->u4_frame_decoded_flag = 0;
ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf,
u4_length);
SWITCHOFFTRACE;
u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8);
if(NAL_FORBIDDEN_BIT(u1_first_byte))
{
H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n");
}
u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte);
if ((ps_dec->u4_slice_start_code_found == 1)
&& (ps_dec->u1_pic_decode_done != 1)
&& (u1_nal_unit_type > IDR_SLICE_NAL))
{
return ERROR_INCOMPLETE_FRAME;
}
ps_dec->u1_nal_unit_type = u1_nal_unit_type;
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte));
switch(u1_nal_unit_type)
{
case SLICE_DATA_PARTITION_A_NAL:
case SLICE_DATA_PARTITION_B_NAL:
case SLICE_DATA_PARTITION_C_NAL:
if(!ps_dec->i4_decode_header)
ih264d_parse_slice_partition(ps_dec, ps_bitstrm);
break;
case IDR_SLICE_NAL:
case SLICE_NAL:
/* ! */
DEBUG_THREADS_PRINTF("Decoding a slice NAL\n");
if(!ps_dec->i4_decode_header)
{
if(ps_dec->i4_header_decoded == 3)
{
/* ! */
ps_dec->u4_slice_start_code_found = 1;
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_decode_slice(
(UWORD8)(u1_nal_unit_type
== IDR_SLICE_NAL),
u1_nal_ref_idc, ps_dec);
if(i_status != OK)
{
return i_status;
}
}
else
{
H264_DEC_DEBUG_PRINT(
"\nSlice NAL Supplied but no header has been supplied\n");
}
}
break;
case SEI_NAL:
if(!ps_dec->i4_decode_header)
{
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm);
if(i_status != OK)
return i_status;
ih264d_parse_sei(ps_dec, ps_bitstrm);
}
break;
case SEQ_PARAM_NAL:
/* ! */
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_sps(ps_dec, ps_bitstrm);
if(i_status == ERROR_INV_SPS_PPS_T)
return i_status;
if(!i_status)
ps_dec->i4_header_decoded |= 0x1;
break;
case PIC_PARAM_NAL:
/* ! */
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_pps(ps_dec, ps_bitstrm);
if(i_status == ERROR_INV_SPS_PPS_T)
return i_status;
if(!i_status)
ps_dec->i4_header_decoded |= 0x2;
break;
case ACCESS_UNIT_DELIMITER_RBSP:
if(!ps_dec->i4_decode_header)
{
ih264d_access_unit_delimiter_rbsp(ps_dec);
}
break;
case END_OF_STREAM_RBSP:
if(!ps_dec->i4_decode_header)
{
ih264d_parse_end_of_stream(ps_dec);
}
break;
case FILLER_DATA_NAL:
if(!ps_dec->i4_decode_header)
{
ih264d_parse_filler_data(ps_dec, ps_bitstrm);
}
break;
default:
H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type);
break;
}
}
}
return i_status;
}
| 174,038 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_request_line(request_rec *r, apr_bucket_brigade *bb)
{
const char *ll;
const char *uri;
const char *pro;
unsigned int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
char http[5];
apr_size_t len;
int num_blank_lines = 0;
int max_blank_lines = r->server->limit_req_fields;
core_server_config *conf = ap_get_core_module_config(r->server->module_config);
int strict = conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT;
int enforce_strict = !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY);
if (max_blank_lines <= 0) {
max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS;
}
/* Read past empty lines until we get a real request line,
* a read error, the connection closes (EOF), or we timeout.
*
* We skip empty lines because browsers have to tack a CRLF on to the end
* of POSTs to support old CERN webservers. But note that we may not
* have flushed any previous response completely to the client yet.
* We delay the flush as long as possible so that we can improve
* performance for clients that are pipelining requests. If a request
* is pipelined then we won't block during the (implicit) read() below.
* If the requests aren't pipelined, then the client is still waiting
* for the final buffer flush from us, and we will block in the implicit
* read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
* have to block during a read.
*/
do {
apr_status_t rv;
/* ensure ap_rgetline allocates memory each time thru the loop
* if there are empty lines
*/
r->the_request = NULL;
rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),
&len, r, 0, bb);
if (rv != APR_SUCCESS) {
r->request_time = apr_time_now();
/* ap_rgetline returns APR_ENOSPC if it fills up the
* buffer before finding the end-of-line. This is only going to
* happen if it exceeds the configured limit for a request-line.
*/
if (APR_STATUS_IS_ENOSPC(rv)) {
r->status = HTTP_REQUEST_URI_TOO_LARGE;
r->proto_num = HTTP_VERSION(1,0);
r->protocol = apr_pstrdup(r->pool, "HTTP/1.0");
}
else if (APR_STATUS_IS_TIMEUP(rv)) {
r->status = HTTP_REQUEST_TIME_OUT;
}
else if (APR_STATUS_IS_EINVAL(rv)) {
r->status = HTTP_BAD_REQUEST;
}
return 0;
}
} while ((len <= 0) && (++num_blank_lines < max_blank_lines));
if (APLOGrtrace5(r)) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r,
"Request received from client: %s",
ap_escape_logitem(r->pool, r->the_request));
}
r->request_time = apr_time_now();
ll = r->the_request;
r->method = ap_getword_white(r->pool, &ll);
uri = ap_getword_white(r->pool, &ll);
/* Provide quick information about the request method as soon as known */
r->method_number = ap_method_number_of(r->method);
if (r->method_number == M_GET && r->method[0] == 'H') {
r->header_only = 1;
}
ap_parse_uri(r, uri);
if (ll[0]) {
r->assbackwards = 0;
pro = ll;
len = strlen(ll);
} else {
r->assbackwards = 1;
pro = "HTTP/0.9";
len = 8;
if (conf->http09_enable == AP_HTTP09_DISABLE) {
r->status = HTTP_VERSION_NOT_SUPPORTED;
r->protocol = apr_pstrmemdup(r->pool, pro, len);
/* If we deny 0.9, send error message with 1.x */
r->assbackwards = 0;
r->proto_num = HTTP_VERSION(0, 9);
r->connection->keepalive = AP_CONN_CLOSE;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401)
"HTTP/0.9 denied by server configuration");
return 0;
}
}
r->protocol = apr_pstrmemdup(r->pool, pro, len);
/* Avoid sscanf in the common case */
if (len == 8
&& pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P'
&& pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.'
&& apr_isdigit(pro[7])) {
r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
}
else {
if (strict) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418)
"Invalid protocol '%s'", r->protocol);
if (enforce_strict) {
r->status = HTTP_BAD_REQUEST;
return 0;
}
}
if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor)
&& (strcasecmp("http", http) == 0)
&& (minor < HTTP_VERSION(1, 0)) ) { /* don't allow HTTP/0.1000 */
r->proto_num = HTTP_VERSION(major, minor);
}
else {
r->proto_num = HTTP_VERSION(1, 0);
}
}
if (strict) {
int err = 0;
if (ap_has_cntrl(r->the_request)) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02420)
"Request line must not contain control characters");
err = HTTP_BAD_REQUEST;
}
if (r->parsed_uri.fragment) {
/* RFC3986 3.5: no fragment */
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421)
"URI must not contain a fragment");
err = HTTP_BAD_REQUEST;
}
else if (r->parsed_uri.user || r->parsed_uri.password) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422)
"URI must not contain a username/password");
err = HTTP_BAD_REQUEST;
}
else if (r->method_number == M_INVALID) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423)
"Invalid HTTP method string: %s", r->method);
err = HTTP_NOT_IMPLEMENTED;
}
else if (r->assbackwards == 0 && r->proto_num < HTTP_VERSION(1, 0)) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02424)
"HTTP/0.x does not take a protocol");
err = HTTP_BAD_REQUEST;
}
if (err && enforce_strict) {
r->status = err;
return 0;
}
}
return 1;
}
Commit Message: *) SECURITY: CVE-2015-0253 (cve.mitre.org)
core: Fix a crash introduced in with ErrorDocument 400 pointing
to a local URL-path with the INCLUDES filter active, introduced
in 2.4.11. PR 57531. [Yann Ylavic]
Submitted By: ylavic
Committed By: covener
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1664205 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: | static int read_request_line(request_rec *r, apr_bucket_brigade *bb)
{
const char *ll;
const char *uri;
const char *pro;
unsigned int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
char http[5];
apr_size_t len;
int num_blank_lines = 0;
int max_blank_lines = r->server->limit_req_fields;
core_server_config *conf = ap_get_core_module_config(r->server->module_config);
int strict = conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT;
int enforce_strict = !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY);
if (max_blank_lines <= 0) {
max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS;
}
/* Read past empty lines until we get a real request line,
* a read error, the connection closes (EOF), or we timeout.
*
* We skip empty lines because browsers have to tack a CRLF on to the end
* of POSTs to support old CERN webservers. But note that we may not
* have flushed any previous response completely to the client yet.
* We delay the flush as long as possible so that we can improve
* performance for clients that are pipelining requests. If a request
* is pipelined then we won't block during the (implicit) read() below.
* If the requests aren't pipelined, then the client is still waiting
* for the final buffer flush from us, and we will block in the implicit
* read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
* have to block during a read.
*/
do {
apr_status_t rv;
/* ensure ap_rgetline allocates memory each time thru the loop
* if there are empty lines
*/
r->the_request = NULL;
rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),
&len, r, 0, bb);
if (rv != APR_SUCCESS) {
r->request_time = apr_time_now();
/* ap_rgetline returns APR_ENOSPC if it fills up the
* buffer before finding the end-of-line. This is only going to
* happen if it exceeds the configured limit for a request-line.
*/
if (APR_STATUS_IS_ENOSPC(rv)) {
r->status = HTTP_REQUEST_URI_TOO_LARGE;
}
else if (APR_STATUS_IS_TIMEUP(rv)) {
r->status = HTTP_REQUEST_TIME_OUT;
}
else if (APR_STATUS_IS_EINVAL(rv)) {
r->status = HTTP_BAD_REQUEST;
}
r->proto_num = HTTP_VERSION(1,0);
r->protocol = apr_pstrdup(r->pool, "HTTP/1.0");
return 0;
}
} while ((len <= 0) && (++num_blank_lines < max_blank_lines));
if (APLOGrtrace5(r)) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r,
"Request received from client: %s",
ap_escape_logitem(r->pool, r->the_request));
}
r->request_time = apr_time_now();
ll = r->the_request;
r->method = ap_getword_white(r->pool, &ll);
uri = ap_getword_white(r->pool, &ll);
/* Provide quick information about the request method as soon as known */
r->method_number = ap_method_number_of(r->method);
if (r->method_number == M_GET && r->method[0] == 'H') {
r->header_only = 1;
}
ap_parse_uri(r, uri);
if (ll[0]) {
r->assbackwards = 0;
pro = ll;
len = strlen(ll);
} else {
r->assbackwards = 1;
pro = "HTTP/0.9";
len = 8;
if (conf->http09_enable == AP_HTTP09_DISABLE) {
r->status = HTTP_VERSION_NOT_SUPPORTED;
r->protocol = apr_pstrmemdup(r->pool, pro, len);
/* If we deny 0.9, send error message with 1.x */
r->assbackwards = 0;
r->proto_num = HTTP_VERSION(0, 9);
r->connection->keepalive = AP_CONN_CLOSE;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401)
"HTTP/0.9 denied by server configuration");
return 0;
}
}
r->protocol = apr_pstrmemdup(r->pool, pro, len);
/* Avoid sscanf in the common case */
if (len == 8
&& pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P'
&& pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.'
&& apr_isdigit(pro[7])) {
r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
}
else {
if (strict) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418)
"Invalid protocol '%s'", r->protocol);
if (enforce_strict) {
r->status = HTTP_BAD_REQUEST;
return 0;
}
}
if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor)
&& (strcasecmp("http", http) == 0)
&& (minor < HTTP_VERSION(1, 0)) ) { /* don't allow HTTP/0.1000 */
r->proto_num = HTTP_VERSION(major, minor);
}
else {
r->proto_num = HTTP_VERSION(1, 0);
}
}
if (strict) {
int err = 0;
if (ap_has_cntrl(r->the_request)) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02420)
"Request line must not contain control characters");
err = HTTP_BAD_REQUEST;
}
if (r->parsed_uri.fragment) {
/* RFC3986 3.5: no fragment */
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421)
"URI must not contain a fragment");
err = HTTP_BAD_REQUEST;
}
else if (r->parsed_uri.user || r->parsed_uri.password) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422)
"URI must not contain a username/password");
err = HTTP_BAD_REQUEST;
}
else if (r->method_number == M_INVALID) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423)
"Invalid HTTP method string: %s", r->method);
err = HTTP_NOT_IMPLEMENTED;
}
else if (r->assbackwards == 0 && r->proto_num < HTTP_VERSION(1, 0)) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02424)
"HTTP/0.x does not take a protocol");
err = HTTP_BAD_REQUEST;
}
if (err && enforce_strict) {
r->status = err;
return 0;
}
}
return 1;
}
| 166,741 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx)
{
assert(pCluster);
assert(pCluster->m_index < 0);
assert(idx >= m_clusterCount);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size)
{
const long n = (size <= 0) ? 2048 : 2*size;
Cluster** const qq = new Cluster*[n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p)
{
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
}
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 Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx)
if (m_clusterPreloadCount > 0) {
assert(m_clusters);
Cluster** const p = m_clusters + m_clusterCount;
assert(*p);
assert((*p)->m_index < 0);
Cluster** q = p + m_clusterPreloadCount;
assert(q < (m_clusters + size));
for (;;) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
if (q == p)
break;
}
}
m_clusters[idx] = pCluster;
++m_clusterCount;
}
| 174,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: 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));
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);
}
Commit Message: Map U+04CF to lowercase L as well.
U+04CF (ӏ) has the confusability skeleton of 'i' (lowercase
I), but it can be confused for 'l' (lowercase L) or '1' (digit) if rendered
in some fonts.
If a host name contains it, calculate the confusability skeleton
twice, once with the default mapping to 'i' (lowercase I) and the 2nd
time with an alternative mapping to 'l'. Mapping them to 'l' (lowercase L)
also gets it treated as similar to digit 1 because the confusability
skeleton of digit 1 is 'l'.
Bug: 817247
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I7442b950c9457eea285e17f01d1f43c9acc5d79c
Reviewed-on: https://chromium-review.googlesource.com/974165
Commit-Queue: Jungshik Shin <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Reviewed-by: Eric Lawrence <[email protected]>
Cr-Commit-Position: refs/heads/master@{#551263}
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));
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,222 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: explicit RemoveDownloadsTester(TestingProfile* testing_profile)
: download_manager_(new content::MockDownloadManager()),
chrome_download_manager_delegate_(testing_profile) {
content::BrowserContext::SetDownloadManagerForTesting(
testing_profile, base::WrapUnique(download_manager_));
EXPECT_EQ(download_manager_,
content::BrowserContext::GetDownloadManager(testing_profile));
EXPECT_CALL(*download_manager_, GetDelegate())
.WillOnce(Return(&chrome_download_manager_delegate_));
EXPECT_CALL(*download_manager_, Shutdown());
}
Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate.
DownloadManager has public SetDelegate method and tests and or other subsystems
can install their own implementations of the delegate.
Bug: 805905
Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8
TBR: tests updated to follow the API change.
Reviewed-on: https://chromium-review.googlesource.com/894702
Reviewed-by: David Vallet <[email protected]>
Reviewed-by: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533515}
CWE ID: CWE-125 | explicit RemoveDownloadsTester(TestingProfile* testing_profile)
: download_manager_(new content::MockDownloadManager()) {
content::BrowserContext::SetDownloadManagerForTesting(
testing_profile, base::WrapUnique(download_manager_));
std::unique_ptr<ChromeDownloadManagerDelegate> delegate =
std::make_unique<ChromeDownloadManagerDelegate>(testing_profile);
chrome_download_manager_delegate_ = delegate.get();
service_ =
DownloadCoreServiceFactory::GetForBrowserContext(testing_profile);
service_->SetDownloadManagerDelegateForTesting(std::move(delegate));
EXPECT_CALL(*download_manager_, GetBrowserContext())
.WillRepeatedly(Return(testing_profile));
EXPECT_CALL(*download_manager_, Shutdown());
}
| 173,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
unsigned char buff[128];
int r, i;
size_t field_length = 0, modulus_length = 0;
sc_path_t tmppath;
set_string (&p15card->tokeninfo->label, "ID-kaart");
set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus");
/* Select application directory */
sc_format_path ("3f00eeee5044", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed");
/* read the serial (document number) */
r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed");
buff[r] = '\0';
set_string (&p15card->tokeninfo->serial_number, (const char *) buff);
p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION
| SC_PKCS15_TOKEN_EID_COMPLIANT
| SC_PKCS15_TOKEN_READONLY;
/* add certificates */
for (i = 0; i < 2; i++) {
static const char *esteid_cert_names[2] = {
"Isikutuvastus",
"Allkirjastamine"};
static char const *esteid_cert_paths[2] = {
"3f00eeeeaace",
"3f00eeeeddce"};
static int esteid_cert_ids[2] = {1, 2};
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id.value[0] = esteid_cert_ids[i];
cert_info.id.len = 1;
sc_format_path(esteid_cert_paths[i], &cert_info.path);
strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if (r < 0)
return SC_ERROR_INTERNAL;
if (i == 0) {
sc_pkcs15_cert_t *cert = NULL;
r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert);
if (r < 0)
return SC_ERROR_INTERNAL;
if (cert->key->algorithm == SC_ALGORITHM_EC)
field_length = cert->key->u.ec.params.field_length;
else
modulus_length = cert->key->u.rsa.modulus.len * 8;
if (r == SC_SUCCESS) {
static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
u8 *cn_name = NULL;
size_t cn_len = 0;
sc_pkcs15_get_name_from_dn(card->ctx, cert->subject,
cert->subject_len, &cn_oid, &cn_name, &cn_len);
if (cn_len > 0) {
char *token_name = malloc(cn_len+1);
if (token_name) {
memcpy(token_name, cn_name, cn_len);
token_name[cn_len] = '\0';
set_string(&p15card->tokeninfo->label, (const char*)token_name);
free(token_name);
}
}
free(cn_name);
sc_pkcs15_free_certificate(cert);
}
}
}
/* the file with key pin info (tries left) */
sc_format_path ("3f000016", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
if (r < 0)
return SC_ERROR_INTERNAL;
/* add pins */
for (i = 0; i < 3; i++) {
unsigned char tries_left;
static const char *esteid_pin_names[3] = {
"PIN1",
"PIN2",
"PUK" };
static const int esteid_pin_min[3] = {4, 5, 8};
static const int esteid_pin_ref[3] = {1, 2, 0};
static const int esteid_pin_authid[3] = {1, 2, 3};
static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN};
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
/* read the number of tries left for the PIN */
r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
if (r < 0)
return SC_ERROR_INTERNAL;
tries_left = buff[5];
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = esteid_pin_authid[i];
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = esteid_pin_ref[i];
pin_info.attrs.pin.flags = esteid_pin_flags[i];
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = esteid_pin_min[i];
pin_info.attrs.pin.stored_length = 12;
pin_info.attrs.pin.max_length = 12;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = (int)tries_left;
pin_info.max_tries = 3;
strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label));
pin_obj.flags = esteid_pin_flags[i];
/* Link normal PINs with PUK */
if (i < 2) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 3;
}
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
/* add private keys */
for (i = 0; i < 2; i++) {
static int prkey_pin[2] = {1, 2};
static const char *prkey_name[2] = {
"Isikutuvastus",
"Allkirjastamine"};
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
memset(&prkey_info, 0, sizeof(prkey_info));
memset(&prkey_obj, 0, sizeof(prkey_obj));
prkey_info.id.len = 1;
prkey_info.id.value[0] = prkey_pin[i];
prkey_info.native = 1;
prkey_info.key_reference = i + 1;
prkey_info.field_length = field_length;
prkey_info.modulus_length = modulus_length;
if (i == 1)
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
else if(field_length > 0) // ECC has sign and derive usage
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE;
else
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT;
strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label));
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = prkey_pin[i];
prkey_obj.user_consent = 0;
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if(field_length > 0)
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
else
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
return SC_SUCCESS;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
unsigned char buff[128];
int r, i;
size_t field_length = 0, modulus_length = 0;
sc_path_t tmppath;
set_string (&p15card->tokeninfo->label, "ID-kaart");
set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus");
/* Select application directory */
sc_format_path ("3f00eeee5044", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed");
/* read the serial (document number) */
r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed");
buff[MIN((size_t) r, (sizeof buff)-1)] = '\0';
set_string (&p15card->tokeninfo->serial_number, (const char *) buff);
p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION
| SC_PKCS15_TOKEN_EID_COMPLIANT
| SC_PKCS15_TOKEN_READONLY;
/* add certificates */
for (i = 0; i < 2; i++) {
static const char *esteid_cert_names[2] = {
"Isikutuvastus",
"Allkirjastamine"};
static char const *esteid_cert_paths[2] = {
"3f00eeeeaace",
"3f00eeeeddce"};
static int esteid_cert_ids[2] = {1, 2};
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id.value[0] = esteid_cert_ids[i];
cert_info.id.len = 1;
sc_format_path(esteid_cert_paths[i], &cert_info.path);
strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if (r < 0)
return SC_ERROR_INTERNAL;
if (i == 0) {
sc_pkcs15_cert_t *cert = NULL;
r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert);
if (r < 0)
return SC_ERROR_INTERNAL;
if (cert->key->algorithm == SC_ALGORITHM_EC)
field_length = cert->key->u.ec.params.field_length;
else
modulus_length = cert->key->u.rsa.modulus.len * 8;
if (r == SC_SUCCESS) {
static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
u8 *cn_name = NULL;
size_t cn_len = 0;
sc_pkcs15_get_name_from_dn(card->ctx, cert->subject,
cert->subject_len, &cn_oid, &cn_name, &cn_len);
if (cn_len > 0) {
char *token_name = malloc(cn_len+1);
if (token_name) {
memcpy(token_name, cn_name, cn_len);
token_name[cn_len] = '\0';
set_string(&p15card->tokeninfo->label, (const char*)token_name);
free(token_name);
}
}
free(cn_name);
sc_pkcs15_free_certificate(cert);
}
}
}
/* the file with key pin info (tries left) */
sc_format_path ("3f000016", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
if (r < 0)
return SC_ERROR_INTERNAL;
/* add pins */
for (i = 0; i < 3; i++) {
unsigned char tries_left;
static const char *esteid_pin_names[3] = {
"PIN1",
"PIN2",
"PUK" };
static const int esteid_pin_min[3] = {4, 5, 8};
static const int esteid_pin_ref[3] = {1, 2, 0};
static const int esteid_pin_authid[3] = {1, 2, 3};
static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN};
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
/* read the number of tries left for the PIN */
r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
if (r < 0)
return SC_ERROR_INTERNAL;
tries_left = buff[5];
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = esteid_pin_authid[i];
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = esteid_pin_ref[i];
pin_info.attrs.pin.flags = esteid_pin_flags[i];
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = esteid_pin_min[i];
pin_info.attrs.pin.stored_length = 12;
pin_info.attrs.pin.max_length = 12;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = (int)tries_left;
pin_info.max_tries = 3;
strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label));
pin_obj.flags = esteid_pin_flags[i];
/* Link normal PINs with PUK */
if (i < 2) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 3;
}
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
/* add private keys */
for (i = 0; i < 2; i++) {
static int prkey_pin[2] = {1, 2};
static const char *prkey_name[2] = {
"Isikutuvastus",
"Allkirjastamine"};
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
memset(&prkey_info, 0, sizeof(prkey_info));
memset(&prkey_obj, 0, sizeof(prkey_obj));
prkey_info.id.len = 1;
prkey_info.id.value[0] = prkey_pin[i];
prkey_info.native = 1;
prkey_info.key_reference = i + 1;
prkey_info.field_length = field_length;
prkey_info.modulus_length = modulus_length;
if (i == 1)
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
else if(field_length > 0) // ECC has sign and derive usage
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE;
else
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT;
strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label));
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = prkey_pin[i];
prkey_obj.user_consent = 0;
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if(field_length > 0)
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
else
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
return SC_SUCCESS;
}
| 169,076 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
{
/* Reuse the standard stuff as appropriate. */
standard_info_part1(&dp->this, pp, pi);
/* If requested strip 16 to 8 bits - this is handled automagically below
* because the output bit depth is read from the library. Note that there
* are interactions with sBIT but, internally, libpng makes sbit at most
* PNG_MAX_GAMMA_8 when doing the following.
*/
if (dp->scale16)
# ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
png_set_scale_16(pp);
# else
/* The following works both in 1.5.4 and earlier versions: */
# ifdef PNG_READ_16_TO_8_SUPPORTED
png_set_strip_16(pp);
# else
png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
# endif
# endif
if (dp->expand16)
# ifdef PNG_READ_EXPAND_16_SUPPORTED
png_set_expand_16(pp);
# else
png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
# endif
if (dp->do_background >= ALPHA_MODE_OFFSET)
{
# ifdef PNG_READ_ALPHA_MODE_SUPPORTED
{
/* This tests the alpha mode handling, if supported. */
int mode = dp->do_background - ALPHA_MODE_OFFSET;
/* The gamma value is the output gamma, and is in the standard,
* non-inverted, represenation. It provides a default for the PNG file
* gamma, but since the file has a gAMA chunk this does not matter.
*/
PNG_CONST double sg = dp->screen_gamma;
# ifndef PNG_FLOATING_POINT_SUPPORTED
PNG_CONST png_fixed_point g = fix(sg);
# endif
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_alpha_mode(pp, mode, sg);
# else
png_set_alpha_mode_fixed(pp, mode, g);
# endif
/* However, for the standard Porter-Duff algorithm the output defaults
* to be linear, so if the test requires non-linear output it must be
* corrected here.
*/
if (mode == PNG_ALPHA_STANDARD && sg != 1)
{
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_gamma(pp, sg, dp->file_gamma);
# else
png_fixed_point f = fix(dp->file_gamma);
png_set_gamma_fixed(pp, g, f);
# endif
}
}
# else
png_error(pp, "alpha mode handling not supported");
# endif
}
else
{
/* Set up gamma processing. */
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
# else
{
png_fixed_point s = fix(dp->screen_gamma);
png_fixed_point f = fix(dp->file_gamma);
png_set_gamma_fixed(pp, s, f);
}
# endif
if (dp->do_background)
{
# ifdef PNG_READ_BACKGROUND_SUPPORTED
/* NOTE: this assumes the caller provided the correct background gamma!
*/
PNG_CONST double bg = dp->background_gamma;
# ifndef PNG_FLOATING_POINT_SUPPORTED
PNG_CONST png_fixed_point g = fix(bg);
# endif
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_background(pp, &dp->background_color, dp->do_background,
0/*need_expand*/, bg);
# else
png_set_background_fixed(pp, &dp->background_color,
dp->do_background, 0/*need_expand*/, g);
# endif
# else
png_error(pp, "png_set_background not supported");
# endif
}
}
{
int i = dp->this.use_update_info;
/* Always do one call, even if use_update_info is 0. */
do
png_read_update_info(pp, pi);
while (--i > 0);
}
/* Now we may get a different cbRow: */
standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
{
/* Reuse the standard stuff as appropriate. */
standard_info_part1(&dp->this, pp, pi);
/* If requested strip 16 to 8 bits - this is handled automagically below
* because the output bit depth is read from the library. Note that there
* are interactions with sBIT but, internally, libpng makes sbit at most
* PNG_MAX_GAMMA_8 prior to 1.7 when doing the following.
*/
if (dp->scale16)
# ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
png_set_scale_16(pp);
# else
/* The following works both in 1.5.4 and earlier versions: */
# ifdef PNG_READ_16_TO_8_SUPPORTED
png_set_strip_16(pp);
# else
png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
# endif
# endif
if (dp->expand16)
# ifdef PNG_READ_EXPAND_16_SUPPORTED
png_set_expand_16(pp);
# else
png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
# endif
if (dp->do_background >= ALPHA_MODE_OFFSET)
{
# ifdef PNG_READ_ALPHA_MODE_SUPPORTED
{
/* This tests the alpha mode handling, if supported. */
int mode = dp->do_background - ALPHA_MODE_OFFSET;
/* The gamma value is the output gamma, and is in the standard,
* non-inverted, represenation. It provides a default for the PNG file
* gamma, but since the file has a gAMA chunk this does not matter.
*/
const double sg = dp->screen_gamma;
# ifndef PNG_FLOATING_POINT_SUPPORTED
const png_fixed_point g = fix(sg);
# endif
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_alpha_mode(pp, mode, sg);
# else
png_set_alpha_mode_fixed(pp, mode, g);
# endif
/* However, for the standard Porter-Duff algorithm the output defaults
* to be linear, so if the test requires non-linear output it must be
* corrected here.
*/
if (mode == PNG_ALPHA_STANDARD && sg != 1)
{
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_gamma(pp, sg, dp->file_gamma);
# else
png_fixed_point f = fix(dp->file_gamma);
png_set_gamma_fixed(pp, g, f);
# endif
}
}
# else
png_error(pp, "alpha mode handling not supported");
# endif
}
else
{
/* Set up gamma processing. */
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
# else
{
png_fixed_point s = fix(dp->screen_gamma);
png_fixed_point f = fix(dp->file_gamma);
png_set_gamma_fixed(pp, s, f);
}
# endif
if (dp->do_background)
{
# ifdef PNG_READ_BACKGROUND_SUPPORTED
/* NOTE: this assumes the caller provided the correct background gamma!
*/
const double bg = dp->background_gamma;
# ifndef PNG_FLOATING_POINT_SUPPORTED
const png_fixed_point g = fix(bg);
# endif
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_background(pp, &dp->background_color, dp->do_background,
0/*need_expand*/, bg);
# else
png_set_background_fixed(pp, &dp->background_color,
dp->do_background, 0/*need_expand*/, g);
# endif
# else
png_error(pp, "png_set_background not supported");
# endif
}
}
{
int i = dp->this.use_update_info;
/* Always do one call, even if use_update_info is 0. */
do
png_read_update_info(pp, pi);
while (--i > 0);
}
/* Now we may get a different cbRow: */
standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
}
| 173,613 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.