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: BlockEntry::Kind BlockGroup::GetKind() const
{
return kBlockGroup;
}
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 | BlockEntry::Kind BlockGroup::GetKind() const
| 174,333 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
if (pos + 8 > len) {
return op->size;
}
int min_val = (ut32)(UINT (data, pos + 4)),
max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
if (pos + 4 >= len) {
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
}
Commit Message: Fix #10296 - Heap out of bounds read in java_switch_op()
CWE ID: CWE-125 | static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
if (pos + 8 + 8 > len) {
return op->size;
}
const int min_val = (ut32)(UINT (data, pos + 4));
const int max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
if (pos + 4 >= len) {
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
}
| 169,198 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: create_principal3_2_svc(cprinc3_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;
ret.api_version = handle->api_version;
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_ADD,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_ADD;
log_unauth("kadm5_create_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_create_principal_3((void *)handle,
&arg->rec, arg->mask,
arg->n_ks_tuple,
arg->ks_tuple,
arg->passwd);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_create_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 | create_principal3_2_svc(cprinc3_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;
ret.api_version = handle->api_version;
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_ADD,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_ADD;
log_unauth("kadm5_create_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_create_principal_3((void *)handle,
&arg->rec, arg->mask,
arg->n_ks_tuple,
arg->ks_tuple,
arg->passwd);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_create_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,509 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {
return -1;
}
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (JAS_CAST(jas_uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {
return -1;
}
return 0;
}
| 168,718 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FileBrowserPrivateGetShareUrlFunction::RunAsync() {
using extensions::api::file_browser_private::GetShareUrl::Params;
const scoped_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
const base::FilePath path = file_manager::util::GetLocalPathFromURL(
render_view_host(), GetProfile(), GURL(params->url));
DCHECK(drive::util::IsUnderDriveMountPoint(path));
const base::FilePath drive_path = drive::util::ExtractDrivePath(path);
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) {
return false;
}
file_system->GetShareUrl(
drive_path,
file_manager::util::GetFileManagerBaseUrl(), // embed origin
base::Bind(&FileBrowserPrivateGetShareUrlFunction::OnGetShareUrl, this));
return true;
}
Commit Message: Reland r286968: The CL borrows ShareDialog from Files.app and add it to Gallery.
Previous Review URL: https://codereview.chromium.org/431293002
BUG=374667
TEST=manually
[email protected], [email protected]
Review URL: https://codereview.chromium.org/433733004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286975 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool FileBrowserPrivateGetShareUrlFunction::RunAsync() {
using extensions::api::file_browser_private::GetShareUrl::Params;
const scoped_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
const base::FilePath path = file_manager::util::GetLocalPathFromURL(
render_view_host(), GetProfile(), GURL(params->url));
DCHECK(drive::util::IsUnderDriveMountPoint(path));
const base::FilePath drive_path = drive::util::ExtractDrivePath(path);
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) {
return false;
}
file_system->GetShareUrl(
drive_path,
GURL("chrome-extension://" + extension_id()), // embed origin
base::Bind(&FileBrowserPrivateGetShareUrlFunction::OnGetShareUrl, this));
return true;
}
| 171,194 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->fp[i]);
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->user, scm->fp->fp[i]);
}
| 167,395 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)
return res;
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
| 168,888 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: create_surface_from_thumbnail_data (guchar *data,
gint width,
gint height,
gint rowstride)
{
guchar *cairo_pixels;
cairo_surface_t *surface;
static cairo_user_data_key_t key;
int j;
cairo_pixels = (guchar *)g_malloc (4 * width * height);
surface = cairo_image_surface_create_for_data ((unsigned char *)cairo_pixels,
CAIRO_FORMAT_RGB24,
width, height, 4 * width);
cairo_surface_set_user_data (surface, &key,
cairo_pixels, (cairo_destroy_func_t)g_free);
for (j = height; j; j--) {
guchar *p = data;
guchar *q = cairo_pixels;
guchar *end = p + 3 * width;
while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
q[0] = p[2];
q[1] = p[1];
q[2] = p[0];
#else
q[1] = p[0];
q[2] = p[1];
q[3] = p[2];
#endif
p += 3;
q += 4;
}
data += rowstride;
cairo_pixels += 4 * width;
}
return surface;
}
Commit Message:
CWE ID: CWE-189 | create_surface_from_thumbnail_data (guchar *data,
gint width,
gint height,
gint rowstride)
{
guchar *cairo_pixels;
gint cairo_stride;
cairo_surface_t *surface;
int j;
surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
if (cairo_surface_status (surface))
return NULL;
cairo_pixels = cairo_image_surface_get_data (surface);
cairo_stride = cairo_image_surface_get_stride (surface);
for (j = height; j; j--) {
guchar *p = data;
guchar *q = cairo_pixels;
guchar *end = p + 3 * width;
while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
q[0] = p[2];
q[1] = p[1];
q[2] = p[0];
#else
q[1] = p[0];
q[2] = p[1];
q[3] = p[2];
#endif
p += 3;
q += 4;
}
data += rowstride;
cairo_pixels += cairo_stride;
}
return surface;
}
| 164,601 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SupervisedUserService::InitSync(const std::string& refresh_token) {
ProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
token_service->UpdateCredentials(supervised_users::kSupervisedUserPseudoEmail,
refresh_token);
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void SupervisedUserService::InitSync(const std::string& refresh_token) {
ProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
token_service->UpdateCredentials(
supervised_users::kSupervisedUserPseudoEmail, refresh_token,
signin_metrics::SourceForRefreshTokenOperation::kSupervisedUser_InitSync);
}
| 172,569 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CanCommitURL(const GURL& url) {
SchemeMap::const_iterator judgment(scheme_policy_.find(url.scheme()));
if (judgment != scheme_policy_.end())
return judgment->second;
if (url.SchemeIs(url::kFileScheme)) {
base::FilePath path;
if (net::FileURLToFilePath(url, &path))
return ContainsKey(request_file_set_, path);
}
return false; // Unmentioned schemes are disallowed.
}
Commit Message: This patch implements a mechanism for more granular link URL permissions (filtering on scheme/host). This fixes the bug that allowed PDFs to have working links to any "chrome://" URLs.
BUG=528505,226927
Review URL: https://codereview.chromium.org/1362433002
Cr-Commit-Position: refs/heads/master@{#351705}
CWE ID: CWE-264 | bool CanCommitURL(const GURL& url) {
// Having permission to a scheme implies permission to all of its URLs.
SchemeMap::const_iterator scheme_judgment(
scheme_policy_.find(url.scheme()));
if (scheme_judgment != scheme_policy_.end())
return scheme_judgment->second;
// Otherwise, check for permission for specific origin.
if (ContainsKey(origin_set_, url::Origin(url)))
return true;
if (url.SchemeIs(url::kFileScheme)) {
base::FilePath path;
if (net::FileURLToFilePath(url, &path))
return ContainsKey(request_file_set_, path);
}
return false; // Unmentioned schemes are disallowed.
}
| 171,775 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Initialize(ChannelLayout channel_layout, int bits_per_channel) {
AudioParameters params(
media::AudioParameters::AUDIO_PCM_LINEAR, channel_layout,
kSamplesPerSecond, bits_per_channel, kRawDataSize);
algorithm_.Initialize(1, params, base::Bind(
&AudioRendererAlgorithmTest::EnqueueData, base::Unretained(this)));
EnqueueData();
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void Initialize(ChannelLayout channel_layout, int bits_per_channel) {
void Initialize(ChannelLayout channel_layout, int bits_per_channel,
int samples_per_second) {
static const int kFrames = kRawDataSize / ((kDefaultSampleBits / 8) *
ChannelLayoutToChannelCount(kDefaultChannelLayout));
AudioParameters params(
media::AudioParameters::AUDIO_PCM_LINEAR, channel_layout,
samples_per_second, bits_per_channel, kFrames);
algorithm_.Initialize(1, params, base::Bind(
&AudioRendererAlgorithmTest::EnqueueData, base::Unretained(this)));
EnqueueData();
}
| 171,534 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mcid_char_imp(fz_context *ctx, pdf_filter_processor *p, tag_record *tr, int uni, int remove)
{
if (tr->mcid_obj == NULL)
/* No object, or already deleted */
return;
if (remove)
{
/* Remove the expanded abbreviation, if there is one. */
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(E));
/* Remove the structure title, if there is one. */
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(T));
}
/* Edit the Alt string */
walk_string(ctx, uni, remove, &tr->alt);
/* Edit the ActualText string */
walk_string(ctx, uni, remove, &tr->actualtext);
/* If we're removing a character, and either of the strings
* haven't matched up to what we were expecting, then just
* delete the whole string. */
else if (tr->alt.pos >= 0 || tr->actualtext.pos >= 0)
{
/* The strings are making sense so far */
remove = 0;
/* The strings are making sense so far */
remove = 0;
}
if (remove)
{
/* Anything else we have to err on the side of caution and
if (tr->alt.pos == -1)
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(Alt));
pdf_drop_obj(ctx, tr->mcid_obj);
tr->mcid_obj = NULL;
fz_free(ctx, tr->alt.utf8);
tr->alt.utf8 = NULL;
fz_free(ctx, tr->actualtext.utf8);
tr->actualtext.utf8 = NULL;
}
}
Commit Message:
CWE ID: CWE-125 | mcid_char_imp(fz_context *ctx, pdf_filter_processor *p, tag_record *tr, int uni, int remove)
{
if (tr->mcid_obj == NULL)
/* No object, or already deleted */
return;
if (remove)
{
/* Remove the expanded abbreviation, if there is one. */
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(E));
/* Remove the structure title, if there is one. */
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(T));
}
/* Edit the Alt string */
walk_string(ctx, uni, remove, &tr->alt);
/* Edit the ActualText string */
walk_string(ctx, uni, remove, &tr->actualtext);
/* If we're removing a character, and either of the strings
* haven't matched up to what we were expecting, then just
* delete the whole string. */
else if (tr->alt.pos >= 0 || tr->actualtext.pos >= 0)
{
/* The strings are making sense so far */
remove = 0;
/* The strings are making sense so far */
remove = 0;
}
if (remove)
{
/* Anything else we have to err on the side of caution and
if (tr->alt.pos == -1)
pdf_dict_del(ctx, tr->mcid_obj, PDF_NAME(Alt));
pdf_drop_obj(ctx, tr->mcid_obj);
tr->mcid_obj = NULL;
fz_free(ctx, tr->alt.utf8);
tr->alt.utf8 = NULL;
fz_free(ctx, tr->actualtext.utf8);
tr->actualtext.utf8 = NULL;
}
}
| 164,659 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int cur, l;
xmlChar stop;
int state = ctxt->instate;
int count = 0;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_SYSTEM_LITERAL;
cur = CUR_CHAR(l);
while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = (xmlParserInputState) state;
return(NULL);
}
buf = tmp;
}
count++;
if (count > 50) {
GROW;
count = 0;
}
COPY_BUF(l,buf,len,cur);
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
GROW;
SHRINK;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
ctxt->instate = (xmlParserInputState) state;
if (!IS_CHAR(cur)) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
return(buf);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int cur, l;
xmlChar stop;
int state = ctxt->instate;
int count = 0;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_SYSTEM_LITERAL;
cur = CUR_CHAR(l);
while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = (xmlParserInputState) state;
return(NULL);
}
buf = tmp;
}
count++;
if (count > 50) {
GROW;
count = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
}
COPY_BUF(l,buf,len,cur);
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
GROW;
SHRINK;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
ctxt->instate = (xmlParserInputState) state;
if (!IS_CHAR(cur)) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
return(buf);
}
| 171,306 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AccessibilityButtonState AXObject::checkboxOrRadioValue() const {
const AtomicString& checkedAttribute =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked);
if (equalIgnoringCase(checkedAttribute, "true"))
return ButtonStateOn;
if (equalIgnoringCase(checkedAttribute, "mixed")) {
AccessibilityRole role = ariaRoleAttribute();
if (role == CheckBoxRole || role == MenuItemCheckBoxRole)
return ButtonStateMixed;
}
return ButtonStateOff;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | AccessibilityButtonState AXObject::checkboxOrRadioValue() const {
const AtomicString& checkedAttribute =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked);
if (equalIgnoringASCIICase(checkedAttribute, "true"))
return ButtonStateOn;
if (equalIgnoringASCIICase(checkedAttribute, "mixed")) {
AccessibilityRole role = ariaRoleAttribute();
if (role == CheckBoxRole || role == MenuItemCheckBoxRole)
return ButtonStateMixed;
}
return ButtonStateOff;
}
| 171,924 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mailimf_group_parse(const char * message, size_t length,
size_t * indx,
struct mailimf_group ** result)
{
size_t cur_token;
char * display_name;
struct mailimf_mailbox_list * mailbox_list;
struct mailimf_group * group;
int r;
int res;
cur_token = * indx;
mailbox_list = NULL;
r = mailimf_display_name_parse(message, length, &cur_token, &display_name);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto err;
}
r = mailimf_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_display_name;
}
r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list);
switch (r) {
case MAILIMF_NO_ERROR:
break;
case MAILIMF_ERROR_PARSE:
r = mailimf_cfws_parse(message, length, &cur_token);
if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) {
res = r;
goto free_display_name;
}
break;
default:
res = r;
goto free_display_name;
}
r = mailimf_semi_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_mailbox_list;
}
group = mailimf_group_new(display_name, mailbox_list);
if (group == NULL) {
res = MAILIMF_ERROR_MEMORY;
goto free_mailbox_list;
}
* indx = cur_token;
* result = group;
return MAILIMF_NO_ERROR;
free_mailbox_list:
if (mailbox_list != NULL) {
mailimf_mailbox_list_free(mailbox_list);
}
free_display_name:
mailimf_display_name_free(display_name);
err:
return res;
}
Commit Message: Fixed crash #274
CWE ID: CWE-476 | static int mailimf_group_parse(const char * message, size_t length,
size_t * indx,
struct mailimf_group ** result)
{
size_t cur_token;
char * display_name;
struct mailimf_mailbox_list * mailbox_list;
struct mailimf_group * group;
int r;
int res;
clist * list;
cur_token = * indx;
mailbox_list = NULL;
r = mailimf_display_name_parse(message, length, &cur_token, &display_name);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto err;
}
r = mailimf_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_display_name;
}
r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list);
switch (r) {
case MAILIMF_NO_ERROR:
break;
case MAILIMF_ERROR_PARSE:
r = mailimf_cfws_parse(message, length, &cur_token);
if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) {
res = r;
goto free_display_name;
}
list = clist_new();
if (list == NULL) {
res = MAILIMF_ERROR_MEMORY;
goto free_display_name;
}
mailbox_list = mailimf_mailbox_list_new(list);
if (mailbox_list == NULL) {
res = MAILIMF_ERROR_MEMORY;
clist_free(list);
goto free_display_name;
}
break;
default:
res = r;
goto free_display_name;
}
r = mailimf_semi_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_mailbox_list;
}
group = mailimf_group_new(display_name, mailbox_list);
if (group == NULL) {
res = MAILIMF_ERROR_MEMORY;
goto free_mailbox_list;
}
* indx = cur_token;
* result = group;
return MAILIMF_NO_ERROR;
free_mailbox_list:
if (mailbox_list != NULL) {
mailimf_mailbox_list_free(mailbox_list);
}
free_display_name:
mailimf_display_name_free(display_name);
err:
return res;
}
| 168,192 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {
int i, j, sym, wordsize;
ut32 stype;
wordsize = MACH0_(get_bits)(bin) / 8;
if (idx < 0 || idx >= bin->nsymtab) {
return 0;
}
if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {
stype = S_LAZY_SYMBOL_POINTERS;
} else {
stype = S_NON_LAZY_SYMBOL_POINTERS;
}
reloc->offset = 0;
reloc->addr = 0;
reloc->addend = 0;
#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break
switch (wordsize) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
default: return false;
}
#undef CASE
for (i = 0; i < bin->nsects; i++) {
if ((bin->sects[i].flags & SECTION_TYPE) == stype) {
for (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++)
if (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) {
sym = j;
break;
}
reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;
reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;
return true;
}
}
return false;
}
Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026)
CWE ID: CWE-125 | static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {
int i, j, sym, wordsize;
ut32 stype;
wordsize = MACH0_(get_bits)(bin) / 8;
if (idx < 0 || idx >= bin->nsymtab) {
return 0;
}
if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {
stype = S_LAZY_SYMBOL_POINTERS;
} else {
stype = S_NON_LAZY_SYMBOL_POINTERS;
}
reloc->offset = 0;
reloc->addr = 0;
reloc->addend = 0;
#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break
switch (wordsize) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
default: return false;
}
#undef CASE
for (i = 0; i < bin->nsects; i++) {
if ((bin->sects[i].flags & SECTION_TYPE) == stype) {
for (j = 0, sym = -1; bin->sects[i].reserved1 + j < bin->nindirectsyms; j++) {
int indidx = bin->sects[i].reserved1 + j;
if (indidx < 0 || indidx >= bin->nindirectsyms) {
break;
}
if (idx == bin->indirectsyms[indidx]) {
sym = j;
break;
}
}
reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;
reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;
return true;
}
}
return false;
}
| 169,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void common_hrtimer_rearm(struct k_itimer *timr)
{
struct hrtimer *timer = &timr->it.real.timer;
if (!timr->it_interval)
return;
timr->it_overrun += (unsigned int) hrtimer_forward(timer,
timer->base->get_time(),
timr->it_interval);
hrtimer_restart(timer);
}
Commit Message: posix-timers: Sanitize overrun handling
The posix timer overrun handling is broken because the forwarding functions
can return a huge number of overruns which does not fit in an int. As a
consequence timer_getoverrun(2) and siginfo::si_overrun can turn into
random number generators.
The k_clock::timer_forward() callbacks return a 64 bit value now. Make
k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal
accounting is correct. 3Remove the temporary (int) casts.
Add a helper function which clamps the overrun value returned to user space
via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value
between 0 and INT_MAX. INT_MAX is an indicator for user space that the
overrun value has been clamped.
Reported-by: Team OWL337 <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Acked-by: John Stultz <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michael Kerrisk <[email protected]>
Link: https://lkml.kernel.org/r/[email protected]
CWE ID: CWE-190 | static void common_hrtimer_rearm(struct k_itimer *timr)
{
struct hrtimer *timer = &timr->it.real.timer;
if (!timr->it_interval)
return;
timr->it_overrun += hrtimer_forward(timer, timer->base->get_time(),
timr->it_interval);
hrtimer_restart(timer);
}
| 169,179 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: make_random_bytes(png_uint_32* seed, void* pv, size_t size)
{
png_uint_32 u0 = seed[0], u1 = seed[1];
png_bytep bytes = png_voidcast(png_bytep, pv);
/* There are thirty-three bits; the next bit in the sequence is bit-33 XOR
* bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
*/
size_t i;
for (i=0; i<size; ++i)
{
/* First generate 8 new bits then shift them in at the end. */
png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
u1 <<= 8;
u1 |= u0 >> 24;
u0 <<= 8;
u0 |= u;
*bytes++ = (png_byte)u;
}
seed[0] = u0;
seed[1] = u1;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | make_random_bytes(png_uint_32* seed, void* pv, size_t size)
{
png_uint_32 u0 = seed[0], u1 = seed[1];
png_bytep bytes = voidcast(png_bytep, pv);
/* There are thirty-three bits; the next bit in the sequence is bit-33 XOR
* bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
*/
size_t i;
for (i=0; i<size; ++i)
{
/* First generate 8 new bits then shift them in at the end. */
png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
u1 <<= 8;
u1 |= u0 >> 24;
u0 <<= 8;
u0 |= u;
*bytes++ = (png_byte)u;
}
seed[0] = u0;
seed[1] = u1;
}
| 173,736 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintPreviewUI::OnReusePreviewData(int preview_request_id) {
base::StringValue ui_identifier(preview_ui_addr_str_);
base::FundamentalValue ui_preview_request_id(preview_request_id);
web_ui()->CallJavascriptFunction("reloadPreviewPages", ui_identifier,
ui_preview_request_id);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewUI::OnReusePreviewData(int preview_request_id) {
base::FundamentalValue ui_identifier(id_);
base::FundamentalValue ui_preview_request_id(preview_request_id);
web_ui()->CallJavascriptFunction("reloadPreviewPages", ui_identifier,
ui_preview_request_id);
}
| 170,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){
long i;
for(i=0; i<=w-sizeof(long); i+=sizeof(long)){
long a = *(long*)(src+i);
long b = *(long*)(dst+i);
*(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80);
}
for(; i<w; i++)
dst[i+0] += src[i+0];
}
Commit Message: avcodec/dsputil: fix signedness in sizeof() comparissions
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-189 | static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){
long i;
for(i=0; i<=w-(int)sizeof(long); i+=sizeof(long)){
long a = *(long*)(src+i);
long b = *(long*)(dst+i);
*(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80);
}
for(; i<w; i++)
dst[i+0] += src[i+0];
}
| 165,929 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cluster::CreateSimpleBlock(
long long st,
long long sz)
{
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count >= 0);
assert(m_entries_count < m_entries_size);
const long idx = m_entries_count;
BlockEntry** const ppEntry = m_entries + idx;
BlockEntry*& pEntry = *ppEntry;
pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz);
if (pEntry == NULL)
return -1; //generic error
SimpleBlock* const p = static_cast<SimpleBlock*>(pEntry);
const long status = p->Parse();
if (status == 0)
{
++m_entries_count;
return 0;
}
delete pEntry;
pEntry = 0;
return status;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Cluster::CreateSimpleBlock(
| 174,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,
const uint8_t *buf, int buf_size,
int first_field)
{
int i, cid, ret;
int old_bit_depth = ctx->bit_depth, bitdepth;
uint64_t header_prefix;
if (buf_size < 0x280) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < 640).\n", buf_size);
return AVERROR_INVALIDDATA;
}
header_prefix = ff_dnxhd_parse_header_prefix(buf);
if (header_prefix == 0) {
av_log(ctx->avctx, AV_LOG_ERROR,
"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",
buf[0], buf[1], buf[2], buf[3], buf[4]);
return AVERROR_INVALIDDATA;
}
if (buf[5] & 2) { /* interlaced */
ctx->cur_field = buf[5] & 1;
frame->interlaced_frame = 1;
frame->top_field_first = first_field ^ ctx->cur_field;
av_log(ctx->avctx, AV_LOG_DEBUG,
"interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
} else {
ctx->cur_field = 0;
}
ctx->mbaff = (buf[0x6] >> 5) & 1;
ctx->height = AV_RB16(buf + 0x18);
ctx->width = AV_RB16(buf + 0x1a);
switch(buf[0x21] >> 5) {
case 1: bitdepth = 8; break;
case 2: bitdepth = 10; break;
case 3: bitdepth = 12; break;
default:
av_log(ctx->avctx, AV_LOG_ERROR,
"Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);
return AVERROR_INVALIDDATA;
}
cid = AV_RB32(buf + 0x28);
ctx->avctx->profile = dnxhd_get_profile(cid);
if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)
return ret;
if (ctx->mbaff && ctx->cid_table->cid != 1260)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive MB interlace flag in an unsupported profile.\n");
ctx->act = buf[0x2C] & 7;
if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive color transform in an unsupported profile.\n");
ctx->is_444 = (buf[0x2C] >> 6) & 1;
if (ctx->is_444) {
if (bitdepth == 8) {
avpriv_request_sample(ctx->avctx, "4:4:4 8 bits");
return AVERROR_INVALIDDATA;
} else if (bitdepth == 10) {
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10
: AV_PIX_FMT_GBRP10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12
: AV_PIX_FMT_GBRP12;
}
} else if (bitdepth == 12) {
ctx->decode_dct_block = dnxhd_decode_dct_block_12;
ctx->pix_fmt = AV_PIX_FMT_YUV422P12;
} else if (bitdepth == 10) {
if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
else
ctx->decode_dct_block = dnxhd_decode_dct_block_10;
ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_8;
ctx->pix_fmt = AV_PIX_FMT_YUV422P;
}
ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;
if (ctx->bit_depth != old_bit_depth) {
ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
ff_idctdsp_init(&ctx->idsp, ctx->avctx);
ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,
ff_zigzag_direct);
}
if (ctx->width != ctx->cid_table->width &&
ctx->cid_table->width != DNXHD_VARIABLE) {
av_reduce(&ctx->avctx->sample_aspect_ratio.num,
&ctx->avctx->sample_aspect_ratio.den,
ctx->width, ctx->cid_table->width, 255);
ctx->width = ctx->cid_table->width;
}
if (buf_size < ctx->cid_table->coding_unit_size) {
av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n",
buf_size, ctx->cid_table->coding_unit_size);
return AVERROR_INVALIDDATA;
}
ctx->mb_width = (ctx->width + 15)>> 4;
ctx->mb_height = AV_RB16(buf + 0x16c);
if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)
ctx->height <<= 1;
av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",
ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",
ctx->bit_depth, ctx->mbaff, ctx->act);
if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {
ctx->data_offset = 0x170 + (ctx->mb_height << 2);
} else {
if (ctx->mb_height > 68 ||
(ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
ctx->data_offset = 0x280;
}
if (buf_size < ctx->data_offset) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < %d).\n", buf_size, ctx->data_offset);
return AVERROR_INVALIDDATA;
}
if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));
return AVERROR_INVALIDDATA;
}
for (i = 0; i < ctx->mb_height; i++) {
ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));
ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n",
i, 0x170 + (i << 2), ctx->mb_scan_index[i]);
if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {
av_log(ctx->avctx, AV_LOG_ERROR,
"invalid mb scan index (%"PRIu32" vs %u).\n",
ctx->mb_scan_index[i], buf_size - ctx->data_offset);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
Commit Message: avcodec/dnxhddec: Move mb height check out of non hr branch
Fixes: out of array access
Fixes: poc.dnxhd
Found-by: Bingchang, Liu@VARAS of IIE
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,
const uint8_t *buf, int buf_size,
int first_field)
{
int i, cid, ret;
int old_bit_depth = ctx->bit_depth, bitdepth;
uint64_t header_prefix;
if (buf_size < 0x280) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < 640).\n", buf_size);
return AVERROR_INVALIDDATA;
}
header_prefix = ff_dnxhd_parse_header_prefix(buf);
if (header_prefix == 0) {
av_log(ctx->avctx, AV_LOG_ERROR,
"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",
buf[0], buf[1], buf[2], buf[3], buf[4]);
return AVERROR_INVALIDDATA;
}
if (buf[5] & 2) { /* interlaced */
ctx->cur_field = buf[5] & 1;
frame->interlaced_frame = 1;
frame->top_field_first = first_field ^ ctx->cur_field;
av_log(ctx->avctx, AV_LOG_DEBUG,
"interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
} else {
ctx->cur_field = 0;
}
ctx->mbaff = (buf[0x6] >> 5) & 1;
ctx->height = AV_RB16(buf + 0x18);
ctx->width = AV_RB16(buf + 0x1a);
switch(buf[0x21] >> 5) {
case 1: bitdepth = 8; break;
case 2: bitdepth = 10; break;
case 3: bitdepth = 12; break;
default:
av_log(ctx->avctx, AV_LOG_ERROR,
"Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);
return AVERROR_INVALIDDATA;
}
cid = AV_RB32(buf + 0x28);
ctx->avctx->profile = dnxhd_get_profile(cid);
if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)
return ret;
if (ctx->mbaff && ctx->cid_table->cid != 1260)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive MB interlace flag in an unsupported profile.\n");
ctx->act = buf[0x2C] & 7;
if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive color transform in an unsupported profile.\n");
ctx->is_444 = (buf[0x2C] >> 6) & 1;
if (ctx->is_444) {
if (bitdepth == 8) {
avpriv_request_sample(ctx->avctx, "4:4:4 8 bits");
return AVERROR_INVALIDDATA;
} else if (bitdepth == 10) {
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10
: AV_PIX_FMT_GBRP10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12
: AV_PIX_FMT_GBRP12;
}
} else if (bitdepth == 12) {
ctx->decode_dct_block = dnxhd_decode_dct_block_12;
ctx->pix_fmt = AV_PIX_FMT_YUV422P12;
} else if (bitdepth == 10) {
if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
else
ctx->decode_dct_block = dnxhd_decode_dct_block_10;
ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_8;
ctx->pix_fmt = AV_PIX_FMT_YUV422P;
}
ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;
if (ctx->bit_depth != old_bit_depth) {
ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
ff_idctdsp_init(&ctx->idsp, ctx->avctx);
ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,
ff_zigzag_direct);
}
if (ctx->width != ctx->cid_table->width &&
ctx->cid_table->width != DNXHD_VARIABLE) {
av_reduce(&ctx->avctx->sample_aspect_ratio.num,
&ctx->avctx->sample_aspect_ratio.den,
ctx->width, ctx->cid_table->width, 255);
ctx->width = ctx->cid_table->width;
}
if (buf_size < ctx->cid_table->coding_unit_size) {
av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n",
buf_size, ctx->cid_table->coding_unit_size);
return AVERROR_INVALIDDATA;
}
ctx->mb_width = (ctx->width + 15)>> 4;
ctx->mb_height = AV_RB16(buf + 0x16c);
if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)
ctx->height <<= 1;
av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",
ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",
ctx->bit_depth, ctx->mbaff, ctx->act);
if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {
ctx->data_offset = 0x170 + (ctx->mb_height << 2);
} else {
if (ctx->mb_height > 68) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
ctx->data_offset = 0x280;
}
if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
if (buf_size < ctx->data_offset) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < %d).\n", buf_size, ctx->data_offset);
return AVERROR_INVALIDDATA;
}
if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));
return AVERROR_INVALIDDATA;
}
for (i = 0; i < ctx->mb_height; i++) {
ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));
ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n",
i, 0x170 + (i << 2), ctx->mb_scan_index[i]);
if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {
av_log(ctx->avctx, AV_LOG_ERROR,
"invalid mb scan index (%"PRIu32" vs %u).\n",
ctx->mb_scan_index[i], buf_size - ctx->data_offset);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
| 168,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: void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a)
{
BN_ULONG t1,t2;
BN_ULONG c1,c2,c3;
c1=0;
c2=0;
c3=0;
sqr_add_c(a,0,c1,c2,c3);
r[0]=c1;
c1=0;
sqr_add_c2(a,1,0,c2,c3,c1);
r[1]=c2;
c2=0;
sqr_add_c(a,1,c3,c1,c2);
sqr_add_c2(a,2,0,c3,c1,c2);
r[2]=c3;
c3=0;
sqr_add_c2(a,3,0,c1,c2,c3);
sqr_add_c2(a,2,1,c1,c2,c3);
r[3]=c1;
c1=0;
sqr_add_c(a,2,c2,c3,c1);
sqr_add_c2(a,3,1,c2,c3,c1);
r[4]=c2;
c2=0;
sqr_add_c2(a,3,2,c3,c1,c2);
r[5]=c3;
c3=0;
sqr_add_c(a,3,c1,c2,c3);
r[6]=c1;
r[7]=c2;
}
Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp).
Reviewed-by: Emilia Kasper <[email protected]>
CWE ID: CWE-310 | void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a)
{
BN_ULONG c1,c2,c3;
c1=0;
c2=0;
c3=0;
sqr_add_c(a,0,c1,c2,c3);
r[0]=c1;
c1=0;
sqr_add_c2(a,1,0,c2,c3,c1);
r[1]=c2;
c2=0;
sqr_add_c(a,1,c3,c1,c2);
sqr_add_c2(a,2,0,c3,c1,c2);
r[2]=c3;
c3=0;
sqr_add_c2(a,3,0,c1,c2,c3);
sqr_add_c2(a,2,1,c1,c2,c3);
r[3]=c1;
c1=0;
sqr_add_c(a,2,c2,c3,c1);
sqr_add_c2(a,3,1,c2,c3,c1);
r[4]=c2;
c2=0;
sqr_add_c2(a,3,2,c3,c1,c2);
r[5]=c3;
c3=0;
sqr_add_c(a,3,c1,c2,c3);
r[6]=c1;
r[7]=c2;
}
| 166,830 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (state_ == WORKER_READY) {
if (sessions().size() == 1) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&SetDevToolsAttachedOnIO,
context_weak_, version_id_, true));
}
session->SetRenderer(RenderProcessHost::FromID(worker_process_id_),
nullptr);
session->AttachToAgent(agent_ptr_);
}
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
}
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 ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (state_ == WORKER_READY) {
if (sessions().size() == 1) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&SetDevToolsAttachedOnIO,
context_weak_, version_id_, true));
}
session->SetRenderer(worker_process_id_, nullptr);
session->AttachToAgent(agent_ptr_);
}
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
}
| 172,783 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(openssl_seal)
{
zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL;
HashTable *pubkeysht;
EVP_PKEY **pkeys;
zend_resource ** key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys, iv_len;
unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks;
char * data;
size_t data_len;
char *method =NULL;
size_t method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX *ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/a/|sz/", &data, &data_len,
&sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) {
return;
}
pubkeysht = Z_ARRVAL_P(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
iv_len = EVP_CIPHER_iv_length(cipher);
if (!iv && iv_len > 0) {
php_error_docref(NULL, E_WARNING,
"Cipher algorithm requires an IV to be supplied as a sixth parameter");
RETURN_FALSE;
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0);
memset(key_resources, 0, sizeof(zend_resource*) * nkeys);
memset(pkeys, 0, sizeof(*pkeys) * nkeys);
/* get the public keys we are using to seal this data */
i = 0;
ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]);
if (pkeys[i] == NULL) {
php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
i++;
} ZEND_HASH_FOREACH_END();
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) {
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx));
EVP_CIPHER_CTX_cleanup(ctx);
if (!EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) ||
!EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) ||
!EVP_SealFinal(ctx, buf + len1, &len2)) {
efree(buf);
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
if (len1 + len2 > 0) {
zval_dtor(sealdata);
ZVAL_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0));
efree(buf);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]);
efree(eks[i]);
eks[i] = NULL;
}
if (iv) {
zval_dtor(iv);
iv_buf[iv_len] = '\0';
ZVAL_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0));
}
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_free(ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == NULL && pkeys[i] != NULL) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
Commit Message:
CWE ID: CWE-754 | PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL;
HashTable *pubkeysht;
EVP_PKEY **pkeys;
zend_resource ** key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys, iv_len;
unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks;
char * data;
size_t data_len;
char *method =NULL;
size_t method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX *ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/a/|sz/", &data, &data_len,
&sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) {
return;
}
pubkeysht = Z_ARRVAL_P(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
iv_len = EVP_CIPHER_iv_length(cipher);
if (!iv && iv_len > 0) {
php_error_docref(NULL, E_WARNING,
"Cipher algorithm requires an IV to be supplied as a sixth parameter");
RETURN_FALSE;
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0);
memset(key_resources, 0, sizeof(zend_resource*) * nkeys);
memset(pkeys, 0, sizeof(*pkeys) * nkeys);
/* get the public keys we are using to seal this data */
i = 0;
ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]);
if (pkeys[i] == NULL) {
php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
i++;
} ZEND_HASH_FOREACH_END();
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) {
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx));
EVP_CIPHER_CTX_cleanup(ctx);
if (EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) <= 0 ||
!EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) ||
!EVP_SealFinal(ctx, buf + len1, &len2)) {
efree(buf);
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
if (len1 + len2 > 0) {
zval_dtor(sealdata);
ZVAL_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0));
efree(buf);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]);
efree(eks[i]);
eks[i] = NULL;
}
if (iv) {
zval_dtor(iv);
iv_buf[iv_len] = '\0';
ZVAL_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0));
}
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_free(ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == NULL && pkeys[i] != NULL) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
| 164,756 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_get_val (MyObject *obj, guint *ret, GError **error)
{
*ret = obj->val;
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_get_val (MyObject *obj, guint *ret, GError **error)
| 165,103 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dump_mm(const struct mm_struct *mm)
{
pr_emerg("mm %px mmap %px seqnum %d task_size %lu\n"
#ifdef CONFIG_MMU
"get_unmapped_area %px\n"
#endif
"mmap_base %lu mmap_legacy_base %lu highest_vm_end %lu\n"
"pgd %px mm_users %d mm_count %d pgtables_bytes %lu map_count %d\n"
"hiwater_rss %lx hiwater_vm %lx total_vm %lx locked_vm %lx\n"
"pinned_vm %lx data_vm %lx exec_vm %lx stack_vm %lx\n"
"start_code %lx end_code %lx start_data %lx end_data %lx\n"
"start_brk %lx brk %lx start_stack %lx\n"
"arg_start %lx arg_end %lx env_start %lx env_end %lx\n"
"binfmt %px flags %lx core_state %px\n"
#ifdef CONFIG_AIO
"ioctx_table %px\n"
#endif
#ifdef CONFIG_MEMCG
"owner %px "
#endif
"exe_file %px\n"
#ifdef CONFIG_MMU_NOTIFIER
"mmu_notifier_mm %px\n"
#endif
#ifdef CONFIG_NUMA_BALANCING
"numa_next_scan %lu numa_scan_offset %lu numa_scan_seq %d\n"
#endif
"tlb_flush_pending %d\n"
"def_flags: %#lx(%pGv)\n",
mm, mm->mmap, mm->vmacache_seqnum, mm->task_size,
#ifdef CONFIG_MMU
mm->get_unmapped_area,
#endif
mm->mmap_base, mm->mmap_legacy_base, mm->highest_vm_end,
mm->pgd, atomic_read(&mm->mm_users),
atomic_read(&mm->mm_count),
mm_pgtables_bytes(mm),
mm->map_count,
mm->hiwater_rss, mm->hiwater_vm, mm->total_vm, mm->locked_vm,
mm->pinned_vm, mm->data_vm, mm->exec_vm, mm->stack_vm,
mm->start_code, mm->end_code, mm->start_data, mm->end_data,
mm->start_brk, mm->brk, mm->start_stack,
mm->arg_start, mm->arg_end, mm->env_start, mm->env_end,
mm->binfmt, mm->flags, mm->core_state,
#ifdef CONFIG_AIO
mm->ioctx_table,
#endif
#ifdef CONFIG_MEMCG
mm->owner,
#endif
mm->exe_file,
#ifdef CONFIG_MMU_NOTIFIER
mm->mmu_notifier_mm,
#endif
#ifdef CONFIG_NUMA_BALANCING
mm->numa_next_scan, mm->numa_scan_offset, mm->numa_scan_seq,
#endif
atomic_read(&mm->tlb_flush_pending),
mm->def_flags, &mm->def_flags
);
}
Commit Message: mm: get rid of vmacache_flush_all() entirely
Jann Horn points out that the vmacache_flush_all() function is not only
potentially expensive, it's buggy too. It also happens to be entirely
unnecessary, because the sequence number overflow case can be avoided by
simply making the sequence number be 64-bit. That doesn't even grow the
data structures in question, because the other adjacent fields are
already 64-bit.
So simplify the whole thing by just making the sequence number overflow
case go away entirely, which gets rid of all the complications and makes
the code faster too. Win-win.
[ Oleg Nesterov points out that the VMACACHE_FULL_FLUSHES statistics
also just goes away entirely with this ]
Reported-by: Jann Horn <[email protected]>
Suggested-by: Will Deacon <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416 | void dump_mm(const struct mm_struct *mm)
{
pr_emerg("mm %px mmap %px seqnum %llu task_size %lu\n"
#ifdef CONFIG_MMU
"get_unmapped_area %px\n"
#endif
"mmap_base %lu mmap_legacy_base %lu highest_vm_end %lu\n"
"pgd %px mm_users %d mm_count %d pgtables_bytes %lu map_count %d\n"
"hiwater_rss %lx hiwater_vm %lx total_vm %lx locked_vm %lx\n"
"pinned_vm %lx data_vm %lx exec_vm %lx stack_vm %lx\n"
"start_code %lx end_code %lx start_data %lx end_data %lx\n"
"start_brk %lx brk %lx start_stack %lx\n"
"arg_start %lx arg_end %lx env_start %lx env_end %lx\n"
"binfmt %px flags %lx core_state %px\n"
#ifdef CONFIG_AIO
"ioctx_table %px\n"
#endif
#ifdef CONFIG_MEMCG
"owner %px "
#endif
"exe_file %px\n"
#ifdef CONFIG_MMU_NOTIFIER
"mmu_notifier_mm %px\n"
#endif
#ifdef CONFIG_NUMA_BALANCING
"numa_next_scan %lu numa_scan_offset %lu numa_scan_seq %d\n"
#endif
"tlb_flush_pending %d\n"
"def_flags: %#lx(%pGv)\n",
mm, mm->mmap, (long long) mm->vmacache_seqnum, mm->task_size,
#ifdef CONFIG_MMU
mm->get_unmapped_area,
#endif
mm->mmap_base, mm->mmap_legacy_base, mm->highest_vm_end,
mm->pgd, atomic_read(&mm->mm_users),
atomic_read(&mm->mm_count),
mm_pgtables_bytes(mm),
mm->map_count,
mm->hiwater_rss, mm->hiwater_vm, mm->total_vm, mm->locked_vm,
mm->pinned_vm, mm->data_vm, mm->exec_vm, mm->stack_vm,
mm->start_code, mm->end_code, mm->start_data, mm->end_data,
mm->start_brk, mm->brk, mm->start_stack,
mm->arg_start, mm->arg_end, mm->env_start, mm->env_end,
mm->binfmt, mm->flags, mm->core_state,
#ifdef CONFIG_AIO
mm->ioctx_table,
#endif
#ifdef CONFIG_MEMCG
mm->owner,
#endif
mm->exe_file,
#ifdef CONFIG_MMU_NOTIFIER
mm->mmu_notifier_mm,
#endif
#ifdef CONFIG_NUMA_BALANCING
mm->numa_next_scan, mm->numa_scan_offset, mm->numa_scan_seq,
#endif
atomic_read(&mm->tlb_flush_pending),
mm->def_flags, &mm->def_flags
);
}
| 169,026 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TIFF_MetaHandler::ProcessXMP()
{
this->processedXMP = true; // Make sure we only come through here once.
bool found;
bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0);
if ( readOnly ) {
this->psirMgr = new PSIR_MemoryReader();
this->iptcMgr = new IPTC_Reader();
} else {
this->psirMgr = new PSIR_FileWriter();
this->iptcMgr = new IPTC_Writer(); // ! Parse it later.
}
TIFF_Manager & tiff = this->tiffMgr; // Give the compiler help in recognizing non-aliases.
PSIR_Manager & psir = *this->psirMgr;
IPTC_Manager & iptc = *this->iptcMgr;
TIFF_Manager::TagInfo psirInfo;
bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo );
if ( havePSIR ) { // ! Do the Photoshop 6 integration before other legacy analysis.
psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen );
PSIR_Manager::ImgRsrcInfo buriedExif;
found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif );
if ( found ) {
tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen );
if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif );
}
}
TIFF_Manager::TagInfo iptcInfo;
bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); // The TIFF IPTC tag.
int iptcDigestState = kDigestMatches;
if ( haveIPTC ) {
bool haveDigest = false;
PSIR_Manager::ImgRsrcInfo digestInfo;
if ( havePSIR ) haveDigest = psir.GetImgRsrc ( kPSIR_IPTCDigest, &digestInfo );
if ( digestInfo.dataLen != 16 ) haveDigest = false;
if ( ! haveDigest ) {
iptcDigestState = kDigestMissing;
} else {
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, iptcInfo.dataLen, digestInfo.dataPtr );
if ( (iptcDigestState == kDigestDiffers) && (kTIFF_TypeSizes[iptcInfo.type] > 1) ) {
XMP_Uns8 * endPtr = (XMP_Uns8*)iptcInfo.dataPtr + iptcInfo.dataLen - 1;
XMP_Uns8 * minPtr = endPtr - kTIFF_TypeSizes[iptcInfo.type] + 1;
while ( (endPtr >= minPtr) && (*endPtr == 0) ) --endPtr;
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, unpaddedLen, digestInfo.dataPtr );
}
}
}
XMP_OptionBits options = k2XMP_FileHadExif; // TIFF files are presumed to have Exif legacy.
if ( haveIPTC ) options |= k2XMP_FileHadIPTC;
if ( this->containsXMP ) options |= k2XMP_FileHadXMP;
bool haveXMP = false;
if ( ! this->xmpPacket.empty() ) {
XMP_Assert ( this->containsXMP );
XMP_StringPtr packetStr = this->xmpPacket.c_str();
XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size();
try {
this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
} catch ( ... ) { /* Ignore parsing failures, someday we hope to get partial XMP back. */ }
haveXMP = true;
}
if ( haveIPTC && (! haveXMP) && (iptcDigestState == kDigestMatches) ) iptcDigestState = kDigestMissing;
bool parseIPTC = (iptcDigestState != kDigestMatches) || (! readOnly);
if ( parseIPTC ) iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen );
ImportPhotoData ( tiff, iptc, psir, iptcDigestState, &this->xmpObj, options );
this->containsXMP = true; // Assume we now have something in the XMP.
} // TIFF_MetaHandler::ProcessXMP
Commit Message:
CWE ID: CWE-125 | void TIFF_MetaHandler::ProcessXMP()
{
this->processedXMP = true; // Make sure we only come through here once.
bool found;
bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0);
if ( readOnly ) {
this->psirMgr = new PSIR_MemoryReader();
this->iptcMgr = new IPTC_Reader();
} else {
this->psirMgr = new PSIR_FileWriter();
this->iptcMgr = new IPTC_Writer(); // ! Parse it later.
}
TIFF_Manager & tiff = this->tiffMgr; // Give the compiler help in recognizing non-aliases.
PSIR_Manager & psir = *this->psirMgr;
IPTC_Manager & iptc = *this->iptcMgr;
TIFF_Manager::TagInfo psirInfo;
bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo );
if ( havePSIR ) { // ! Do the Photoshop 6 integration before other legacy analysis.
psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen );
PSIR_Manager::ImgRsrcInfo buriedExif;
found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif );
if ( found ) {
tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen );
if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif );
}
}
TIFF_Manager::TagInfo iptcInfo;
bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); // The TIFF IPTC tag.
int iptcDigestState = kDigestMatches;
if ( haveIPTC ) {
bool haveDigest = false;
PSIR_Manager::ImgRsrcInfo digestInfo;
if ( havePSIR ) haveDigest = psir.GetImgRsrc ( kPSIR_IPTCDigest, &digestInfo );
if ( digestInfo.dataLen != 16 ) haveDigest = false;
if ( ! haveDigest ) {
iptcDigestState = kDigestMissing;
} else {
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, iptcInfo.dataLen, digestInfo.dataPtr );
// See bug https://bugs.freedesktop.org/show_bug.cgi?id=105205
// if iptcInfo.dataLen is 0, then there is no digest.
if ( (iptcDigestState == kDigestDiffers) && (kTIFF_TypeSizes[iptcInfo.type] > 1) && iptcInfo.dataLen > 0 ) {
XMP_Uns8 * endPtr = (XMP_Uns8*)iptcInfo.dataPtr + iptcInfo.dataLen - 1;
XMP_Uns8 * minPtr = endPtr - kTIFF_TypeSizes[iptcInfo.type] + 1;
while ( (endPtr >= minPtr) && (*endPtr == 0) ) --endPtr;
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, unpaddedLen, digestInfo.dataPtr );
}
}
}
XMP_OptionBits options = k2XMP_FileHadExif; // TIFF files are presumed to have Exif legacy.
if ( haveIPTC ) options |= k2XMP_FileHadIPTC;
if ( this->containsXMP ) options |= k2XMP_FileHadXMP;
bool haveXMP = false;
if ( ! this->xmpPacket.empty() ) {
XMP_Assert ( this->containsXMP );
XMP_StringPtr packetStr = this->xmpPacket.c_str();
XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size();
try {
this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
} catch ( ... ) { /* Ignore parsing failures, someday we hope to get partial XMP back. */ }
haveXMP = true;
}
if ( haveIPTC && (! haveXMP) && (iptcDigestState == kDigestMatches) ) iptcDigestState = kDigestMissing;
bool parseIPTC = (iptcDigestState != kDigestMatches) || (! readOnly);
if ( parseIPTC ) iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen );
ImportPhotoData ( tiff, iptc, psir, iptcDigestState, &this->xmpObj, options );
this->containsXMP = true; // Assume we now have something in the XMP.
} // TIFF_MetaHandler::ProcessXMP
| 164,996 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NodeIterator::~NodeIterator()
{
root()->document().detachNodeIterator(this);
}
Commit Message: Fix detached Attr nodes interaction with NodeIterator
- Don't register NodeIterator to document when attaching to Attr node.
-- NodeIterator is registered to its document to receive updateForNodeRemoval notifications.
-- However it wouldn't make sense on Attr nodes, as they never have children.
BUG=572537
Review URL: https://codereview.chromium.org/1577213003
Cr-Commit-Position: refs/heads/master@{#369687}
CWE ID: | NodeIterator::~NodeIterator()
{
if (!root()->isAttributeNode())
root()->document().detachNodeIterator(this);
}
| 172,143 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad sbounds\n");
return -EINVAL;
}
if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad ubounds\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
if (!env->allow_ptr_leaks)
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
if (!env->allow_ptr_leaks)
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit for now.
* (However, in principle we could allow some cases, e.g.
* ptr &= ~3 which would reduce min_value by 3.)
*/
if (!env->allow_ptr_leaks)
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
Commit Message: bpf: fix integer overflows
There were various issues related to the limited size of integers used in
the verifier:
- `off + size` overflow in __check_map_access()
- `off + reg->off` overflow in check_mem_access()
- `off + reg->var_off.value` overflow or 32-bit truncation of
`reg->var_off.value` in check_mem_access()
- 32-bit truncation in check_stack_boundary()
Make sure that any integer math cannot overflow by not allowing
pointer math with large values.
Also reduce the scope of "scalar op scalar" tracking.
Fixes: f1174f77b50c ("bpf/verifier: rework value tracking")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-190 | static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad sbounds\n");
return -EINVAL;
}
if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad ubounds\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
if (!env->allow_ptr_leaks)
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
!check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
return -EINVAL;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
if (!env->allow_ptr_leaks)
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit for now.
* (However, in principle we could allow some cases, e.g.
* ptr &= ~3 which would reduce min_value by 3.)
*/
if (!env->allow_ptr_leaks)
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
return -EINVAL;
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
| 167,643 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LayoutSVGTransformableContainer::calculateLocalTransform()
{
SVGGraphicsElement* element = toSVGGraphicsElement(this->element());
ASSERT(element);
SVGUseElement* useElement = nullptr;
if (isSVGUseElement(*element)) {
useElement = toSVGUseElement(element);
} else if (isSVGGElement(*element) && toSVGGElement(element)->inUseShadowTree()) {
SVGElement* correspondingElement = element->correspondingElement();
if (isSVGUseElement(correspondingElement))
useElement = toSVGUseElement(correspondingElement);
}
if (useElement) {
SVGLengthContext lengthContext(useElement);
FloatSize translation(
useElement->x()->currentValue()->value(lengthContext),
useElement->y()->currentValue()->value(lengthContext));
if (translation != m_additionalTranslation)
m_needsTransformUpdate = true;
m_additionalTranslation = translation;
}
if (!m_needsTransformUpdate)
return false;
m_localTransform = element->calculateAnimatedLocalTransform();
m_localTransform.translate(m_additionalTranslation.width(), m_additionalTranslation.height());
m_needsTransformUpdate = false;
return true;
}
Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers
Currently, SVG containers in the LayoutObject hierarchy force layout of
their children if the transform changes. The main reason for this is to
trigger paint invalidation of the subtree. In some cases - changes to the
scale factor - there are other reasons to trigger layout, like computing
a new scale factor for <text> or re-layout nodes with non-scaling stroke.
Compute a "scale-factor change" in addition to the "transform change"
already computed, then use this new signal to determine if layout should
be forced for the subtree. Trigger paint invalidation using the
LayoutObject flags instead.
The downside to this is that paint invalidation will walk into "hidden"
containers which rarely require repaint (since they are not technically
visible). This will hopefully be rectified in a follow-up CL.
For the testcase from 603850, this essentially eliminates the cost of
layout (from ~350ms to ~0ms on authors machine; layout cost is related
to text metrics recalculation), bumping frame rate significantly.
BUG=603956,603850
Review-Url: https://codereview.chromium.org/1996543002
Cr-Commit-Position: refs/heads/master@{#400950}
CWE ID: | bool LayoutSVGTransformableContainer::calculateLocalTransform()
void LayoutSVGTransformableContainer::setNeedsTransformUpdate()
{
setMayNeedPaintInvalidationSubtree();
m_needsTransformUpdate = true;
}
static std::pair<double, double> scaleReference(const AffineTransform& transform)
{
return std::make_pair(transform.xScaleSquared(), transform.yScaleSquared());
}
LayoutSVGContainer::TransformChange LayoutSVGTransformableContainer::calculateLocalTransform()
{
SVGGraphicsElement* element = toSVGGraphicsElement(this->element());
ASSERT(element);
SVGUseElement* useElement = nullptr;
if (isSVGUseElement(*element)) {
useElement = toSVGUseElement(element);
} else if (isSVGGElement(*element) && toSVGGElement(element)->inUseShadowTree()) {
SVGElement* correspondingElement = element->correspondingElement();
if (isSVGUseElement(correspondingElement))
useElement = toSVGUseElement(correspondingElement);
}
if (useElement) {
SVGLengthContext lengthContext(useElement);
FloatSize translation(
useElement->x()->currentValue()->value(lengthContext),
useElement->y()->currentValue()->value(lengthContext));
// TODO(fs): Signal this on style update instead. (Since these are
// suppose to be presentation attributes now, this does feel a bit
// broken...)
if (translation != m_additionalTranslation)
setNeedsTransformUpdate();
m_additionalTranslation = translation;
}
if (!m_needsTransformUpdate)
return TransformChange::None;
std::pair<double, double> oldScale = scaleReference(m_localTransform);
m_localTransform = element->calculateAnimatedLocalTransform();
m_localTransform.translate(m_additionalTranslation.width(), m_additionalTranslation.height());
m_needsTransformUpdate = false;
return scaleReference(m_localTransform) != oldScale
? TransformChange::Full : TransformChange::ScaleInvariant;
}
| 171,666 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __init ipgre_init(void)
{
int err;
printk(KERN_INFO "GRE over IPv4 tunneling driver\n");
if (inet_add_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) {
printk(KERN_INFO "ipgre init: can't add protocol\n");
return -EAGAIN;
}
err = register_pernet_device(&ipgre_net_ops);
if (err < 0)
goto gen_device_failed;
err = rtnl_link_register(&ipgre_link_ops);
if (err < 0)
goto rtnl_link_failed;
err = rtnl_link_register(&ipgre_tap_ops);
if (err < 0)
goto tap_ops_failed;
out:
return err;
tap_ops_failed:
rtnl_link_unregister(&ipgre_link_ops);
rtnl_link_failed:
unregister_pernet_device(&ipgre_net_ops);
gen_device_failed:
inet_del_protocol(&ipgre_protocol, IPPROTO_GRE);
goto out;
}
Commit Message: gre: fix netns vs proto registration ordering
GRE protocol receive hook can be called right after protocol addition is done.
If netns stuff is not yet initialized, we're going to oops in
net_generic().
This is remotely oopsable if ip_gre is compiled as module and packet
comes at unfortunate moment of module loading.
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static int __init ipgre_init(void)
{
int err;
printk(KERN_INFO "GRE over IPv4 tunneling driver\n");
err = register_pernet_device(&ipgre_net_ops);
if (err < 0)
return err;
err = inet_add_protocol(&ipgre_protocol, IPPROTO_GRE);
if (err < 0) {
printk(KERN_INFO "ipgre init: can't add protocol\n");
goto add_proto_failed;
}
err = rtnl_link_register(&ipgre_link_ops);
if (err < 0)
goto rtnl_link_failed;
err = rtnl_link_register(&ipgre_tap_ops);
if (err < 0)
goto tap_ops_failed;
out:
return err;
tap_ops_failed:
rtnl_link_unregister(&ipgre_link_ops);
rtnl_link_failed:
inet_del_protocol(&ipgre_protocol, IPPROTO_GRE);
add_proto_failed:
unregister_pernet_device(&ipgre_net_ops);
goto out;
}
| 165,884 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sycc420_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
const int *y, *cb, *cr, *ny;
unsigned int maxw, maxh, max;
int offset, upb;
unsigned int i, j;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * (size_t)max);
d1 = g = (int*)malloc(sizeof(int) * (size_t)max);
d2 = b = (int*)malloc(sizeof(int) * (size_t)max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i=0U; i < (maxh & ~(unsigned int)1U); i += 2U)
{
ny = y + maxw;
nr = r + maxw; ng = g + maxw; nb = b + maxw;
for(j=0; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
y += maxw; r += maxw; g += maxw; b += maxw;
}
if(i < maxh)
{
for(j=0U; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
#if defined(USE_JPWL) || defined(USE_MJ2)
img->comps[1].w = maxw; img->comps[1].h = maxh;
img->comps[2].w = maxw; img->comps[2].h = maxh;
#else
img->comps[1].w = (OPJ_UINT32)maxw; img->comps[1].h = (OPJ_UINT32)maxh;
img->comps[2].w = (OPJ_UINT32)maxw; img->comps[2].h = (OPJ_UINT32)maxh;
#endif
img->comps[1].dx = img->comps[0].dx;
img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[0].dy;
img->comps[2].dy = img->comps[0].dy;
return;
fails:
if(r) free(r);
if(g) free(g);
if(b) free(b);
}/* sycc420_to_rgb() */
Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745)
42x Images with an odd x0/y0 lead to subsampled component starting at the
2nd column/line.
That is offset = comp->dx * comp->x0 - image->x0 = 1
Fix #726
CWE ID: CWE-125 | static void sycc420_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
const int *y, *cb, *cr, *ny;
size_t maxw, maxh, max, offx, loopmaxw, offy, loopmaxh;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * max);
d1 = g = (int*)malloc(sizeof(int) * max);
d2 = b = (int*)malloc(sizeof(int) * max);
if (r == NULL || g == NULL || b == NULL) goto fails;
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
/* if img->y0 is odd, then first line shall use Cb/Cr = 0 */
offy = img->y0 & 1U;
loopmaxh = maxh - offy;
if (offy > 0U) {
size_t j;
for(j=0; j < maxw; ++j)
{
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
}
}
for(i=0U; i < (loopmaxh & ~(size_t)1U); i += 2U)
{
size_t j;
ny = y + maxw;
nr = r + maxw; ng = g + maxw; nb = b + maxw;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
}
for(j=0; j < (loopmaxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
if(j < loopmaxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
y += maxw; r += maxw; g += maxw; b += maxw;
}
if(i < loopmaxh)
{
size_t j;
for(j=0U; j < (maxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
free(r);
free(g);
free(b);
}/* sycc420_to_rgb() */
| 168,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void perf_event_for_each_child(struct perf_event *event,
void (*func)(struct perf_event *))
{
struct perf_event *child;
WARN_ON_ONCE(event->ctx->parent_ctx);
mutex_lock(&event->child_mutex);
func(event);
list_for_each_entry(child, &event->child_list, child_list)
func(child);
mutex_unlock(&event->child_mutex);
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | static void perf_event_for_each_child(struct perf_event *event,
void (*func)(struct perf_event *))
{
struct perf_event *child;
WARN_ON_ONCE(event->ctx->parent_ctx);
mutex_lock(&event->child_mutex);
func(event);
list_for_each_entry(child, &event->child_list, child_list)
func(child);
mutex_unlock(&event->child_mutex);
}
| 166,985 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MountLibrary* CrosLibrary::GetMountLibrary() {
return mount_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | MountLibrary* CrosLibrary::GetMountLibrary() {
| 170,626 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: compile_length_bag_node(BagNode* node, regex_t* reg)
{
int len;
int tlen;
if (node->type == BAG_OPTION)
return compile_length_option_node(node, reg);
if (NODE_BAG_BODY(node)) {
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
if (tlen < 0) return tlen;
}
else
tlen = 0;
switch (node->type) {
case BAG_MEMORY:
#ifdef USE_CALL
if (node->m.regnum == 0 && NODE_IS_CALLED(node)) {
len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;
return len;
}
if (NODE_IS_CALLED(node)) {
len = SIZE_OP_MEMORY_START_PUSH + tlen
+ SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;
if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH);
else
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END);
}
else if (NODE_IS_RECURSION(node)) {
len = SIZE_OP_MEMORY_START_PUSH;
len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC);
}
else
#endif
{
if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum))
len = SIZE_OP_MEMORY_START_PUSH;
else
len = SIZE_OP_MEMORY_START;
len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)
? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END);
}
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) {
int v;
QuantNode* qn;
qn = QUANT_(NODE_BAG_BODY(node));
tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
v = onig_positive_int_multiply(qn->lower, tlen);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP;
}
else {
len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END;
}
break;
case BAG_IF_ELSE:
{
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
len = compile_length_tree(cond, reg);
if (len < 0) return len;
len += SIZE_OP_PUSH;
len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END;
if (IS_NOT_NULL(Then)) {
tlen = compile_length_tree(Then, reg);
if (tlen < 0) return tlen;
len += tlen;
}
if (IS_NOT_NULL(Else)) {
len += SIZE_OP_JUMP;
tlen = compile_length_tree(Else, reg);
if (tlen < 0) return tlen;
len += tlen;
}
}
break;
case BAG_OPTION:
/* never come here, but set for escape warning */
len = 0;
break;
}
return len;
}
Commit Message: Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode.
CWE ID: CWE-476 | compile_length_bag_node(BagNode* node, regex_t* reg)
{
int len;
int tlen;
if (node->type == BAG_OPTION)
return compile_length_option_node(node, reg);
if (NODE_BAG_BODY(node)) {
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
if (tlen < 0) return tlen;
}
else
tlen = 0;
switch (node->type) {
case BAG_MEMORY:
#ifdef USE_CALL
if (node->m.regnum == 0 && NODE_IS_CALLED(node)) {
len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;
return len;
}
if (NODE_IS_CALLED(node)) {
len = SIZE_OP_MEMORY_START_PUSH + tlen
+ SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;
if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH);
else
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END);
}
else if (NODE_IS_RECURSION(node)) {
len = SIZE_OP_MEMORY_START_PUSH;
len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC);
}
else
#endif
{
if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum))
len = SIZE_OP_MEMORY_START_PUSH;
else
len = SIZE_OP_MEMORY_START;
len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)
? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END);
}
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) {
int v;
QuantNode* qn;
qn = QUANT_(NODE_BAG_BODY(node));
tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
v = onig_positive_int_multiply(qn->lower, tlen);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP;
}
else {
len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END;
}
break;
case BAG_IF_ELSE:
{
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
len = compile_length_tree(cond, reg);
if (len < 0) return len;
len += SIZE_OP_PUSH;
len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END;
if (IS_NOT_NULL(Then)) {
tlen = compile_length_tree(Then, reg);
if (tlen < 0) return tlen;
len += tlen;
}
len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END;
if (IS_NOT_NULL(Else)) {
tlen = compile_length_tree(Else, reg);
if (tlen < 0) return tlen;
len += tlen;
}
}
break;
case BAG_OPTION:
/* never come here, but set for escape warning */
len = 0;
break;
}
return len;
}
| 169,612 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: print_attr_string(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
register u_int i;
ND_TCHECK2(data[0],length);
switch(attr_code)
{
case TUNNEL_PASS:
if (length < 3)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (*data && (*data <=0x1F) )
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data)));
data+=2;
length-=2;
break;
case TUNNEL_CLIENT_END:
case TUNNEL_SERVER_END:
case TUNNEL_PRIV_GROUP:
case TUNNEL_ASSIGN_ID:
case TUNNEL_CLIENT_AUTH:
case TUNNEL_SERVER_AUTH:
if (*data <= 0x1F)
{
if (length < 1)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (*data)
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
}
break;
case EGRESS_VLAN_NAME:
ND_PRINT((ndo, "%s (0x%02x) ",
tok2str(rfc4675_tagged,"Unknown tag",*data),
*data));
data++;
length--;
break;
}
for (i=0; *data && i < length ; i++, data++)
ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-13032/RADIUS: Check whether a byte exists before testing its value.
Reverse the test in a for loop to test the length before testing whether
we have a null byte.
This fixes a buffer over-read discovered by Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Clean up other length tests while we're at it.
CWE ID: CWE-125 | print_attr_string(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
register u_int i;
ND_TCHECK2(data[0],length);
switch(attr_code)
{
case TUNNEL_PASS:
if (length < 3)
goto trunc;
if (*data && (*data <=0x1F) )
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data)));
data+=2;
length-=2;
break;
case TUNNEL_CLIENT_END:
case TUNNEL_SERVER_END:
case TUNNEL_PRIV_GROUP:
case TUNNEL_ASSIGN_ID:
case TUNNEL_CLIENT_AUTH:
case TUNNEL_SERVER_AUTH:
if (*data <= 0x1F)
{
if (length < 1)
goto trunc;
if (*data)
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
}
break;
case EGRESS_VLAN_NAME:
if (length < 1)
goto trunc;
ND_PRINT((ndo, "%s (0x%02x) ",
tok2str(rfc4675_tagged,"Unknown tag",*data),
*data));
data++;
length--;
break;
}
for (i=0; i < length && *data; i++, data++)
ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 167,851 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), nullptr, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([ijl\u0131]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Block dotless-i / j + a combining mark
U+0131 (doltess i) and U+0237 (dotless j) are blocked from being
followed by a combining mark in U+0300 block.
Bug: 774842
Test: See the bug
Change-Id: I92aac0e97233184864d060fd0f137a90b042c679
Reviewed-on: https://chromium-review.googlesource.com/767888
Commit-Queue: Jungshik Shin <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#517605}
CWE ID: CWE-20 | bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), nullptr, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
// - Disallow dotless i (U+0131) followed by a combining mark.
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"(\u0131[\u0300-\u0339]|)"
R"([ijl]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,692 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 net_ctl_permissions(struct ctl_table_header *head,
struct ctl_table *table)
{
struct net *net = container_of(head->set, struct net, sysctls);
kuid_t root_uid = make_kuid(net->user_ns, 0);
kgid_t root_gid = make_kgid(net->user_ns, 0);
/* Allow network administrator to have same access as root. */
if (ns_capable(net->user_ns, CAP_NET_ADMIN) ||
uid_eq(root_uid, current_uid())) {
int mode = (table->mode >> 6) & 7;
return (mode << 6) | (mode << 3) | mode;
}
/* Allow netns root group to have the same access as the root group */
if (gid_eq(root_gid, current_gid())) {
int mode = (table->mode >> 3) & 7;
return (mode << 3) | mode;
}
return table->mode;
}
Commit Message: net: Update the sysctl permissions handler to test effective uid/gid
Modify the code to use current_euid(), and in_egroup_p, as in done
in fs/proc/proc_sysctl.c:test_perm()
Cc: [email protected]
Reviewed-by: Eric Sandeen <[email protected]>
Reported-by: Eric Sandeen <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20 | static int net_ctl_permissions(struct ctl_table_header *head,
struct ctl_table *table)
{
struct net *net = container_of(head->set, struct net, sysctls);
kuid_t root_uid = make_kuid(net->user_ns, 0);
kgid_t root_gid = make_kgid(net->user_ns, 0);
/* Allow network administrator to have same access as root. */
if (ns_capable(net->user_ns, CAP_NET_ADMIN) ||
uid_eq(root_uid, current_euid())) {
int mode = (table->mode >> 6) & 7;
return (mode << 6) | (mode << 3) | mode;
}
/* Allow netns root group to have the same access as the root group */
if (in_egroup_p(root_gid)) {
int mode = (table->mode >> 3) & 7;
return (mode << 3) | mode;
}
return table->mode;
}
| 165,994 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_sd_new(Jbig2Ctx *ctx, int n_symbols)
{
Jbig2SymbolDict *new = NULL;
if (n_symbols < 0) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "Negative number of symbols in symbol dict: %d", n_symbols);
return NULL;
}
new = jbig2_new(ctx, Jbig2SymbolDict, 1);
if (new != NULL) {
new->glyphs = jbig2_new(ctx, Jbig2Image *, n_symbols);
new->n_symbols = n_symbols;
} else {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate new empty symbol dict");
return NULL;
}
if (new->glyphs != NULL) {
memset(new->glyphs, 0, n_symbols * sizeof(Jbig2Image *));
} else {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate glyphs for new empty symbol dict");
jbig2_free(ctx->allocator, new);
return NULL;
}
return new;
}
Commit Message:
CWE ID: CWE-119 | jbig2_sd_new(Jbig2Ctx *ctx, int n_symbols)
jbig2_sd_new(Jbig2Ctx *ctx, uint32_t n_symbols)
{
Jbig2SymbolDict *new_dict = NULL;
if (n_symbols < 0) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "Negative number of symbols in symbol dict: %d", n_symbols);
return NULL;
}
new_dict = jbig2_new(ctx, Jbig2SymbolDict, 1);
if (new_dict != NULL) {
new_dict->glyphs = jbig2_new(ctx, Jbig2Image *, n_symbols);
new_dict->n_symbols = n_symbols;
} else {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate new empty symbol dict");
return NULL;
}
if (new_dict->glyphs != NULL) {
memset(new_dict->glyphs, 0, n_symbols * sizeof(Jbig2Image *));
} else {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate glyphs for new empty symbol dict");
jbig2_free(ctx->allocator, new_dict);
return NULL;
}
return new_dict;
}
| 165,502 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CopyTransportDIBHandleForMessage(
const TransportDIB::Handle& handle_in,
TransportDIB::Handle* handle_out) {
#if defined(OS_MACOSX)
if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) {
PLOG(ERROR) << "dup()";
return;
}
handle_out->auto_close = true;
#else
*handle_out = handle_in;
#endif
}
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 void CopyTransportDIBHandleForMessage(
const TransportDIB::Handle& handle_in,
TransportDIB::Handle* handle_out,
base::ProcessId peer_pid) {
#if defined(OS_MACOSX)
if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) {
PLOG(ERROR) << "dup()";
return;
}
handle_out->auto_close = true;
#elif defined(OS_WIN)
// On Windows we need to duplicate the handle for the plugin process.
*handle_out = NULL;
sandbox::BrokerDuplicateHandle(handle_in, peer_pid, handle_out,
FILE_MAP_READ | FILE_MAP_WRITE, 0);
CHECK(*handle_out != NULL);
#else
*handle_out = handle_in;
#endif
}
| 170,955 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionTtsController::Stop() {
if (current_utterance_ && !current_utterance_->extension_id().empty()) {
current_utterance_->profile()->GetExtensionEventRouter()->
DispatchEventToExtension(
current_utterance_->extension_id(),
events::kOnStop,
"[]",
current_utterance_->profile(),
GURL());
} else {
GetPlatformImpl()->clear_error();
GetPlatformImpl()->StopSpeaking();
}
if (current_utterance_)
current_utterance_->set_error(kSpeechInterruptedError);
FinishCurrentUtterance();
ClearUtteranceQueue();
}
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 ExtensionTtsController::Stop() {
double volume = 1.0;
if (options->HasKey(constants::kVolumeKey)) {
EXTENSION_FUNCTION_VALIDATE(
options->GetDouble(constants::kVolumeKey, &volume));
if (volume < 0.0 || volume > 1.0) {
error_ = constants::kErrorInvalidVolume;
return false;
}
}
| 170,391 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void ikev2_parent_inI2outR2_continue(struct pluto_crypto_req_cont *pcrc,
struct pluto_crypto_req *r,
err_t ugh)
{
struct dh_continuation *dh = (struct dh_continuation *)pcrc;
struct msg_digest *md = dh->md;
struct state *const st = md->st;
stf_status e;
DBG(DBG_CONTROLMORE,
DBG_log("ikev2 parent inI2outR2: calculating g^{xy}, sending R2"));
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"%s: Request was disconnected from state",
__FUNCTION__);
if (dh->md)
release_md(dh->md);
return;
}
/* XXX should check out ugh */
passert(ugh == NULL);
passert(cur_state == NULL);
passert(st != NULL);
passert(st->st_suspended_md == dh->md);
set_suspended(st, NULL); /* no longer connected or suspended */
set_cur_state(st);
st->st_calculating = FALSE;
e = ikev2_parent_inI2outR2_tail(pcrc, r);
if ( e > STF_FAIL) {
/* we do not send a notify because we are the initiator that could be responding to an error notification */
int v2_notify_num = e - STF_FAIL;
DBG_log(
"ikev2_parent_inI2outR2_tail returned STF_FAIL with %s",
enum_name(&ikev2_notify_names, v2_notify_num));
} else if ( e != STF_OK) {
DBG_log("ikev2_parent_inI2outR2_tail returned %s",
enum_name(&stfstatus_name, e));
}
if (dh->md != NULL) {
complete_v2_state_transition(&dh->md, e);
if (dh->md)
release_md(dh->md);
}
reset_globals();
passert(GLOBALS_ARE_RESET());
}
Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload
CWE ID: CWE-20 | static void ikev2_parent_inI2outR2_continue(struct pluto_crypto_req_cont *pcrc,
struct pluto_crypto_req *r,
err_t ugh)
{
struct dh_continuation *dh = (struct dh_continuation *)pcrc;
struct msg_digest *md = dh->md;
struct state *const st = md->st;
stf_status e;
DBG(DBG_CONTROLMORE,
DBG_log("ikev2 parent inI2outR2: calculating g^{xy}, sending R2"));
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"%s: Request was disconnected from state",
__FUNCTION__);
if (dh->md)
release_md(dh->md);
return;
}
/* XXX should check out ugh */
passert(ugh == NULL);
passert(cur_state == NULL);
passert(st != NULL);
passert(st->st_suspended_md == dh->md);
set_suspended(st, NULL); /* no longer connected or suspended */
set_cur_state(st);
st->st_calculating = FALSE;
e = ikev2_parent_inI2outR2_tail(pcrc, r);
if ( e > STF_FAIL) {
/* we do not send a notify because we are the initiator that could be responding to an error notification */
int v2_notify_num = e - STF_FAIL;
DBG_log(
"ikev2_parent_inI2outR2_tail returned STF_FAIL with %s",
enum_name(&ikev2_notify_names, v2_notify_num));
} else if ( e != STF_OK) {
DBG_log("ikev2_parent_inI2outR2_tail returned %s",
enum_name(&stfstatus_name, e));
}
if (dh->md != NULL) {
complete_v2_state_transition(&dh->md, e);
if (dh->md)
release_md(dh->md);
}
reset_globals();
}
| 166,471 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
{
int i;
for (i = 0; attrs[i]; i++)
{
MAPI_Attr* a = attrs[i];
if (a->num_values)
{
switch (a->name)
{
case MAPI_ATTACH_LONG_FILENAME:
if (file->name) XFREE(file->name);
file->name = strdup( (char*)a->values[0].data.buf );
break;
case MAPI_ATTACH_DATA_OBJ:
file->len = a->values[0].len;
if (file->data) XFREE (file->data);
file->data = CHECKED_XMALLOC (unsigned char, file->len);
memmove (file->data, a->values[0].data.buf, file->len);
break;
case MAPI_ATTACH_MIME_TAG:
if (file->mime_type) XFREE (file->mime_type);
file->mime_type = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->mime_type, a->values[0].data.buf, a->values[0].len);
break;
case MAPI_ATTACH_CONTENT_ID:
if (file->content_id) XFREE(file->content_id);
file->content_id = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->content_id, a->values[0].data.buf, a->values[0].len);
break;
default:
break;
}
}
}
}
Commit Message: Check types to avoid invalid reads/writes.
CWE ID: CWE-125 | file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
{
int i;
for (i = 0; attrs[i]; i++)
{
MAPI_Attr* a = attrs[i];
if (a->num_values)
{
switch (a->name)
{
case MAPI_ATTACH_LONG_FILENAME:
assert(a->type == szMAPI_STRING);
if (file->name) XFREE(file->name);
file->name = strdup( (char*)a->values[0].data.buf );
break;
case MAPI_ATTACH_DATA_OBJ:
assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT));
file->len = a->values[0].len;
if (file->data) XFREE (file->data);
file->data = CHECKED_XMALLOC (unsigned char, file->len);
memmove (file->data, a->values[0].data.buf, file->len);
break;
case MAPI_ATTACH_MIME_TAG:
assert(a->type == szMAPI_STRING);
if (file->mime_type) XFREE (file->mime_type);
file->mime_type = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->mime_type, a->values[0].data.buf, a->values[0].len);
break;
case MAPI_ATTACH_CONTENT_ID:
assert(a->type == szMAPI_STRING);
if (file->content_id) XFREE(file->content_id);
file->content_id = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->content_id, a->values[0].data.buf, a->values[0].len);
break;
default:
break;
}
}
}
}
| 168,351 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Initialize() {
Initialize(kDefaultChannelLayout, kDefaultSampleBits);
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void Initialize() {
Initialize(kDefaultChannelLayout, kDefaultSampleBits, kSamplesPerSecond);
}
| 171,533 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void QuicClientPromisedInfo::OnPromiseHeaders(const SpdyHeaderBlock& headers) {
SpdyHeaderBlock::const_iterator it = headers.find(kHttp2MethodHeader);
DCHECK(it != headers.end());
if (!(it->second == "GET" || it->second == "HEAD")) {
QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid method "
<< it->second;
Reset(QUIC_INVALID_PROMISE_METHOD);
return;
}
if (!SpdyUtils::UrlIsValid(headers)) {
QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid URL "
<< url_;
Reset(QUIC_INVALID_PROMISE_URL);
return;
}
if (!session_->IsAuthorized(SpdyUtils::GetHostNameFromHeaderBlock(headers))) {
Reset(QUIC_UNAUTHORIZED_PROMISE_URL);
return;
}
request_headers_.reset(new SpdyHeaderBlock(headers.Clone()));
}
Commit Message: Fix Stack Buffer Overflow in QuicClientPromisedInfo::OnPromiseHeaders
BUG=777728
Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I6a80db88aafdf20c7abd3847404b818565681310
Reviewed-on: https://chromium-review.googlesource.com/748425
Reviewed-by: Zhongyi Shi <[email protected]>
Commit-Queue: Ryan Hamilton <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513105}
CWE ID: CWE-119 | void QuicClientPromisedInfo::OnPromiseHeaders(const SpdyHeaderBlock& headers) {
SpdyHeaderBlock::const_iterator it = headers.find(kHttp2MethodHeader);
if (it == headers.end()) {
QUIC_DVLOG(1) << "Promise for stream " << id_ << " has no method";
Reset(QUIC_INVALID_PROMISE_METHOD);
return;
}
if (!(it->second == "GET" || it->second == "HEAD")) {
QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid method "
<< it->second;
Reset(QUIC_INVALID_PROMISE_METHOD);
return;
}
if (!SpdyUtils::UrlIsValid(headers)) {
QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid URL "
<< url_;
Reset(QUIC_INVALID_PROMISE_URL);
return;
}
if (!session_->IsAuthorized(SpdyUtils::GetHostNameFromHeaderBlock(headers))) {
Reset(QUIC_UNAUTHORIZED_PROMISE_URL);
return;
}
request_headers_.reset(new SpdyHeaderBlock(headers.Clone()));
}
| 172,940 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UpdateForDataChange(int days_since_last_update) {
MaintainContentLengthPrefsWindow(original_update_.Get(), kNumDaysInHistory);
MaintainContentLengthPrefsWindow(received_update_.Get(), kNumDaysInHistory);
if (days_since_last_update) {
MaintainContentLengthPrefsForDateChange(
original_update_.Get(), received_update_.Get(),
days_since_last_update);
}
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void UpdateForDataChange(int days_since_last_update) {
original_.UpdateForDataChange(days_since_last_update);
received_.UpdateForDataChange(days_since_last_update);
}
| 171,329 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nsPluginInstance::setupCookies(const std::string& pageurl)
{
std::string::size_type pos;
pos = pageurl.find("/", pageurl.find("//", 0) + 2) + 1;
std::string url = pageurl.substr(0, pos);
std::string ncookie;
char *cookie = 0;
uint32_t length = 0;
NPError rv = NPERR_GENERIC_ERROR;
#if NPAPI_VERSION != 190
if (NPNFuncs.getvalueforurl) {
rv = NPN_GetValueForURL(_instance, NPNURLVCookie, url.c_str(),
&cookie, &length);
} else {
LOG_ONCE( gnash::log_debug("Browser doesn't support getvalueforurl") );
}
#endif
if (rv == NPERR_GENERIC_ERROR) {
log_debug("Trying window.document.cookie for cookies");
ncookie = getDocumentProp("cookie");
}
if (cookie) {
ncookie.assign(cookie, length);
NPN_MemFree(cookie);
}
if (ncookie.empty()) {
gnash::log_debug("No stored Cookie for %s", url);
return;
}
gnash::log_debug("The Cookie for %s is %s", url, ncookie);
std::ofstream cookiefile;
std::stringstream ss;
ss << "/tmp/gnash-cookies." << getpid();
cookiefile.open(ss.str().c_str(), std::ios::out | std::ios::trunc);
typedef boost::char_separator<char> char_sep;
typedef boost::tokenizer<char_sep> tokenizer;
tokenizer tok(ncookie, char_sep(";"));
for (tokenizer::iterator it=tok.begin(); it != tok.end(); ++it) {
cookiefile << "Set-Cookie: " << *it << std::endl;
}
cookiefile.close();
if (setenv("GNASH_COOKIES_IN", ss.str().c_str(), 1) < 0) {
gnash::log_error(
"Couldn't set environment variable GNASH_COOKIES_IN to %s",
ncookie);
}
}
Commit Message:
CWE ID: CWE-264 | nsPluginInstance::setupCookies(const std::string& pageurl)
{
std::string::size_type pos;
pos = pageurl.find("/", pageurl.find("//", 0) + 2) + 1;
std::string url = pageurl.substr(0, pos);
std::string ncookie;
char *cookie = 0;
uint32_t length = 0;
NPError rv = NPERR_GENERIC_ERROR;
#if NPAPI_VERSION != 190
if (NPNFuncs.getvalueforurl) {
rv = NPN_GetValueForURL(_instance, NPNURLVCookie, url.c_str(),
&cookie, &length);
} else {
LOG_ONCE( gnash::log_debug("Browser doesn't support getvalueforurl") );
}
#endif
if (rv == NPERR_GENERIC_ERROR) {
log_debug("Trying window.document.cookie for cookies");
ncookie = getDocumentProp("cookie");
}
if (cookie) {
ncookie.assign(cookie, length);
NPN_MemFree(cookie);
}
if (ncookie.empty()) {
gnash::log_debug("No stored Cookie for %s", url);
return;
}
gnash::log_debug("The Cookie for %s is %s", url, ncookie);
std::ofstream cookiefile;
std::stringstream ss;
ss << "/tmp/gnash-cookies." << getpid();
cookiefile.open(ss.str().c_str(), std::ios::out | std::ios::trunc);
chmod (ss.str().c_str(), 0600);
typedef boost::char_separator<char> char_sep;
typedef boost::tokenizer<char_sep> tokenizer;
tokenizer tok(ncookie, char_sep(";"));
for (tokenizer::iterator it=tok.begin(); it != tok.end(); ++it) {
cookiefile << "Set-Cookie: " << *it << std::endl;
}
cookiefile.close();
if (setenv("GNASH_COOKIES_IN", ss.str().c_str(), 1) < 0) {
gnash::log_error(
"Couldn't set environment variable GNASH_COOKIES_IN to %s",
ncookie);
}
}
| 165,233 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Wait() {
message_loop_runner_->Run();
message_loop_runner_ = new MessageLoopRunner;
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID: | void Wait() {
run_loop_->Run();
run_loop_ = std::make_unique<base::RunLoop>();
}
| 172,719 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dwarf_elf_object_access_load_section(void* obj_in,
Dwarf_Half section_index,
Dwarf_Small** section_data,
int* error)
{
dwarf_elf_object_access_internals_t*obj =
(dwarf_elf_object_access_internals_t*)obj_in;
if (section_index == 0) {
return DW_DLV_NO_ENTRY;
}
{
Elf_Scn *scn = 0;
Elf_Data *data = 0;
scn = elf_getscn(obj->elf, section_index);
if (scn == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
/* When using libelf as a producer, section data may be stored
in multiple buffers. In libdwarf however, we only use libelf
as a consumer (there is a dwarf producer API, but it doesn't
use libelf). Because of this, this single call to elf_getdata
will retrieve the entire section in a single contiguous
buffer. */
data = elf_getdata(scn, NULL);
if (data == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
*section_data = data->d_buf;
}
return DW_DLV_OK;
}
Commit Message: A DWARF related section marked SHT_NOBITS (elf section type)
is an error in the elf object. Now detected.
dwarf_elf_access.c
CWE ID: CWE-476 | dwarf_elf_object_access_load_section(void* obj_in,
Dwarf_Half section_index,
Dwarf_Small** section_data,
int* error)
{
dwarf_elf_object_access_internals_t*obj =
(dwarf_elf_object_access_internals_t*)obj_in;
if (section_index == 0) {
return DW_DLV_NO_ENTRY;
}
{
Elf_Scn *scn = 0;
Elf_Data *data = 0;
scn = elf_getscn(obj->elf, section_index);
if (scn == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
/* When using libelf as a producer, section data may be stored
in multiple buffers. In libdwarf however, we only use libelf
as a consumer (there is a dwarf producer API, but it doesn't
use libelf). Because of this, this single call to elf_getdata
will retrieve the entire section in a single contiguous
buffer. */
data = elf_getdata(scn, NULL);
if (data == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
if (!data->d_buf) {
/* If NULL it means 'the section has no data'
according to libelf documentation.
No DWARF-related section should ever have
'no data'. Happens if a section type is
SHT_NOBITS and no section libdwarf
wants to look at should be SHT_NOBITS. */
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
*section_data = data->d_buf;
}
return DW_DLV_OK;
}
| 168,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
RFCOMM_PARSE_LEN_FIELD(eal, len, p_data);
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
Commit Message: Add bound check for rfc_parse_data
Bug: 78288018
Test: manual
Change-Id: I44349cd22c141483d01bce0f5a2131b727d0feb0
(cherry picked from commit 6039cb7225733195192b396ad19c528800feb735)
CWE ID: CWE-125 | uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
eal = *(p_data)&RFCOMM_EA;
len = *(p_data)++ >> RFCOMM_SHIFT_LENGTH1;
if (eal == 0 && p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
len += (*(p_data)++ << RFCOMM_SHIFT_LENGTH2);
} else if (eal == 0) {
RFCOMM_TRACE_ERROR("Bad Length when EAL = 0: %d", p_buf->len);
android_errorWriteLog(0x534e4554, "78288018");
return RFC_EVENT_BAD_FRAME;
}
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
| 174,612 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 snd_timer_user_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct snd_timer_user *tu;
long result = 0, unit;
int qhead;
int err = 0;
tu = file->private_data;
unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read);
spin_lock_irq(&tu->qlock);
while ((long)count - result >= unit) {
while (!tu->qused) {
wait_queue_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto _error;
}
set_current_state(TASK_INTERRUPTIBLE);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tu->qchange_sleep, &wait);
spin_unlock_irq(&tu->qlock);
schedule();
spin_lock_irq(&tu->qlock);
remove_wait_queue(&tu->qchange_sleep, &wait);
if (tu->disconnected) {
err = -ENODEV;
goto _error;
}
if (signal_pending(current)) {
err = -ERESTARTSYS;
goto _error;
}
}
qhead = tu->qhead++;
tu->qhead %= tu->queue_size;
tu->qused--;
spin_unlock_irq(&tu->qlock);
mutex_lock(&tu->ioctl_lock);
if (tu->tread) {
if (copy_to_user(buffer, &tu->tqueue[qhead],
sizeof(struct snd_timer_tread)))
err = -EFAULT;
} else {
if (copy_to_user(buffer, &tu->queue[qhead],
sizeof(struct snd_timer_read)))
err = -EFAULT;
}
mutex_unlock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
if (err < 0)
goto _error;
result += unit;
buffer += unit;
}
_error:
spin_unlock_irq(&tu->qlock);
return result > 0 ? result : err;
}
Commit Message: ALSA: timer: Fix race between read and ioctl
The read from ALSA timer device, the function snd_timer_user_tread(),
may access to an uninitialized struct snd_timer_user fields when the
read is concurrently performed while the ioctl like
snd_timer_user_tselect() is invoked. We have already fixed the races
among ioctls via a mutex, but we seem to have forgotten the race
between read vs ioctl.
This patch simply applies (more exactly extends the already applied
range of) tu->ioctl_lock in snd_timer_user_tread() for closing the
race window.
Reported-by: Alexander Potapenko <[email protected]>
Tested-by: Alexander Potapenko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-200 | static ssize_t snd_timer_user_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct snd_timer_user *tu;
long result = 0, unit;
int qhead;
int err = 0;
tu = file->private_data;
unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read);
mutex_lock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
while ((long)count - result >= unit) {
while (!tu->qused) {
wait_queue_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto _error;
}
set_current_state(TASK_INTERRUPTIBLE);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tu->qchange_sleep, &wait);
spin_unlock_irq(&tu->qlock);
mutex_unlock(&tu->ioctl_lock);
schedule();
mutex_lock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
remove_wait_queue(&tu->qchange_sleep, &wait);
if (tu->disconnected) {
err = -ENODEV;
goto _error;
}
if (signal_pending(current)) {
err = -ERESTARTSYS;
goto _error;
}
}
qhead = tu->qhead++;
tu->qhead %= tu->queue_size;
tu->qused--;
spin_unlock_irq(&tu->qlock);
if (tu->tread) {
if (copy_to_user(buffer, &tu->tqueue[qhead],
sizeof(struct snd_timer_tread)))
err = -EFAULT;
} else {
if (copy_to_user(buffer, &tu->queue[qhead],
sizeof(struct snd_timer_read)))
err = -EFAULT;
}
spin_lock_irq(&tu->qlock);
if (err < 0)
goto _error;
result += unit;
buffer += unit;
}
_error:
spin_unlock_irq(&tu->qlock);
mutex_unlock(&tu->ioctl_lock);
return result > 0 ? result : err;
}
| 170,008 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset,
gfx::SizeF contents_size_dip,
float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_updateScrollState(env,
obj.obj(),
max_scroll_offset.x(),
max_scroll_offset.y(),
contents_size_dip.width(),
contents_size_dip.height(),
page_scale_factor,
min_page_scale_factor,
max_page_scale_factor);
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | void AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset,
void AwContents::UpdateScrollState(const gfx::Vector2d& max_scroll_offset,
const gfx::SizeF& contents_size_dip,
float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_updateScrollState(env,
obj.obj(),
max_scroll_offset.x(),
max_scroll_offset.y(),
contents_size_dip.width(),
contents_size_dip.height(),
page_scale_factor,
min_page_scale_factor,
max_page_scale_factor);
}
| 171,618 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Chapters* Segment::GetChapters() const
{
return m_pChapters;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Chapters* Segment::GetChapters() const
| 174,290 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void get_socket_name( char* buf, int len )
{
char* dpy = g_strdup(g_getenv("DISPLAY"));
if(dpy && *dpy)
{
char* p = strchr(dpy, ':');
for(++p; *p && *p != '.' && *p != '\n';)
++p;
if(*p)
*p = '\0';
}
g_snprintf( buf, len, "%s/.menu-cached-%s-%s", g_get_tmp_dir(),
dpy ? dpy : ":0", g_get_user_name() );
g_free(dpy);
}
Commit Message:
CWE ID: CWE-20 | static void get_socket_name( char* buf, int len )
{
char* dpy = g_strdup(g_getenv("DISPLAY"));
if(dpy && *dpy)
{
char* p = strchr(dpy, ':');
for(++p; *p && *p != '.' && *p != '\n';)
++p;
if(*p)
*p = '\0';
}
#if GLIB_CHECK_VERSION(2, 28, 0)
g_snprintf( buf, len, "%s/menu-cached-%s", g_get_user_runtime_dir(),
dpy ? dpy : ":0" );
#else
g_snprintf( buf, len, "%s/.menu-cached-%s-%s", g_get_tmp_dir(),
dpy ? dpy : ":0", g_get_user_name() );
#endif
g_free(dpy);
}
| 164,817 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 send_event (int fd, uint16_t type, uint16_t code, int32_t value)
{
struct uinput_event event;
BTIF_TRACE_DEBUG("%s type:%u code:%u value:%d", __FUNCTION__,
type, code, value);
memset(&event, 0, sizeof(event));
event.type = type;
event.code = code;
event.value = value;
return write(fd, &event, sizeof(event));
}
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 | int send_event (int fd, uint16_t type, uint16_t code, int32_t value)
{
struct uinput_event event;
BTIF_TRACE_DEBUG("%s type:%u code:%u value:%d", __FUNCTION__,
type, code, value);
memset(&event, 0, sizeof(event));
event.type = type;
event.code = code;
event.value = value;
return TEMP_FAILURE_RETRY(write(fd, &event, sizeof(event)));
}
| 173,451 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ServerWrapper::OnHttpRequest(int connection_id,
const net::HttpServerRequestInfo& info) {
server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools);
if (base::StartsWith(info.path, "/json", base::CompareCase::SENSITIVE)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnJsonRequest,
handler_, connection_id, info));
return;
}
if (info.path.empty() || info.path == "/") {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnDiscoveryPageRequest, handler_,
connection_id));
return;
}
if (!base::StartsWith(info.path, "/devtools/",
base::CompareCase::SENSITIVE)) {
server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation);
return;
}
std::string filename = PathWithoutParams(info.path.substr(10));
std::string mime_type = GetMimeType(filename);
if (!debug_frontend_dir_.empty()) {
base::FilePath path = debug_frontend_dir_.AppendASCII(filename);
std::string data;
base::ReadFileToString(path, &data);
server_->Send200(connection_id, data, mime_type,
kDevtoolsHttpHandlerTrafficAnnotation);
return;
}
if (bundles_resources_) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnFrontendResourceRequest,
handler_, connection_id, filename));
return;
}
server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation);
}
Commit Message: DevTools: check Host header for being IP or localhost when connecting over RDP.
Bug: 813540
Change-Id: I9338aa2475c15090b8a60729be25502eb866efb7
Reviewed-on: https://chromium-review.googlesource.com/952522
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Pavel Feldman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#541547}
CWE ID: CWE-20 | void ServerWrapper::OnHttpRequest(int connection_id,
const net::HttpServerRequestInfo& info) {
if (!RequestIsSafeToServe(info)) {
Send500(connection_id,
"Host header is specified and is not an IP address or localhost.");
return;
}
server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools);
if (base::StartsWith(info.path, "/json", base::CompareCase::SENSITIVE)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnJsonRequest,
handler_, connection_id, info));
return;
}
if (info.path.empty() || info.path == "/") {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnDiscoveryPageRequest, handler_,
connection_id));
return;
}
if (!base::StartsWith(info.path, "/devtools/",
base::CompareCase::SENSITIVE)) {
server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation);
return;
}
std::string filename = PathWithoutParams(info.path.substr(10));
std::string mime_type = GetMimeType(filename);
if (!debug_frontend_dir_.empty()) {
base::FilePath path = debug_frontend_dir_.AppendASCII(filename);
std::string data;
base::ReadFileToString(path, &data);
server_->Send200(connection_id, data, mime_type,
kDevtoolsHttpHandlerTrafficAnnotation);
return;
}
if (bundles_resources_) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnFrontendResourceRequest,
handler_, connection_id, filename));
return;
}
server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation);
}
| 172,732 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftVPXEncoder::onQueueFilled(OMX_U32 /* portIndex */) {
if (mCodecContext == NULL) {
if (OK != initEncoder()) {
ALOGE("Failed to initialize encoder");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
}
vpx_codec_err_t codec_return;
List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex);
while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) {
BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader;
BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader;
if ((inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) &&
inputBufferHeader->nFilledLen == 0) {
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
inputBufferInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inputBufferHeader);
outputBufferHeader->nFilledLen = 0;
outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
outputBufferInfo->mOwnedByUs = false;
notifyFillBufferDone(outputBufferHeader);
return;
}
const uint8_t *source =
inputBufferHeader->pBuffer + inputBufferHeader->nOffset;
if (mInputDataIsMeta) {
source = extractGraphicBuffer(
mConversionBuffer, mWidth * mHeight * 3 / 2,
source, inputBufferHeader->nFilledLen,
mWidth, mHeight);
if (source == NULL) {
ALOGE("Unable to extract gralloc buffer in metadata mode");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
} else if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) {
ConvertYUV420SemiPlanarToYUV420Planar(
source, mConversionBuffer, mWidth, mHeight);
source = mConversionBuffer;
}
vpx_image_t raw_frame;
vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight,
kInputBufferAlignment, (uint8_t *)source);
vpx_enc_frame_flags_t flags = 0;
if (mTemporalPatternLength > 0) {
flags = getEncodeFlags();
}
if (mKeyFrameRequested) {
flags |= VPX_EFLAG_FORCE_KF;
mKeyFrameRequested = false;
}
if (mBitrateUpdated) {
mCodecConfiguration->rc_target_bitrate = mBitrate/1000;
vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext,
mCodecConfiguration);
if (res != VPX_CODEC_OK) {
ALOGE("vp8 encoder failed to update bitrate: %s",
vpx_codec_err_to_string(res));
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
}
mBitrateUpdated = false;
}
uint32_t frameDuration;
if (inputBufferHeader->nTimeStamp > mLastTimestamp) {
frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp);
} else {
frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate);
}
mLastTimestamp = inputBufferHeader->nTimeStamp;
codec_return = vpx_codec_encode(
mCodecContext,
&raw_frame,
inputBufferHeader->nTimeStamp, // in timebase units
frameDuration, // frame duration in timebase units
flags, // frame flags
VPX_DL_REALTIME); // encoding deadline
if (codec_return != VPX_CODEC_OK) {
ALOGE("vpx encoder failed to encode frame");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
vpx_codec_iter_t encoded_packet_iterator = NULL;
const vpx_codec_cx_pkt_t* encoded_packet;
while ((encoded_packet = vpx_codec_get_cx_data(
mCodecContext, &encoded_packet_iterator))) {
if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) {
outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts;
outputBufferHeader->nFlags = 0;
if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY)
outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME;
outputBufferHeader->nOffset = 0;
outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz;
memcpy(outputBufferHeader->pBuffer,
encoded_packet->data.frame.buf,
encoded_packet->data.frame.sz);
outputBufferInfo->mOwnedByUs = false;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outputBufferHeader->nFlags |= OMX_BUFFERFLAG_EOS;
}
notifyFillBufferDone(outputBufferHeader);
}
}
inputBufferInfo->mOwnedByUs = false;
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
notifyEmptyBufferDone(inputBufferHeader);
}
}
Commit Message: codecs: check OMX buffer size before use in VP8 encoder.
Bug: 27569635
Change-Id: I469573f40e21dc9f4c200749d4f220e3a2d31761
CWE ID: CWE-264 | void SoftVPXEncoder::onQueueFilled(OMX_U32 /* portIndex */) {
if (mCodecContext == NULL) {
if (OK != initEncoder()) {
ALOGE("Failed to initialize encoder");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
}
vpx_codec_err_t codec_return;
List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex);
while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) {
BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader;
BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader;
if ((inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) &&
inputBufferHeader->nFilledLen == 0) {
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
inputBufferInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inputBufferHeader);
outputBufferHeader->nFilledLen = 0;
outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
outputBufferInfo->mOwnedByUs = false;
notifyFillBufferDone(outputBufferHeader);
return;
}
const uint8_t *source =
inputBufferHeader->pBuffer + inputBufferHeader->nOffset;
size_t frameSize = mWidth * mHeight * 3 / 2;
if (mInputDataIsMeta) {
source = extractGraphicBuffer(
mConversionBuffer, frameSize,
source, inputBufferHeader->nFilledLen,
mWidth, mHeight);
if (source == NULL) {
ALOGE("Unable to extract gralloc buffer in metadata mode");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
} else {
if (inputBufferHeader->nFilledLen < frameSize) {
android_errorWriteLog(0x534e4554, "27569635");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
} else if (inputBufferHeader->nFilledLen > frameSize) {
ALOGW("Input buffer contains too many pixels");
}
if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) {
ConvertYUV420SemiPlanarToYUV420Planar(
source, mConversionBuffer, mWidth, mHeight);
source = mConversionBuffer;
}
}
vpx_image_t raw_frame;
vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight,
kInputBufferAlignment, (uint8_t *)source);
vpx_enc_frame_flags_t flags = 0;
if (mTemporalPatternLength > 0) {
flags = getEncodeFlags();
}
if (mKeyFrameRequested) {
flags |= VPX_EFLAG_FORCE_KF;
mKeyFrameRequested = false;
}
if (mBitrateUpdated) {
mCodecConfiguration->rc_target_bitrate = mBitrate/1000;
vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext,
mCodecConfiguration);
if (res != VPX_CODEC_OK) {
ALOGE("vp8 encoder failed to update bitrate: %s",
vpx_codec_err_to_string(res));
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
}
mBitrateUpdated = false;
}
uint32_t frameDuration;
if (inputBufferHeader->nTimeStamp > mLastTimestamp) {
frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp);
} else {
frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate);
}
mLastTimestamp = inputBufferHeader->nTimeStamp;
codec_return = vpx_codec_encode(
mCodecContext,
&raw_frame,
inputBufferHeader->nTimeStamp, // in timebase units
frameDuration, // frame duration in timebase units
flags, // frame flags
VPX_DL_REALTIME); // encoding deadline
if (codec_return != VPX_CODEC_OK) {
ALOGE("vpx encoder failed to encode frame");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
vpx_codec_iter_t encoded_packet_iterator = NULL;
const vpx_codec_cx_pkt_t* encoded_packet;
while ((encoded_packet = vpx_codec_get_cx_data(
mCodecContext, &encoded_packet_iterator))) {
if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) {
outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts;
outputBufferHeader->nFlags = 0;
if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY)
outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME;
outputBufferHeader->nOffset = 0;
outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz;
if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) {
android_errorWriteLog(0x534e4554, "27569635");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
memcpy(outputBufferHeader->pBuffer,
encoded_packet->data.frame.buf,
encoded_packet->data.frame.sz);
outputBufferInfo->mOwnedByUs = false;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outputBufferHeader->nFlags |= OMX_BUFFERFLAG_EOS;
}
notifyFillBufferDone(outputBufferHeader);
}
}
inputBufferInfo->mOwnedByUs = false;
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
notifyEmptyBufferDone(inputBufferHeader);
}
}
| 173,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: bool WtsSessionProcessDelegate::Core::Initialize(uint32 session_id) {
if (base::win::GetVersion() == base::win::VERSION_XP)
launch_elevated_ = false;
if (launch_elevated_) {
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid()) {
LOG(ERROR) << "Failed to create a nameless event";
return false;
}
io_task_runner_->PostTask(FROM_HERE,
base::Bind(&Core::InitializeJob, this));
}
return CreateSessionToken(session_id, &session_token_);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool WtsSessionProcessDelegate::Core::Initialize(uint32 session_id) {
if (base::win::GetVersion() == base::win::VERSION_XP)
launch_elevated_ = false;
if (launch_elevated_) {
// GetNamedPipeClientProcessId() is available starting from Vista.
HMODULE kernel32 = ::GetModuleHandle(L"kernel32.dll");
CHECK(kernel32 != NULL);
get_named_pipe_client_pid_ =
reinterpret_cast<GetNamedPipeClientProcessIdFn>(
GetProcAddress(kernel32, "GetNamedPipeClientProcessId"));
CHECK(get_named_pipe_client_pid_ != NULL);
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid()) {
LOG(ERROR) << "Failed to create a nameless event";
return false;
}
io_task_runner_->PostTask(FROM_HERE,
base::Bind(&Core::InitializeJob, this));
}
return CreateSessionToken(session_id, &session_token_);
}
| 171,558 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LockScreenMediaControlsView::OnMouseEntered(const ui::MouseEvent& event) {
if (is_in_drag_ || contents_view_->layer()->GetAnimator()->is_animating())
return;
close_button_->SetVisible(true);
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | void LockScreenMediaControlsView::OnMouseEntered(const ui::MouseEvent& event) {
if (is_in_drag_ || contents_view_->layer()->GetAnimator()->is_animating())
return;
header_row_->SetCloseButtonVisibility(true);
}
| 172,340 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: UserSelectionScreen::UpdateAndReturnUserListForMojo() {
std::vector<ash::mojom::LoginUserInfoPtr> user_info_list;
const AccountId owner = GetOwnerAccountId();
const bool is_signin_to_add = IsSigninToAdd();
users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add);
user_auth_type_map_.clear();
for (user_manager::UserList::const_iterator it = users_to_send_.begin();
it != users_to_send_.end(); ++it) {
const AccountId& account_id = (*it)->GetAccountId();
bool is_owner = owner == account_id;
const bool is_public_account =
((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT);
const proximity_auth::mojom::AuthType initial_auth_type =
is_public_account
? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK
: (ShouldForceOnlineSignIn(*it)
? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN
: proximity_auth::mojom::AuthType::OFFLINE_PASSWORD);
user_auth_type_map_[account_id] = initial_auth_type;
ash::mojom::LoginUserInfoPtr login_user_info =
ash::mojom::LoginUserInfo::New();
const std::vector<std::string>* public_session_recommended_locales =
public_session_recommended_locales_.find(account_id) ==
public_session_recommended_locales_.end()
? nullptr
: &public_session_recommended_locales_[account_id];
FillUserMojoStruct(*it, is_owner, is_signin_to_add, initial_auth_type,
public_session_recommended_locales,
login_user_info.get());
login_user_info->can_remove = CanRemoveUser(*it);
if (is_public_account && LoginScreenClient::HasInstance()) {
LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts(
account_id, login_user_info->public_account_info->default_locale);
}
user_info_list.push_back(std::move(login_user_info));
}
return user_info_list;
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID: | UserSelectionScreen::UpdateAndReturnUserListForMojo() {
std::vector<ash::mojom::LoginUserInfoPtr> user_info_list;
const AccountId owner = GetOwnerAccountId();
const bool is_signin_to_add = IsSigninToAdd();
users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add);
user_auth_type_map_.clear();
for (const user_manager::User* user : users_to_send_) {
const AccountId& account_id = user->GetAccountId();
bool is_owner = owner == account_id;
const bool is_public_account =
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT;
const proximity_auth::mojom::AuthType initial_auth_type =
is_public_account
? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK
: (ShouldForceOnlineSignIn(user)
? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN
: proximity_auth::mojom::AuthType::OFFLINE_PASSWORD);
user_auth_type_map_[account_id] = initial_auth_type;
ash::mojom::LoginUserInfoPtr user_info = ash::mojom::LoginUserInfo::New();
user_info->basic_user_info = ash::mojom::UserInfo::New();
user_info->basic_user_info->type = user->GetType();
user_info->basic_user_info->account_id = user->GetAccountId();
user_info->basic_user_info->display_name =
base::UTF16ToUTF8(user->GetDisplayName());
user_info->basic_user_info->display_email = user->display_email();
user_info->basic_user_info->avatar = BuildMojoUserAvatarForUser(user);
user_info->auth_type = initial_auth_type;
user_info->is_signed_in = user->is_logged_in();
user_info->is_device_owner = is_owner;
user_info->can_remove = CanRemoveUser(user);
user_info->allow_fingerprint_unlock = AllowFingerprintForUser(user);
// Fill multi-profile data.
if (!is_signin_to_add) {
user_info->is_multiprofile_allowed = true;
} else {
GetMultiProfilePolicy(user, &user_info->is_multiprofile_allowed,
&user_info->multiprofile_policy);
}
// Fill public session data.
if (user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) {
user_info->public_account_info = ash::mojom::PublicAccountInfo::New();
std::string domain;
if (GetEnterpriseDomain(&domain))
user_info->public_account_info->enterprise_domain = domain;
const std::vector<std::string>* public_session_recommended_locales =
public_session_recommended_locales_.find(account_id) ==
public_session_recommended_locales_.end()
? nullptr
: &public_session_recommended_locales_[account_id];
std::string selected_locale;
bool has_multiple_locales;
std::unique_ptr<base::ListValue> available_locales =
GetPublicSessionLocales(public_session_recommended_locales,
&selected_locale, &has_multiple_locales);
DCHECK(available_locales);
user_info->public_account_info->available_locales =
lock_screen_utils::FromListValueToLocaleItem(
std::move(available_locales));
user_info->public_account_info->default_locale = selected_locale;
user_info->public_account_info->show_advanced_view = has_multiple_locales;
}
user_info->can_remove = CanRemoveUser(user);
if (is_public_account && LoginScreenClient::HasInstance()) {
LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts(
account_id, user_info->public_account_info->default_locale);
}
user_info_list.push_back(std::move(user_info));
}
return user_info_list;
}
| 172,204 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltAttrListTemplateProcess(xsltTransformContextPtr ctxt,
xmlNodePtr target, xmlAttrPtr attrs)
{
xmlAttrPtr attr, copy, last;
xmlNodePtr oldInsert, text;
xmlNsPtr origNs = NULL, copyNs = NULL;
const xmlChar *value;
xmlChar *valueAVT;
if ((ctxt == NULL) || (target == NULL) || (attrs == NULL))
return(NULL);
oldInsert = ctxt->insert;
ctxt->insert = target;
/*
* Instantiate LRE-attributes.
*/
if (target->properties) {
last = target->properties;
while (last->next != NULL)
last = last->next;
} else {
last = NULL;
}
attr = attrs;
do {
/*
* Skip XSLT attributes.
*/
#ifdef XSLT_REFACTORED
if (attr->psvi == xsltXSLTAttrMarker) {
goto next_attribute;
}
#else
if ((attr->ns != NULL) &&
xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
{
goto next_attribute;
}
#endif
/*
* Get the value.
*/
if (attr->children != NULL) {
if ((attr->children->type != XML_TEXT_NODE) ||
(attr->children->next != NULL))
{
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: The children of an attribute node of a "
"literal result element are not in the expected form.\n");
goto error;
}
value = attr->children->content;
if (value == NULL)
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
} else
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
/*
* Create a new attribute.
*/
copy = xmlNewDocProp(target->doc, attr->name, NULL);
if (copy == NULL) {
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '%s'.\n",
attr->name);
}
goto error;
}
/*
* Attach it to the target element.
*/
copy->parent = target;
if (last == NULL) {
target->properties = copy;
last = copy;
} else {
last->next = copy;
copy->prev = last;
last = copy;
}
/*
* Set the namespace. Avoid lookups of same namespaces.
*/
if (attr->ns != origNs) {
origNs = attr->ns;
if (attr->ns != NULL) {
#ifdef XSLT_REFACTORED
copyNs = xsltGetSpecialNamespace(ctxt, attr->parent,
attr->ns->href, attr->ns->prefix, target);
#else
copyNs = xsltGetNamespace(ctxt, attr->parent,
attr->ns, target);
#endif
if (copyNs == NULL)
goto error;
} else
copyNs = NULL;
}
copy->ns = copyNs;
/*
* Set the value.
*/
text = xmlNewText(NULL);
if (text != NULL) {
copy->last = copy->children = text;
text->parent = (xmlNodePtr) copy;
text->doc = copy->doc;
if (attr->psvi != NULL) {
/*
* Evaluate the Attribute Value Template.
*/
valueAVT = xsltEvalAVT(ctxt, attr->psvi, attr->parent);
if (valueAVT == NULL) {
/*
* TODO: Damn, we need an easy mechanism to report
* qualified names!
*/
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '%s'.\n",
attr->name);
}
text->content = xmlStrdup(BAD_CAST "");
goto error;
} else {
text->content = valueAVT;
}
} else if ((ctxt->internalized) &&
(target->doc != NULL) &&
(target->doc->dict == ctxt->dict))
{
text->content = (xmlChar *) value;
} else {
text->content = xmlStrdup(value);
}
if ((copy != NULL) && (text != NULL) &&
(xmlIsID(copy->doc, copy->parent, copy)))
xmlAddID(NULL, copy->doc, text->content, copy);
}
next_attribute:
attr = attr->next;
} while (attr != NULL);
/*
* Apply attribute-sets.
* The creation of such attributes will not overwrite any existing
* attribute.
*/
attr = attrs;
do {
#ifdef XSLT_REFACTORED
if ((attr->psvi == xsltXSLTAttrMarker) &&
xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets"))
{
xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);
}
#else
if ((attr->ns != NULL) &&
xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets") &&
xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
{
xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);
}
#endif
attr = attr->next;
} while (attr != NULL);
ctxt->insert = oldInsert;
return(target->properties);
error:
ctxt->insert = oldInsert;
return(NULL);
}
Commit Message: Fix dictionary string usage.
BUG=144799
Review URL: https://chromiumcodereview.appspot.com/10919019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154331 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | xsltAttrListTemplateProcess(xsltTransformContextPtr ctxt,
xmlNodePtr target, xmlAttrPtr attrs)
{
xmlAttrPtr attr, copy, last;
xmlNodePtr oldInsert, text;
xmlNsPtr origNs = NULL, copyNs = NULL;
const xmlChar *value;
xmlChar *valueAVT;
if ((ctxt == NULL) || (target == NULL) || (attrs == NULL))
return(NULL);
oldInsert = ctxt->insert;
ctxt->insert = target;
/*
* Instantiate LRE-attributes.
*/
if (target->properties) {
last = target->properties;
while (last->next != NULL)
last = last->next;
} else {
last = NULL;
}
attr = attrs;
do {
/*
* Skip XSLT attributes.
*/
#ifdef XSLT_REFACTORED
if (attr->psvi == xsltXSLTAttrMarker) {
goto next_attribute;
}
#else
if ((attr->ns != NULL) &&
xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
{
goto next_attribute;
}
#endif
/*
* Get the value.
*/
if (attr->children != NULL) {
if ((attr->children->type != XML_TEXT_NODE) ||
(attr->children->next != NULL))
{
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: The children of an attribute node of a "
"literal result element are not in the expected form.\n");
goto error;
}
value = attr->children->content;
if (value == NULL)
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
} else
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
/*
* Create a new attribute.
*/
copy = xmlNewDocProp(target->doc, attr->name, NULL);
if (copy == NULL) {
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '%s'.\n",
attr->name);
}
goto error;
}
/*
* Attach it to the target element.
*/
copy->parent = target;
if (last == NULL) {
target->properties = copy;
last = copy;
} else {
last->next = copy;
copy->prev = last;
last = copy;
}
/*
* Set the namespace. Avoid lookups of same namespaces.
*/
if (attr->ns != origNs) {
origNs = attr->ns;
if (attr->ns != NULL) {
#ifdef XSLT_REFACTORED
copyNs = xsltGetSpecialNamespace(ctxt, attr->parent,
attr->ns->href, attr->ns->prefix, target);
#else
copyNs = xsltGetNamespace(ctxt, attr->parent,
attr->ns, target);
#endif
if (copyNs == NULL)
goto error;
} else
copyNs = NULL;
}
copy->ns = copyNs;
/*
* Set the value.
*/
text = xmlNewText(NULL);
if (text != NULL) {
copy->last = copy->children = text;
text->parent = (xmlNodePtr) copy;
text->doc = copy->doc;
if (attr->psvi != NULL) {
/*
* Evaluate the Attribute Value Template.
*/
valueAVT = xsltEvalAVT(ctxt, attr->psvi, attr->parent);
if (valueAVT == NULL) {
/*
* TODO: Damn, we need an easy mechanism to report
* qualified names!
*/
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '%s'.\n",
attr->name);
}
text->content = xmlStrdup(BAD_CAST "");
goto error;
} else {
text->content = valueAVT;
}
} else if ((ctxt->internalized) &&
(target->doc != NULL) &&
(target->doc->dict == ctxt->dict) &&
xmlDictOwns(ctxt->dict, value))
{
text->content = (xmlChar *) value;
} else {
text->content = xmlStrdup(value);
}
if ((copy != NULL) && (text != NULL) &&
(xmlIsID(copy->doc, copy->parent, copy)))
xmlAddID(NULL, copy->doc, text->content, copy);
}
next_attribute:
attr = attr->next;
} while (attr != NULL);
/*
* Apply attribute-sets.
* The creation of such attributes will not overwrite any existing
* attribute.
*/
attr = attrs;
do {
#ifdef XSLT_REFACTORED
if ((attr->psvi == xsltXSLTAttrMarker) &&
xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets"))
{
xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);
}
#else
if ((attr->ns != NULL) &&
xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets") &&
xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
{
xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);
}
#endif
attr = attr->next;
} while (attr != NULL);
ctxt->insert = oldInsert;
return(target->properties);
error:
ctxt->insert = oldInsert;
return(NULL);
}
| 170,859 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 StoreAccumulatedContentLength(int received_content_length,
int original_content_length,
bool data_reduction_proxy_was_used) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&UpdateContentLengthPrefs,
received_content_length, original_content_length,
data_reduction_proxy_was_used));
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void StoreAccumulatedContentLength(int received_content_length,
void StoreAccumulatedContentLength(
int received_content_length,
int original_content_length,
chrome_browser_net::DataReductionRequestType data_reduction_type) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&UpdateContentLengthPrefs,
received_content_length, original_content_length,
data_reduction_type));
}
| 171,333 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200 | int res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1; // "partition size" in spec
info->partitions=(char)(oggpack_read(opb,6)+1); // "classification" in spec
info->groupbook=(unsigned char)oggpack_read(opb,8); // "classbook" in spec
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
// According to the Vorbis spec (paragraph 8.6.2 "packet decode"), residue
// begin and end should be limited to the maximum possible vector size in
// case they exceed it. However doing that makes the decoder crash further
// down, so we return an error instead.
int limit = (info->type == 2 ? vi->channels : 1) * ci->blocksizes[1] / 2;
if (info->begin > info->end ||
info->end > limit) {
goto errout;
}
return 0;
errout:
res_clear_info(info);
return 1;
}
| 173,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 search_old_relocation(struct reloc_struct_t *reloc_table, ut32 addr_to_patch, int n_reloc) {
int i;
for (i = 0; i < n_reloc; i++) {
if (addr_to_patch == reloc_table[i].data_offset) {
return i;
}
}
return -1;
}
Commit Message: Fix #6829 oob write because of using wrong struct
CWE ID: CWE-119 | static int search_old_relocation(struct reloc_struct_t *reloc_table, ut32 addr_to_patch, int n_reloc) {
static int search_old_relocation (struct reloc_struct_t *reloc_table,
ut32 addr_to_patch, int n_reloc) {
int i;
for (i = 0; i < n_reloc; i++) {
if (addr_to_patch == reloc_table[i].data_offset) {
return i;
}
}
return -1;
}
| 168,365 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_insert(netdissect_options *ndo,
const u_char *bp, const struct ip *ip, int dport)
{
struct rx_cache_entry *rxent;
const struct rx_header *rxh = (const struct rx_header *) bp;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t)))
return;
rxent = &rx_cache[rx_cache_next];
if (++rx_cache_next >= RX_CACHE_SIZE)
rx_cache_next = 0;
rxent->callnum = EXTRACT_32BITS(&rxh->callNumber);
UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));
UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));
rxent->dport = dport;
rxent->serviceId = EXTRACT_32BITS(&rxh->serviceId);
rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));
}
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_insert(netdissect_options *ndo,
const u_char *bp, const struct ip *ip, int dport)
{
struct rx_cache_entry *rxent;
const struct rx_header *rxh = (const struct rx_header *) bp;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t)))
return;
rxent = &rx_cache[rx_cache_next];
if (++rx_cache_next >= RX_CACHE_SIZE)
rx_cache_next = 0;
rxent->callnum = EXTRACT_32BITS(&rxh->callNumber);
UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));
UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));
rxent->dport = dport;
rxent->serviceId = EXTRACT_16BITS(&rxh->serviceId);
rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));
}
| 169,846 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
uint32 close_types) {
if (indices.empty())
return true;
bool retval = true;
std::vector<TabContentsWrapper*> tabs;
for (size_t i = 0; i < indices.size(); ++i)
tabs.push_back(GetContentsAt(indices[i]));
if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
std::map<RenderProcessHost*, size_t> processes;
for (size_t i = 0; i < indices.size(); ++i) {
if (!delegate_->CanCloseContentsAt(indices[i])) {
retval = false;
continue;
}
TabContentsWrapper* detached_contents = GetContentsAt(indices[i]);
RenderProcessHost* process =
detached_contents->tab_contents()->GetRenderProcessHost();
std::map<RenderProcessHost*, size_t>::iterator iter =
processes.find(process);
if (iter == processes.end()) {
processes[process] = 1;
} else {
iter->second++;
}
}
for (std::map<RenderProcessHost*, size_t>::iterator iter =
processes.begin();
iter != processes.end(); ++iter) {
iter->first->FastShutdownForPageCount(iter->second);
}
}
for (size_t i = 0; i < tabs.size(); ++i) {
TabContentsWrapper* detached_contents = tabs[i];
int index = GetIndexOfTabContents(detached_contents);
if (index == kNoTab)
continue;
detached_contents->tab_contents()->OnCloseStarted();
if (!delegate_->CanCloseContentsAt(index)) {
retval = false;
continue;
}
if (!detached_contents->tab_contents()->closed_by_user_gesture()) {
detached_contents->tab_contents()->set_closed_by_user_gesture(
close_types & CLOSE_USER_GESTURE);
}
if (delegate_->RunUnloadListenerBeforeClosing(detached_contents)) {
retval = false;
continue;
}
InternalCloseTab(detached_contents, index,
(close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
}
return retval;
}
Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab.
BUG=chromium-os:12088
TEST=verify bug per bug report.
Review URL: http://codereview.chromium.org/6882058
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
bool TabStripModel::InternalCloseTabs(const std::vector<int>& in_indices,
uint32 close_types) {
if (in_indices.empty())
return true;
std::vector<int> indices(in_indices);
bool retval = delegate_->CanCloseContents(&indices);
if (indices.empty())
return retval;
std::vector<TabContentsWrapper*> tabs;
for (size_t i = 0; i < indices.size(); ++i)
tabs.push_back(GetContentsAt(indices[i]));
if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
std::map<RenderProcessHost*, size_t> processes;
for (size_t i = 0; i < indices.size(); ++i) {
TabContentsWrapper* detached_contents = GetContentsAt(indices[i]);
RenderProcessHost* process =
detached_contents->tab_contents()->GetRenderProcessHost();
std::map<RenderProcessHost*, size_t>::iterator iter =
processes.find(process);
if (iter == processes.end()) {
processes[process] = 1;
} else {
iter->second++;
}
}
for (std::map<RenderProcessHost*, size_t>::iterator iter =
processes.begin();
iter != processes.end(); ++iter) {
iter->first->FastShutdownForPageCount(iter->second);
}
}
for (size_t i = 0; i < tabs.size(); ++i) {
TabContentsWrapper* detached_contents = tabs[i];
int index = GetIndexOfTabContents(detached_contents);
if (index == kNoTab)
continue;
detached_contents->tab_contents()->OnCloseStarted();
if (!detached_contents->tab_contents()->closed_by_user_gesture()) {
detached_contents->tab_contents()->set_closed_by_user_gesture(
close_types & CLOSE_USER_GESTURE);
}
if (delegate_->RunUnloadListenerBeforeClosing(detached_contents)) {
retval = false;
continue;
}
InternalCloseTab(detached_contents, index,
(close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
}
return retval;
}
| 170,302 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();
if (!config) {
LOG_ERROR(LOG_TAG, "%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))
unlink(LEGACY_CONFIG_FILE_PATH);
}
alarm_timer = alarm_new();
if (!alarm_timer) {
LOG_ERROR(LOG_TAG, "%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
Commit Message: Fix crashes with lots of discovered LE devices
When loads of devices are discovered a config file which is too large
can be written out, which causes the BT daemon to crash on startup.
This limits the number of config entries for unpaired devices which
are initialized, and prevents a large number from being saved to the
filesystem.
Bug: 26071376
Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184
CWE ID: CWE-119 | static future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();
if (!config) {
LOG_ERROR(LOG_TAG, "%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))
unlink(LEGACY_CONFIG_FILE_PATH);
}
btif_config_devcache_cleanup();
alarm_timer = alarm_new();
if (!alarm_timer) {
LOG_ERROR(LOG_TAG, "%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
| 173,930 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response,
const GURL& url) {
//// static
DCHECK(response && response->headers.get());
std::string location;
if (!response->headers->IsRedirect(&location))
return false;
std::string fake_response_headers =
base::StringPrintf("HTTP/1.0 302 Found\n"
"Location: %s\n"
"Content-length: 0\n"
"Connection: close\n"
"\n",
location.c_str());
std::string raw_headers =
HttpUtil::AssembleRawHeaders(fake_response_headers.data(),
fake_response_headers.length());
response->headers = new HttpResponseHeaders(raw_headers);
return true;
}
Commit Message: Sanitize headers in Proxy Authentication Required responses
BUG=431504
Review URL: https://codereview.chromium.org/769043003
Cr-Commit-Position: refs/heads/master@{#310014}
CWE ID: CWE-19 | bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response,
bool ProxyClientSocket::SanitizeProxyAuth(HttpResponseInfo* response) {
DCHECK(response && response->headers.get());
scoped_refptr<HttpResponseHeaders> old_headers = response->headers;
const char kHeaders[] = "HTTP/1.1 407 Proxy Authentication Required\n\n";
scoped_refptr<HttpResponseHeaders> new_headers = new HttpResponseHeaders(
HttpUtil::AssembleRawHeaders(kHeaders, arraysize(kHeaders)));
new_headers->ReplaceStatusLine(old_headers->GetStatusLine());
CopyHeaderValues(old_headers, new_headers, "Connection");
CopyHeaderValues(old_headers, new_headers, "Proxy-Authenticate");
response->headers = new_headers;
return true;
}
//// static
bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response) {
DCHECK(response && response->headers.get());
std::string location;
if (!response->headers->IsRedirect(&location))
return false;
// Return minimal headers; set "Content-Length: 0" to ignore response body.
std::string fake_response_headers = base::StringPrintf(
"HTTP/1.0 302 Found\n"
"Location: %s\n"
"Content-Length: 0\n"
"Connection: close\n"
"\n",
location.c_str());
std::string raw_headers =
HttpUtil::AssembleRawHeaders(fake_response_headers.data(),
fake_response_headers.length());
response->headers = new HttpResponseHeaders(raw_headers);
return true;
}
| 172,040 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Backtrace::GetFunctionName(uintptr_t pc, uintptr_t* offset) {
std::string func_name = GetFunctionNameRaw(pc, offset);
if (!func_name.empty()) {
#if defined(__APPLE__)
if (func_name[0] != '_') {
return func_name;
}
#endif
char* name = __cxa_demangle(func_name.c_str(), 0, 0, 0);
if (name) {
func_name = name;
free(name);
}
}
return func_name;
}
Commit Message: Don't demangle symbol names.
Bug: http://b/27299236
Change-Id: I26ef47f80d4d6048a316ba51e83365ff65d70439
CWE ID: CWE-264 | std::string Backtrace::GetFunctionName(uintptr_t pc, uintptr_t* offset) {
std::string func_name = GetFunctionNameRaw(pc, offset);
return func_name;
}
| 173,887 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLMediaElement::NoneSupported(const String& message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='" << message
<< "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200 | void HTMLMediaElement::NoneSupported(const String& message) {
void HTMLMediaElement::NoneSupported(const String& input_message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='"
<< input_message << "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
String empty_string;
const String& message = MediaShouldBeOpaque() ? empty_string : input_message;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
| 173,163 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap)
{
RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
ScriptPromise promise = resolver->promise();
resolver->resolve(imageBitmap);
return promise;
}
Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas
BUG=354356
Review URL: https://codereview.chromium.org/211313003
git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap)
{
RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
ScriptPromise promise = resolver->promise();
if (imageBitmap) {
resolver->resolve(imageBitmap);
} else {
v8::Isolate* isolate = ScriptState::current()->isolate();
resolver->reject(ScriptValue(v8::Null(isolate), isolate));
}
return promise;
}
| 171,395 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
*session_data_size = psession.size;
if (psession.size > *session_data_size)
{
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
Commit Message:
CWE ID: CWE-119 | gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
if (psession.size > *session_data_size)
{
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
*session_data_size = psession.size;
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
| 164,569 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(GetProcess(), nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
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 SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
| 172,787 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MakeGroupObsolete() {
PushNextTask(
base::BindOnce(&AppCacheStorageImplTest::Verify_MakeGroupObsolete,
base::Unretained(this)));
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
AppCacheDatabase::EntryRecord entry_record;
entry_record.cache_id = 1;
entry_record.flags = AppCacheEntry::FALLBACK;
entry_record.response_id = 1;
entry_record.url = kEntryUrl;
EXPECT_TRUE(database()->InsertEntry(&entry_record));
AppCacheDatabase::NamespaceRecord fallback_namespace_record;
fallback_namespace_record.cache_id = 1;
fallback_namespace_record.namespace_.target_url = kEntryUrl;
fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace;
fallback_namespace_record.origin = url::Origin::Create(kManifestUrl);
EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record));
AppCacheDatabase::OnlineWhiteListRecord online_whitelist_record;
online_whitelist_record.cache_id = 1;
online_whitelist_record.namespace_url = kOnlineNamespace;
EXPECT_TRUE(database()->InsertOnlineWhiteList(&online_whitelist_record));
storage()->MakeGroupObsolete(group_.get(), delegate(), 0);
EXPECT_FALSE(group_->is_obsolete());
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void MakeGroupObsolete() {
PushNextTask(
base::BindOnce(&AppCacheStorageImplTest::Verify_MakeGroupObsolete,
base::Unretained(this)));
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
EXPECT_EQ(kDefaultEntrySize + kDefaultEntryPadding,
storage()->usage_map_[kOrigin]);
AppCacheDatabase::EntryRecord entry_record;
entry_record.cache_id = 1;
entry_record.flags = AppCacheEntry::FALLBACK;
entry_record.response_id = 1;
entry_record.url = kEntryUrl;
EXPECT_TRUE(database()->InsertEntry(&entry_record));
AppCacheDatabase::NamespaceRecord fallback_namespace_record;
fallback_namespace_record.cache_id = 1;
fallback_namespace_record.namespace_.target_url = kEntryUrl;
fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace;
fallback_namespace_record.origin = url::Origin::Create(kManifestUrl);
EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record));
AppCacheDatabase::OnlineWhiteListRecord online_whitelist_record;
online_whitelist_record.cache_id = 1;
online_whitelist_record.namespace_url = kOnlineNamespace;
EXPECT_TRUE(database()->InsertOnlineWhiteList(&online_whitelist_record));
storage()->MakeGroupObsolete(group_.get(), delegate(), 0);
EXPECT_FALSE(group_->is_obsolete());
}
| 172,987 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int usb_enumerate_device_otg(struct usb_device *udev)
{
int err = 0;
#ifdef CONFIG_USB_OTG
/*
* OTG-aware devices on OTG-capable root hubs may be able to use SRP,
* to wake us after we've powered off VBUS; and HNP, switching roles
* "host" to "peripheral". The OTG descriptor helps figure this out.
*/
if (!udev->bus->is_b_host
&& udev->config
&& udev->parent == udev->bus->root_hub) {
struct usb_otg_descriptor *desc = NULL;
struct usb_bus *bus = udev->bus;
unsigned port1 = udev->portnum;
/* descriptor may appear anywhere in config */
err = __usb_get_extra_descriptor(udev->rawdescriptors[0],
le16_to_cpu(udev->config[0].desc.wTotalLength),
USB_DT_OTG, (void **) &desc);
if (err || !(desc->bmAttributes & USB_OTG_HNP))
return 0;
dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n",
(port1 == bus->otg_port) ? "" : "non-");
/* enable HNP before suspend, it's simpler */
if (port1 == bus->otg_port) {
bus->b_hnp_enable = 1;
err = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
USB_REQ_SET_FEATURE, 0,
USB_DEVICE_B_HNP_ENABLE,
0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (err < 0) {
/*
* OTG MESSAGE: report errors here,
* customize to match your product.
*/
dev_err(&udev->dev, "can't set HNP mode: %d\n",
err);
bus->b_hnp_enable = 0;
}
} else if (desc->bLength == sizeof
(struct usb_otg_descriptor)) {
/* Set a_alt_hnp_support for legacy otg device */
err = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
USB_REQ_SET_FEATURE, 0,
USB_DEVICE_A_ALT_HNP_SUPPORT,
0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (err < 0)
dev_err(&udev->dev,
"set a_alt_hnp_support failed: %d\n",
err);
}
}
#endif
return err;
}
Commit Message: USB: check usb_get_extra_descriptor for proper size
When reading an extra descriptor, we need to properly check the minimum
and maximum size allowed, to prevent from invalid data being sent by a
device.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Co-developed-by: Linus Torvalds <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Mathias Payer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-400 | static int usb_enumerate_device_otg(struct usb_device *udev)
{
int err = 0;
#ifdef CONFIG_USB_OTG
/*
* OTG-aware devices on OTG-capable root hubs may be able to use SRP,
* to wake us after we've powered off VBUS; and HNP, switching roles
* "host" to "peripheral". The OTG descriptor helps figure this out.
*/
if (!udev->bus->is_b_host
&& udev->config
&& udev->parent == udev->bus->root_hub) {
struct usb_otg_descriptor *desc = NULL;
struct usb_bus *bus = udev->bus;
unsigned port1 = udev->portnum;
/* descriptor may appear anywhere in config */
err = __usb_get_extra_descriptor(udev->rawdescriptors[0],
le16_to_cpu(udev->config[0].desc.wTotalLength),
USB_DT_OTG, (void **) &desc, sizeof(*desc));
if (err || !(desc->bmAttributes & USB_OTG_HNP))
return 0;
dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n",
(port1 == bus->otg_port) ? "" : "non-");
/* enable HNP before suspend, it's simpler */
if (port1 == bus->otg_port) {
bus->b_hnp_enable = 1;
err = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
USB_REQ_SET_FEATURE, 0,
USB_DEVICE_B_HNP_ENABLE,
0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (err < 0) {
/*
* OTG MESSAGE: report errors here,
* customize to match your product.
*/
dev_err(&udev->dev, "can't set HNP mode: %d\n",
err);
bus->b_hnp_enable = 0;
}
} else if (desc->bLength == sizeof
(struct usb_otg_descriptor)) {
/* Set a_alt_hnp_support for legacy otg device */
err = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
USB_REQ_SET_FEATURE, 0,
USB_DEVICE_A_ALT_HNP_SUPPORT,
0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (err < 0)
dev_err(&udev->dev,
"set a_alt_hnp_support failed: %d\n",
err);
}
}
#endif
return err;
}
| 168,959 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHPAPI char *php_escape_shell_arg(char *str)
{
int x, y = 0, l = strlen(str);
char *cmd;
size_t estimate = (4 * l) + 3;
TSRMLS_FETCH();
cmd = safe_emalloc(4, l, 3); /* worst case */
#ifdef PHP_WIN32
cmd[y++] = '"';
#else
cmd[y++] = '\'';
#endif
for (x = 0; x < l; x++) {
int mb_len = php_mblen(str + x, (l - x));
/* skip non-valid multibyte characters */
if (mb_len < 0) {
continue;
} else if (mb_len > 1) {
memcpy(cmd + y, str + x, mb_len);
y += mb_len;
x += mb_len - 1;
continue;
}
switch (str[x]) {
#ifdef PHP_WIN32
case '"':
case '%':
cmd[y++] = ' ';
break;
#else
case '\'':
cmd[y++] = '\'';
cmd[y++] = '\\';
cmd[y++] = '\'';
#endif
/* fall-through */
default:
cmd[y++] = str[x];
}
}
#ifdef PHP_WIN32
cmd[y++] = '"';
#else
cmd[y++] = '\'';
return cmd;
}
Commit Message:
CWE ID: CWE-78 | PHPAPI char *php_escape_shell_arg(char *str)
{
int x, y = 0, l = strlen(str);
char *cmd;
size_t estimate = (4 * l) + 3;
TSRMLS_FETCH();
cmd = safe_emalloc(4, l, 3); /* worst case */
#ifdef PHP_WIN32
cmd[y++] = '"';
#else
cmd[y++] = '\'';
#endif
for (x = 0; x < l; x++) {
int mb_len = php_mblen(str + x, (l - x));
/* skip non-valid multibyte characters */
if (mb_len < 0) {
continue;
} else if (mb_len > 1) {
memcpy(cmd + y, str + x, mb_len);
y += mb_len;
x += mb_len - 1;
continue;
}
switch (str[x]) {
#ifdef PHP_WIN32
case '"':
case '%':
cmd[y++] = ' ';
break;
#else
case '\'':
cmd[y++] = '\'';
cmd[y++] = '\\';
cmd[y++] = '\'';
#endif
/* fall-through */
default:
cmd[y++] = str[x];
}
}
#ifdef PHP_WIN32
if (y > 0 && '\\' == cmd[y - 1]) {
int k = 0, n = y - 1;
for (; n >= 0 && '\\' == cmd[n]; n--, k++);
if (k % 2) {
cmd[y++] = '\\';
}
}
cmd[y++] = '"';
#else
cmd[y++] = '\'';
return cmd;
}
| 165,302 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_caller_uid (GDBusMethodInvocation *context, gint *uid)
{
PolkitSubject *subject;
PolkitSubject *process;
subject = polkit_system_bus_name_new (g_dbus_method_invocation_get_sender (context));
process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, NULL);
if (!process) {
g_object_unref (subject);
return FALSE;
}
*uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process));
g_object_unref (subject);
g_object_unref (process);
return TRUE;
}
Commit Message:
CWE ID: CWE-362 | get_caller_uid (GDBusMethodInvocation *context, gint *uid)
get_caller_uid (GDBusMethodInvocation *context,
gint *uid)
{
GVariant *reply;
GError *error;
error = NULL;
reply = g_dbus_connection_call_sync (g_dbus_method_invocation_get_connection (context),
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"GetConnectionUnixUser",
g_variant_new ("(s)",
g_dbus_method_invocation_get_sender (context)),
G_VARIANT_TYPE ("(u)"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (reply == NULL) {
g_warning ("Could not talk to message bus to find uid of sender %s: %s",
g_dbus_method_invocation_get_sender (context),
error->message);
g_error_free (error);
return FALSE;
}
g_variant_get (reply, "(u)", uid);
g_variant_unref (reply);
return TRUE;
}
| 165,011 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 4;
fwd_txfm_ref = fht4x4_ref;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 4;
fwd_txfm_ref = fht4x4_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
}
| 174,556 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 http_connect(URLContext *h, const char *path, const char *local_path,
const char *hoststr, const char *auth,
const char *proxyauth, int *new_location)
{
HTTPContext *s = h->priv_data;
int post, err;
char headers[HTTP_HEADERS_SIZE] = "";
char *authstr = NULL, *proxyauthstr = NULL;
int64_t off = s->off;
int len = 0;
const char *method;
int send_expect_100 = 0;
/* send http header */
post = h->flags & AVIO_FLAG_WRITE;
if (s->post_data) {
/* force POST method and disable chunked encoding when
* custom HTTP post data is set */
post = 1;
s->chunked_post = 0;
}
if (s->method)
method = s->method;
else
method = post ? "POST" : "GET";
authstr = ff_http_auth_create_response(&s->auth_state, auth,
local_path, method);
proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
local_path, method);
if (post && !s->post_data) {
send_expect_100 = s->send_expect_100;
/* The user has supplied authentication but we don't know the auth type,
* send Expect: 100-continue to get the 401 response including the
* WWW-Authenticate header, or an 100 continue if no auth actually
* is needed. */
if (auth && *auth &&
s->auth_state.auth_type == HTTP_AUTH_NONE &&
s->http_code != 401)
send_expect_100 = 1;
}
#if FF_API_HTTP_USER_AGENT
if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
s->user_agent = av_strdup(s->user_agent_deprecated);
}
#endif
/* set default headers if needed */
if (!has_header(s->headers, "\r\nUser-Agent: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"User-Agent: %s\r\n", s->user_agent);
if (!has_header(s->headers, "\r\nAccept: "))
len += av_strlcpy(headers + len, "Accept: */*\r\n",
sizeof(headers) - len);
if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Range: bytes=%"PRId64"-", s->off);
if (s->end_off)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"%"PRId64, s->end_off - 1);
len += av_strlcpy(headers + len, "\r\n",
sizeof(headers) - len);
}
if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Expect: 100-continue\r\n");
if (!has_header(s->headers, "\r\nConnection: ")) {
if (s->multiple_requests)
len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
sizeof(headers) - len);
else
len += av_strlcpy(headers + len, "Connection: close\r\n",
sizeof(headers) - len);
}
if (!has_header(s->headers, "\r\nHost: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Host: %s\r\n", hoststr);
if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Content-Length: %d\r\n", s->post_datalen);
if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Content-Type: %s\r\n", s->content_type);
if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
char *cookies = NULL;
if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Cookie: %s\r\n", cookies);
av_free(cookies);
}
}
if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Icy-MetaData: %d\r\n", 1);
/* now add in custom headers */
if (s->headers)
av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
snprintf(s->buffer, sizeof(s->buffer),
"%s %s HTTP/1.1\r\n"
"%s"
"%s"
"%s"
"%s%s"
"\r\n",
method,
path,
post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
headers,
authstr ? authstr : "",
proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
goto done;
if (s->post_data)
if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
goto done;
/* init input buffer */
s->buf_ptr = s->buffer;
s->buf_end = s->buffer;
s->line_count = 0;
s->off = 0;
s->icy_data_read = 0;
s->filesize = -1;
s->willclose = 0;
s->end_chunked_post = 0;
s->end_header = 0;
if (post && !s->post_data && !send_expect_100) {
/* Pretend that it did work. We didn't read any header yet, since
* we've still to send the POST data, but the code calling this
* function will check http_code after we return. */
s->http_code = 200;
err = 0;
goto done;
}
/* wait for header */
err = http_read_header(h, new_location);
if (err < 0)
goto done;
if (*new_location)
s->off = off;
err = (off == s->off) ? 0 : -1;
done:
av_freep(&authstr);
av_freep(&proxyauthstr);
return err;
}
Commit Message: http: make length/offset-related variables unsigned.
Fixes #5992, reported and found by Paul Cher <[email protected]>.
CWE ID: CWE-119 | static int http_connect(URLContext *h, const char *path, const char *local_path,
const char *hoststr, const char *auth,
const char *proxyauth, int *new_location)
{
HTTPContext *s = h->priv_data;
int post, err;
char headers[HTTP_HEADERS_SIZE] = "";
char *authstr = NULL, *proxyauthstr = NULL;
uint64_t off = s->off;
int len = 0;
const char *method;
int send_expect_100 = 0;
/* send http header */
post = h->flags & AVIO_FLAG_WRITE;
if (s->post_data) {
/* force POST method and disable chunked encoding when
* custom HTTP post data is set */
post = 1;
s->chunked_post = 0;
}
if (s->method)
method = s->method;
else
method = post ? "POST" : "GET";
authstr = ff_http_auth_create_response(&s->auth_state, auth,
local_path, method);
proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
local_path, method);
if (post && !s->post_data) {
send_expect_100 = s->send_expect_100;
/* The user has supplied authentication but we don't know the auth type,
* send Expect: 100-continue to get the 401 response including the
* WWW-Authenticate header, or an 100 continue if no auth actually
* is needed. */
if (auth && *auth &&
s->auth_state.auth_type == HTTP_AUTH_NONE &&
s->http_code != 401)
send_expect_100 = 1;
}
#if FF_API_HTTP_USER_AGENT
if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
s->user_agent = av_strdup(s->user_agent_deprecated);
}
#endif
/* set default headers if needed */
if (!has_header(s->headers, "\r\nUser-Agent: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"User-Agent: %s\r\n", s->user_agent);
if (!has_header(s->headers, "\r\nAccept: "))
len += av_strlcpy(headers + len, "Accept: */*\r\n",
sizeof(headers) - len);
if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Range: bytes=%"PRIu64"-", s->off);
if (s->end_off)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"%"PRId64, s->end_off - 1);
len += av_strlcpy(headers + len, "\r\n",
sizeof(headers) - len);
}
if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Expect: 100-continue\r\n");
if (!has_header(s->headers, "\r\nConnection: ")) {
if (s->multiple_requests)
len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
sizeof(headers) - len);
else
len += av_strlcpy(headers + len, "Connection: close\r\n",
sizeof(headers) - len);
}
if (!has_header(s->headers, "\r\nHost: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Host: %s\r\n", hoststr);
if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Content-Length: %d\r\n", s->post_datalen);
if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Content-Type: %s\r\n", s->content_type);
if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
char *cookies = NULL;
if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Cookie: %s\r\n", cookies);
av_free(cookies);
}
}
if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Icy-MetaData: %d\r\n", 1);
/* now add in custom headers */
if (s->headers)
av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
snprintf(s->buffer, sizeof(s->buffer),
"%s %s HTTP/1.1\r\n"
"%s"
"%s"
"%s"
"%s%s"
"\r\n",
method,
path,
post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
headers,
authstr ? authstr : "",
proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
goto done;
if (s->post_data)
if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
goto done;
/* init input buffer */
s->buf_ptr = s->buffer;
s->buf_end = s->buffer;
s->line_count = 0;
s->off = 0;
s->icy_data_read = 0;
s->filesize = UINT64_MAX;
s->willclose = 0;
s->end_chunked_post = 0;
s->end_header = 0;
if (post && !s->post_data && !send_expect_100) {
/* Pretend that it did work. We didn't read any header yet, since
* we've still to send the POST data, but the code calling this
* function will check http_code after we return. */
s->http_code = 200;
err = 0;
goto done;
}
/* wait for header */
err = http_read_header(h, new_location);
if (err < 0)
goto done;
if (*new_location)
s->off = off;
err = (off == s->off) ? 0 : -1;
done:
av_freep(&authstr);
av_freep(&proxyauthstr);
return err;
}
| 168,497 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ecryptfs_privileged_open(struct file **lower_file,
struct dentry *lower_dentry,
struct vfsmount *lower_mnt,
const struct cred *cred)
{
struct ecryptfs_open_req req;
int flags = O_LARGEFILE;
int rc = 0;
init_completion(&req.done);
req.lower_file = lower_file;
req.path.dentry = lower_dentry;
req.path.mnt = lower_mnt;
/* Corresponding dput() and mntput() are done when the
* lower file is fput() when all eCryptfs files for the inode are
* released. */
flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR;
(*lower_file) = dentry_open(&req.path, flags, cred);
if (!IS_ERR(*lower_file))
goto out;
if ((flags & O_ACCMODE) == O_RDONLY) {
rc = PTR_ERR((*lower_file));
goto out;
}
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
rc = -EIO;
mutex_unlock(&ecryptfs_kthread_ctl.mux);
printk(KERN_ERR "%s: We are in the middle of shutting down; "
"aborting privileged request to open lower file\n",
__func__);
goto out;
}
list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);
mutex_unlock(&ecryptfs_kthread_ctl.mux);
wake_up(&ecryptfs_kthread_ctl.wait);
wait_for_completion(&req.done);
if (IS_ERR(*lower_file))
rc = PTR_ERR(*lower_file);
out:
return rc;
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119 | int ecryptfs_privileged_open(struct file **lower_file,
struct dentry *lower_dentry,
struct vfsmount *lower_mnt,
const struct cred *cred)
{
struct ecryptfs_open_req req;
int flags = O_LARGEFILE;
int rc = 0;
init_completion(&req.done);
req.lower_file = lower_file;
req.path.dentry = lower_dentry;
req.path.mnt = lower_mnt;
/* Corresponding dput() and mntput() are done when the
* lower file is fput() when all eCryptfs files for the inode are
* released. */
flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR;
(*lower_file) = dentry_open(&req.path, flags, cred);
if (!IS_ERR(*lower_file))
goto have_file;
if ((flags & O_ACCMODE) == O_RDONLY) {
rc = PTR_ERR((*lower_file));
goto out;
}
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
rc = -EIO;
mutex_unlock(&ecryptfs_kthread_ctl.mux);
printk(KERN_ERR "%s: We are in the middle of shutting down; "
"aborting privileged request to open lower file\n",
__func__);
goto out;
}
list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);
mutex_unlock(&ecryptfs_kthread_ctl.mux);
wake_up(&ecryptfs_kthread_ctl.wait);
wait_for_completion(&req.done);
if (IS_ERR(*lower_file)) {
rc = PTR_ERR(*lower_file);
goto out;
}
have_file:
if ((*lower_file)->f_op->mmap == NULL) {
fput(*lower_file);
*lower_file = NULL;
rc = -EMEDIUMTYPE;
}
out:
return rc;
}
| 167,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: void InspectorNetworkAgent::DidBlockRequest(
ExecutionContext* execution_context,
const ResourceRequest& request,
DocumentLoader* loader,
const FetchInitiatorInfo& initiator_info,
ResourceRequestBlockedReason reason) {
unsigned long identifier = CreateUniqueIdentifier();
WillSendRequestInternal(execution_context, identifier, loader, request,
ResourceResponse(), initiator_info);
String request_id = IdentifiersFactory::RequestId(identifier);
String protocol_reason = BuildBlockedReason(reason);
GetFrontend()->loadingFailed(
request_id, MonotonicallyIncreasingTime(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
String(), false, protocol_reason);
}
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 | void InspectorNetworkAgent::DidBlockRequest(
ExecutionContext* execution_context,
const ResourceRequest& request,
DocumentLoader* loader,
const FetchInitiatorInfo& initiator_info,
ResourceRequestBlockedReason reason,
Resource::Type resource_type) {
unsigned long identifier = CreateUniqueIdentifier();
InspectorPageAgent::ResourceType type =
InspectorPageAgent::ToResourceType(resource_type);
WillSendRequestInternal(execution_context, identifier, loader, request,
ResourceResponse(), initiator_info, type);
String request_id = IdentifiersFactory::RequestId(identifier);
String protocol_reason = BuildBlockedReason(reason);
GetFrontend()->loadingFailed(
request_id, MonotonicallyIncreasingTime(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
String(), false, protocol_reason);
}
| 172,465 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: server_partial_file_request(struct httpd *env, struct client *clt, char *path,
struct stat *st, char *range_str)
{
struct server_config *srv_conf = clt->clt_srv_conf;
struct http_descriptor *resp = clt->clt_descresp;
struct http_descriptor *desc = clt->clt_descreq;
struct media_type *media, multipart_media;
struct range *range;
struct evbuffer *evb = NULL;
size_t content_length;
int code = 500, fd = -1, i, nranges, ret;
uint32_t boundary;
char content_range[64];
const char *errstr = NULL;
/* Ignore range request for methods other than GET */
if (desc->http_method != HTTP_METHOD_GET)
return server_file_request(env, clt, path, st);
if ((range = parse_range(range_str, st->st_size, &nranges)) == NULL) {
code = 416;
(void)snprintf(content_range, sizeof(content_range),
"bytes */%lld", st->st_size);
errstr = content_range;
goto abort;
}
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
media = media_find_config(env, srv_conf, path);
if ((evb = evbuffer_new()) == NULL) {
errstr = "failed to allocate file buffer";
goto abort;
}
if (nranges == 1) {
(void)snprintf(content_range, sizeof(content_range),
"bytes %lld-%lld/%lld", range->start, range->end,
st->st_size);
if (kv_add(&resp->http_headers, "Content-Range",
content_range) == NULL)
goto abort;
content_length = range->end - range->start + 1;
if (buffer_add_range(fd, evb, range) == 0)
goto abort;
} else {
content_length = 0;
boundary = arc4random();
/* Generate a multipart payload of byteranges */
while (nranges--) {
if ((i = evbuffer_add_printf(evb, "\r\n--%ud\r\n",
boundary)) == -1)
goto abort;
content_length += i;
if ((i = evbuffer_add_printf(evb,
"Content-Type: %s/%s\r\n",
media->media_type, media->media_subtype)) == -1)
goto abort;
content_length += i;
if ((i = evbuffer_add_printf(evb,
"Content-Range: bytes %lld-%lld/%lld\r\n\r\n",
range->start, range->end, st->st_size)) == -1)
goto abort;
content_length += i;
if (buffer_add_range(fd, evb, range) == 0)
goto abort;
content_length += range->end - range->start + 1;
range++;
}
if ((i = evbuffer_add_printf(evb, "\r\n--%ud--\r\n",
boundary)) == -1)
goto abort;
content_length += i;
/* prepare multipart/byteranges media type */
(void)strlcpy(multipart_media.media_type, "multipart",
sizeof(multipart_media.media_type));
(void)snprintf(multipart_media.media_subtype,
sizeof(multipart_media.media_subtype),
"byteranges; boundary=%ud", boundary);
media = &multipart_media;
}
close(fd);
fd = -1;
ret = server_response_http(clt, 206, media, content_length,
MINIMUM(time(NULL), st->st_mtim.tv_sec));
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
goto done;
default:
break;
}
if (server_bufferevent_write_buffer(clt, evb) == -1)
goto fail;
bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
if (clt->clt_persist)
clt->clt_toread = TOREAD_HTTP_HEADER;
else
clt->clt_toread = TOREAD_HTTP_NONE;
clt->clt_done = 0;
done:
evbuffer_free(evb);
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (evb != NULL)
evbuffer_free(evb);
if (fd != -1)
close(fd);
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, code, errstr);
return (-1);
}
Commit Message: Reimplement httpd's support for byte ranges.
The previous implementation loaded all the output into a single output
buffer and used its size to determine the Content-Length of the body.
The new implementation calculates the body length first and writes the
individual ranges in an async way using the bufferevent mechanism.
This prevents httpd from using too much memory and applies the
watermark and throttling mechanisms to range requests.
Problem reported by Pierre Kim (pierre.kim.sec at gmail.com)
OK benno@ sunil@
CWE ID: CWE-770 | server_partial_file_request(struct httpd *env, struct client *clt, char *path,
struct stat *st, char *range_str)
{
struct server_config *srv_conf = clt->clt_srv_conf;
struct http_descriptor *resp = clt->clt_descresp;
struct http_descriptor *desc = clt->clt_descreq;
struct media_type *media, multipart_media;
struct range_data *r = &clt->clt_ranges;
struct range *range;
size_t content_length = 0;
int code = 500, fd = -1, i, nranges, ret;
char content_range[64];
const char *errstr = NULL;
/* Ignore range request for methods other than GET */
if (desc->http_method != HTTP_METHOD_GET)
return server_file_request(env, clt, path, st);
if ((nranges = parse_ranges(clt, range_str, st->st_size)) < 1) {
code = 416;
(void)snprintf(content_range, sizeof(content_range),
"bytes */%lld", st->st_size);
errstr = content_range;
goto abort;
}
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
media = media_find_config(env, srv_conf, path);
r->range_media = media;
if (nranges == 1) {
range = &r->range[0];
(void)snprintf(content_range, sizeof(content_range),
"bytes %lld-%lld/%lld", range->start, range->end,
st->st_size);
if (kv_add(&resp->http_headers, "Content-Range",
content_range) == NULL)
goto abort;
range = &r->range[0];
content_length += range->end - range->start + 1;
} else {
/* Add boundary, all parts will be handled by the callback */
arc4random_buf(&clt->clt_boundary, sizeof(clt->clt_boundary));
/* Calculate Content-Length of the complete multipart body */
for (i = 0; i < nranges; i++) {
range = &r->range[i];
/* calculate Content-Length of the complete body */
if ((ret = snprintf(NULL, 0,
"\r\n--%llu\r\n"
"Content-Type: %s/%s\r\n"
"Content-Range: bytes %lld-%lld/%lld\r\n\r\n",
clt->clt_boundary,
media->media_type, media->media_subtype,
range->start, range->end, st->st_size)) < 0)
goto abort;
/* Add data length */
content_length += ret + range->end - range->start + 1;
}
if ((ret = snprintf(NULL, 0, "\r\n--%llu--\r\n",
clt->clt_boundary)) < 0)
goto abort;
content_length += ret;
/* prepare multipart/byteranges media type */
(void)strlcpy(multipart_media.media_type, "multipart",
sizeof(multipart_media.media_type));
(void)snprintf(multipart_media.media_subtype,
sizeof(multipart_media.media_subtype),
"byteranges; boundary=%llu", clt->clt_boundary);
media = &multipart_media;
}
/* Start with first range */
r->range_toread = TOREAD_HTTP_RANGE;
ret = server_response_http(clt, 206, media, content_length,
MINIMUM(time(NULL), st->st_mtim.tv_sec));
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
close(fd);
goto done;
default:
break;
}
clt->clt_fd = fd;
if (clt->clt_srvbev != NULL)
bufferevent_free(clt->clt_srvbev);
clt->clt_srvbev_throttled = 0;
clt->clt_srvbev = bufferevent_new(clt->clt_fd, server_read_httprange,
server_write, server_file_error, clt);
if (clt->clt_srvbev == NULL) {
errstr = "failed to allocate file buffer event";
goto fail;
}
/* Adjust read watermark to the socket output buffer size */
bufferevent_setwatermark(clt->clt_srvbev, EV_READ, 0,
clt->clt_sndbufsiz);
bufferevent_settimeout(clt->clt_srvbev,
srv_conf->timeout.tv_sec, srv_conf->timeout.tv_sec);
bufferevent_enable(clt->clt_srvbev, EV_READ);
bufferevent_disable(clt->clt_bev, EV_READ);
done:
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (fd != -1)
close(fd);
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, code, errstr);
return (-1);
}
| 168,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: static int ivr_read_header(AVFormatContext *s)
{
unsigned tag, type, len, tlen, value;
int i, j, n, count, nb_streams = 0, ret;
uint8_t key[256], val[256];
AVIOContext *pb = s->pb;
AVStream *st;
int64_t pos, offset, temp;
pos = avio_tell(pb);
tag = avio_rl32(pb);
if (tag == MKTAG('.','R','1','M')) {
if (avio_rb16(pb) != 1)
return AVERROR_INVALIDDATA;
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
len = avio_rb32(pb);
avio_skip(pb, len);
avio_skip(pb, 5);
temp = avio_rb64(pb);
while (!avio_feof(pb) && temp) {
offset = temp;
temp = avio_rb64(pb);
}
avio_skip(pb, offset - avio_tell(pb));
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
len = avio_rb32(pb);
avio_skip(pb, len);
if (avio_r8(pb) != 2)
return AVERROR_INVALIDDATA;
avio_skip(pb, 16);
pos = avio_tell(pb);
tag = avio_rl32(pb);
}
if (tag != MKTAG('.','R','E','C'))
return AVERROR_INVALIDDATA;
if (avio_r8(pb) != 0)
return AVERROR_INVALIDDATA;
count = avio_rb32(pb);
for (i = 0; i < count; i++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
type = avio_r8(pb);
tlen = avio_rb32(pb);
avio_get_str(pb, tlen, key, sizeof(key));
len = avio_rb32(pb);
if (type == 5) {
avio_get_str(pb, len, val, sizeof(val));
av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);
} else if (type == 4) {
av_log(s, AV_LOG_DEBUG, "%s = '0x", key);
for (j = 0; j < len; j++)
av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));
av_log(s, AV_LOG_DEBUG, "'\n");
} else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) {
nb_streams = value = avio_rb32(pb);
} else if (len == 4 && type == 3) {
value = avio_rb32(pb);
av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);
} else {
av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);
avio_skip(pb, len);
}
}
for (n = 0; n < nb_streams; n++) {
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
st->priv_data = ff_rm_alloc_rmstream();
if (!st->priv_data)
return AVERROR(ENOMEM);
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
count = avio_rb32(pb);
for (i = 0; i < count; i++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
type = avio_r8(pb);
tlen = avio_rb32(pb);
avio_get_str(pb, tlen, key, sizeof(key));
len = avio_rb32(pb);
if (type == 5) {
avio_get_str(pb, len, val, sizeof(val));
av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);
} else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) {
ret = ffio_ensure_seekback(pb, 4);
if (ret < 0)
return ret;
if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) {
ret = rm_read_multi(s, pb, st, NULL);
} else {
avio_seek(pb, -4, SEEK_CUR);
ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL);
}
if (ret < 0)
return ret;
} else if (type == 4) {
int j;
av_log(s, AV_LOG_DEBUG, "%s = '0x", key);
for (j = 0; j < len; j++)
av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));
av_log(s, AV_LOG_DEBUG, "'\n");
} else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) {
st->duration = avio_rb32(pb);
} else if (len == 4 && type == 3) {
value = avio_rb32(pb);
av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);
} else {
av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);
avio_skip(pb, len);
}
}
}
if (avio_r8(pb) != 6)
return AVERROR_INVALIDDATA;
avio_skip(pb, 12);
avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb));
if (avio_r8(pb) != 8)
return AVERROR_INVALIDDATA;
avio_skip(pb, 8);
return 0;
}
Commit Message: avformat/rmdec: Fix DoS due to lack of eof check
Fixes: loop.ivr
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-834 | static int ivr_read_header(AVFormatContext *s)
{
unsigned tag, type, len, tlen, value;
int i, j, n, count, nb_streams = 0, ret;
uint8_t key[256], val[256];
AVIOContext *pb = s->pb;
AVStream *st;
int64_t pos, offset, temp;
pos = avio_tell(pb);
tag = avio_rl32(pb);
if (tag == MKTAG('.','R','1','M')) {
if (avio_rb16(pb) != 1)
return AVERROR_INVALIDDATA;
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
len = avio_rb32(pb);
avio_skip(pb, len);
avio_skip(pb, 5);
temp = avio_rb64(pb);
while (!avio_feof(pb) && temp) {
offset = temp;
temp = avio_rb64(pb);
}
avio_skip(pb, offset - avio_tell(pb));
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
len = avio_rb32(pb);
avio_skip(pb, len);
if (avio_r8(pb) != 2)
return AVERROR_INVALIDDATA;
avio_skip(pb, 16);
pos = avio_tell(pb);
tag = avio_rl32(pb);
}
if (tag != MKTAG('.','R','E','C'))
return AVERROR_INVALIDDATA;
if (avio_r8(pb) != 0)
return AVERROR_INVALIDDATA;
count = avio_rb32(pb);
for (i = 0; i < count; i++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
type = avio_r8(pb);
tlen = avio_rb32(pb);
avio_get_str(pb, tlen, key, sizeof(key));
len = avio_rb32(pb);
if (type == 5) {
avio_get_str(pb, len, val, sizeof(val));
av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);
} else if (type == 4) {
av_log(s, AV_LOG_DEBUG, "%s = '0x", key);
for (j = 0; j < len; j++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));
}
av_log(s, AV_LOG_DEBUG, "'\n");
} else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) {
nb_streams = value = avio_rb32(pb);
} else if (len == 4 && type == 3) {
value = avio_rb32(pb);
av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);
} else {
av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);
avio_skip(pb, len);
}
}
for (n = 0; n < nb_streams; n++) {
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
st->priv_data = ff_rm_alloc_rmstream();
if (!st->priv_data)
return AVERROR(ENOMEM);
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
count = avio_rb32(pb);
for (i = 0; i < count; i++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
type = avio_r8(pb);
tlen = avio_rb32(pb);
avio_get_str(pb, tlen, key, sizeof(key));
len = avio_rb32(pb);
if (type == 5) {
avio_get_str(pb, len, val, sizeof(val));
av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);
} else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) {
ret = ffio_ensure_seekback(pb, 4);
if (ret < 0)
return ret;
if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) {
ret = rm_read_multi(s, pb, st, NULL);
} else {
avio_seek(pb, -4, SEEK_CUR);
ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL);
}
if (ret < 0)
return ret;
} else if (type == 4) {
int j;
av_log(s, AV_LOG_DEBUG, "%s = '0x", key);
for (j = 0; j < len; j++)
av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));
av_log(s, AV_LOG_DEBUG, "'\n");
} else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) {
st->duration = avio_rb32(pb);
} else if (len == 4 && type == 3) {
value = avio_rb32(pb);
av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);
} else {
av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);
avio_skip(pb, len);
}
}
}
if (avio_r8(pb) != 6)
return AVERROR_INVALIDDATA;
avio_skip(pb, 12);
avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb));
if (avio_r8(pb) != 8)
return AVERROR_INVALIDDATA;
avio_skip(pb, 8);
return 0;
}
| 167,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: void SetupConnectedStreams() {
CallbackRunLoop run_loop(runner());
ASSERT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished());
ASSERT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished());
client_peer_->CreateStreamWithDelegate();
ASSERT_TRUE(client_peer_->stream());
ASSERT_TRUE(client_peer_->stream_delegate());
base::RepeatingCallback<void()> callback = run_loop.CreateCallback();
QuicPeerForTest* server_peer_ptr = server_peer_.get();
MockP2PQuicStreamDelegate* stream_delegate =
new MockP2PQuicStreamDelegate();
P2PQuicStream* server_stream;
EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnStream(_))
.WillOnce(Invoke([&callback, &server_stream,
&stream_delegate](P2PQuicStream* stream) {
stream->SetDelegate(stream_delegate);
server_stream = stream;
callback.Run();
}));
client_peer_->stream()->WriteOrBufferData(kTriggerRemoteStreamPhrase,
/*fin=*/false, nullptr);
run_loop.RunUntilCallbacksFired();
server_peer_ptr->SetStreamAndDelegate(
static_cast<P2PQuicStreamImpl*>(server_stream),
std::unique_ptr<MockP2PQuicStreamDelegate>(stream_delegate));
ASSERT_TRUE(client_peer_->stream());
ASSERT_TRUE(client_peer_->stream_delegate());
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284 | void SetupConnectedStreams() {
CallbackRunLoop run_loop(runner());
ASSERT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished());
ASSERT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished());
client_peer_->CreateStreamWithDelegate();
ASSERT_TRUE(client_peer_->stream());
ASSERT_TRUE(client_peer_->stream_delegate());
base::RepeatingCallback<void()> callback = run_loop.CreateCallback();
QuicPeerForTest* server_peer_ptr = server_peer_.get();
MockP2PQuicStreamDelegate* stream_delegate =
new MockP2PQuicStreamDelegate();
P2PQuicStream* server_stream;
EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnStream(_))
.WillOnce(Invoke([&callback, &server_stream,
&stream_delegate](P2PQuicStream* stream) {
stream->SetDelegate(stream_delegate);
server_stream = stream;
callback.Run();
}));
client_peer_->stream()->WriteData(
std::vector<uint8_t>(kTriggerRemoteStreamPhrase.begin(),
kTriggerRemoteStreamPhrase.end()),
/*fin=*/false);
run_loop.RunUntilCallbacksFired();
server_peer_ptr->SetStreamAndDelegate(
static_cast<P2PQuicStreamImpl*>(server_stream),
std::unique_ptr<MockP2PQuicStreamDelegate>(stream_delegate));
ASSERT_TRUE(client_peer_->stream());
ASSERT_TRUE(client_peer_->stream_delegate());
}
| 172,268 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: kdc_process_s4u2proxy_req(kdc_realm_t *kdc_active_realm,
krb5_kdc_req *request,
const krb5_enc_tkt_part *t2enc,
const krb5_db_entry *server,
krb5_const_principal server_princ,
krb5_const_principal proxy_princ,
const char **status)
{
krb5_error_code errcode;
/*
* Constrained delegation is mutually exclusive with renew/forward/etc.
* We can assert from this check that the header ticket was a TGT, as
* that is validated previously in validate_tgs_request().
*/
if (request->kdc_options & (NON_TGT_OPTION | KDC_OPT_ENC_TKT_IN_SKEY)) {
return KRB5KDC_ERR_BADOPTION;
}
/* Ensure that evidence ticket server matches TGT client */
if (!krb5_principal_compare(kdc_context,
server->princ, /* after canon */
server_princ)) {
return KRB5KDC_ERR_SERVER_NOMATCH;
}
if (!isflagset(t2enc->flags, TKT_FLG_FORWARDABLE)) {
*status = "EVIDENCE_TKT_NOT_FORWARDABLE";
return KRB5_TKT_NOT_FORWARDABLE;
}
/* Backend policy check */
errcode = check_allowed_to_delegate_to(kdc_context,
t2enc->client,
server,
proxy_princ);
if (errcode) {
*status = "NOT_ALLOWED_TO_DELEGATE";
return errcode;
}
return 0;
}
Commit Message: Prevent KDC unset status assertion failures
Assign status values if S4U2Self padata fails to decode, if an
S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request
uses an evidence ticket which does not match the canonicalized request
server principal name. Reported by Samuel Cabrero.
If a status value is not assigned during KDC processing, default to
"UNKNOWN_REASON" rather than failing an assertion. This change will
prevent future denial of service bugs due to similar mistakes, and
will allow us to omit assigning status values for unlikely errors such
as small memory allocation failures.
CVE-2017-11368:
In MIT krb5 1.7 and later, an authenticated attacker can cause an
assertion failure in krb5kdc by sending an invalid S4U2Self or
S4U2Proxy request.
CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C
ticket: 8599 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-617 | kdc_process_s4u2proxy_req(kdc_realm_t *kdc_active_realm,
krb5_kdc_req *request,
const krb5_enc_tkt_part *t2enc,
const krb5_db_entry *server,
krb5_const_principal server_princ,
krb5_const_principal proxy_princ,
const char **status)
{
krb5_error_code errcode;
/*
* Constrained delegation is mutually exclusive with renew/forward/etc.
* We can assert from this check that the header ticket was a TGT, as
* that is validated previously in validate_tgs_request().
*/
if (request->kdc_options & (NON_TGT_OPTION | KDC_OPT_ENC_TKT_IN_SKEY)) {
*status = "INVALID_S4U2PROXY_OPTIONS";
return KRB5KDC_ERR_BADOPTION;
}
/* Ensure that evidence ticket server matches TGT client */
if (!krb5_principal_compare(kdc_context,
server->princ, /* after canon */
server_princ)) {
*status = "EVIDENCE_TICKET_MISMATCH";
return KRB5KDC_ERR_SERVER_NOMATCH;
}
if (!isflagset(t2enc->flags, TKT_FLG_FORWARDABLE)) {
*status = "EVIDENCE_TKT_NOT_FORWARDABLE";
return KRB5_TKT_NOT_FORWARDABLE;
}
/* Backend policy check */
errcode = check_allowed_to_delegate_to(kdc_context,
t2enc->client,
server,
proxy_princ);
if (errcode) {
*status = "NOT_ALLOWED_TO_DELEGATE";
return errcode;
}
return 0;
}
| 168,042 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ps_sd *ps_sd_new(ps_mm *data, const char *key)
{
php_uint32 hv, slot;
ps_sd *sd;
int keylen;
keylen = strlen(key);
sd = mm_malloc(data->mm, sizeof(ps_sd) + keylen);
if (!sd) {
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mm_malloc failed, avail %d, err %s", mm_available(data->mm), mm_error());
return NULL;
}
hv = ps_sd_hash(key, keylen);
slot = hv & data->hash_max;
sd->ctime = 0;
sd->hv = hv;
sd->data = NULL;
sd->alloclen = sd->datalen = 0;
memcpy(sd->key, key, keylen + 1);
sd->next = data->hash[slot];
data->hash[slot] = sd;
data->hash_cnt++;
if (!sd->next) {
if (data->hash_cnt >= data->hash_max) {
hash_split(data);
}
}
ps_mm_debug(("inserting %s(%p) into slot %d\n", key, sd, slot));
return sd;
}
Commit Message:
CWE ID: CWE-264 | static ps_sd *ps_sd_new(ps_mm *data, const char *key)
{
php_uint32 hv, slot;
ps_sd *sd;
int keylen;
keylen = strlen(key);
sd = mm_malloc(data->mm, sizeof(ps_sd) + keylen);
if (!sd) {
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mm_malloc failed, avail %ld, err %s", mm_available(data->mm), mm_error());
return NULL;
}
hv = ps_sd_hash(key, keylen);
slot = hv & data->hash_max;
sd->ctime = 0;
sd->hv = hv;
sd->data = NULL;
sd->alloclen = sd->datalen = 0;
memcpy(sd->key, key, keylen + 1);
sd->next = data->hash[slot];
data->hash[slot] = sd;
data->hash_cnt++;
if (!sd->next) {
if (data->hash_cnt >= data->hash_max) {
hash_split(data);
}
}
ps_mm_debug(("inserting %s(%p) into slot %d\n", key, sd, slot));
return sd;
}
| 164,872 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Track::ParseContentEncodingsEntry(long long start, long long size) {
IMkvReader* const pReader = m_pSegment->m_pReader;
assert(pReader);
long long pos = start;
const long long stop = start + size;
int count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x2240) // ContentEncoding ID
++count;
pos += size; // consume payload
assert(pos <= stop);
}
if (count <= 0)
return -1;
content_encoding_entries_ = new (std::nothrow) ContentEncoding* [count];
if (!content_encoding_entries_)
return -1;
content_encoding_entries_end_ = content_encoding_entries_;
pos = start;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x2240) { // ContentEncoding ID
ContentEncoding* const content_encoding =
new (std::nothrow) ContentEncoding();
if (!content_encoding)
return -1;
status = content_encoding->ParseContentEncodingEntry(pos, size, pReader);
if (status) {
delete content_encoding;
return status;
}
*content_encoding_entries_end_++ = content_encoding;
}
pos += size; // consume payload
assert(pos <= stop);
}
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 Track::ParseContentEncodingsEntry(long long start, long long size) {
IMkvReader* const pReader = m_pSegment->m_pReader;
assert(pReader);
long long pos = start;
const long long stop = start + size;
int count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x2240) // ContentEncoding ID
++count;
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (count <= 0)
return -1;
content_encoding_entries_ = new (std::nothrow) ContentEncoding*[count];
if (!content_encoding_entries_)
return -1;
content_encoding_entries_end_ = content_encoding_entries_;
pos = start;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x2240) { // ContentEncoding ID
ContentEncoding* const content_encoding =
new (std::nothrow) ContentEncoding();
if (!content_encoding)
return -1;
status = content_encoding->ParseContentEncodingEntry(pos, size, pReader);
if (status) {
delete content_encoding;
return status;
}
*content_encoding_entries_end_++ = content_encoding;
}
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,851 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: UserInitiatedInfo CreateUserInitiatedInfo(
content::NavigationHandle* navigation_handle,
PageLoadTracker* committed_load) {
if (!navigation_handle->IsRendererInitiated())
return UserInitiatedInfo::BrowserInitiated();
return UserInitiatedInfo::RenderInitiated(
navigation_handle->HasUserGesture());
}
Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation.
Also refactor UkmPageLoadMetricsObserver to use this new boolean to
report the user initiated metric in RecordPageLoadExtraInfoMetrics, so
that it works correctly in the case when the page load failed.
Bug: 925104
Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff
Reviewed-on: https://chromium-review.googlesource.com/c/1450460
Commit-Queue: Annie Sullivan <[email protected]>
Reviewed-by: Bryan McQuade <[email protected]>
Cr-Commit-Position: refs/heads/master@{#630870}
CWE ID: CWE-79 | UserInitiatedInfo CreateUserInitiatedInfo(
content::NavigationHandle* navigation_handle,
PageLoadTracker* committed_load) {
if (!navigation_handle->IsRendererInitiated())
return UserInitiatedInfo::BrowserInitiated();
return UserInitiatedInfo::RenderInitiated(
navigation_handle->HasUserGesture(),
!navigation_handle->NavigationInputStart().is_null());
}
| 172,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 hi3660_stub_clk_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *res;
unsigned int i;
int ret;
/* Use mailbox client without blocking */
stub_clk_chan.cl.dev = dev;
stub_clk_chan.cl.tx_done = NULL;
stub_clk_chan.cl.tx_block = false;
stub_clk_chan.cl.knows_txdone = false;
/* Allocate mailbox channel */
stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);
if (IS_ERR(stub_clk_chan.mbox))
return PTR_ERR(stub_clk_chan.mbox);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
freq_reg = devm_ioremap(dev, res->start, resource_size(res));
if (!freq_reg)
return -ENOMEM;
freq_reg += HI3660_STUB_CLOCK_DATA;
for (i = 0; i < HI3660_CLK_STUB_NUM; i++) {
ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);
if (ret)
return ret;
}
return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,
hi3660_stub_clks);
}
Commit Message: clk: hisilicon: hi3660:Fix potential NULL dereference in hi3660_stub_clk_probe()
platform_get_resource() may return NULL, add proper check to
avoid potential NULL dereferencing.
This is detected by Coccinelle semantic patch.
@@
expression pdev, res, n, t, e, e1, e2;
@@
res = platform_get_resource(pdev, t, n);
+ if (!res)
+ return -EINVAL;
... when != res == NULL
e = devm_ioremap(e1, res->start, e2);
Fixes: 4f16f7ff3bc0 ("clk: hisilicon: Add support for Hi3660 stub clocks")
Signed-off-by: Wei Yongjun <[email protected]>
Signed-off-by: Stephen Boyd <[email protected]>
CWE ID: CWE-476 | static int hi3660_stub_clk_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *res;
unsigned int i;
int ret;
/* Use mailbox client without blocking */
stub_clk_chan.cl.dev = dev;
stub_clk_chan.cl.tx_done = NULL;
stub_clk_chan.cl.tx_block = false;
stub_clk_chan.cl.knows_txdone = false;
/* Allocate mailbox channel */
stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);
if (IS_ERR(stub_clk_chan.mbox))
return PTR_ERR(stub_clk_chan.mbox);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -EINVAL;
freq_reg = devm_ioremap(dev, res->start, resource_size(res));
if (!freq_reg)
return -ENOMEM;
freq_reg += HI3660_STUB_CLOCK_DATA;
for (i = 0; i < HI3660_CLK_STUB_NUM; i++) {
ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);
if (ret)
return ret;
}
return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,
hi3660_stub_clks);
}
| 169,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 socket_write(const socket_t *socket, const void *buf, size_t count) {
assert(socket != NULL);
assert(buf != NULL);
return send(socket->fd, buf, count, MSG_DONTWAIT);
}
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 | ssize_t socket_write(const socket_t *socket, const void *buf, size_t count) {
assert(socket != NULL);
assert(buf != NULL);
return TEMP_FAILURE_RETRY(send(socket->fd, buf, count, MSG_DONTWAIT));
}
| 173,487 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebRuntimeFeatures::enableSpeechSynthesis(bool enable)
{
RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable);
}
Commit Message: Remove SpeechSynthesis runtime flag (status=stable)
BUG=402536
Review URL: https://codereview.chromium.org/482273005
git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-94 | void WebRuntimeFeatures::enableSpeechSynthesis(bool enable)
| 171,458 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
if (mHeadersDecoded) {
drainAllOutputBuffers(false /* eos */);
}
H264SwDecRet ret = H264SWDEC_PIC_RDY;
bool portWillReset = false;
while ((mEOSStatus != INPUT_DATA_AVAILABLE || !inQueue.empty())
&& outQueue.size() == kNumOutputBuffers) {
if (mEOSStatus == INPUT_EOS_SEEN) {
drainAllOutputBuffers(true /* eos */);
return;
}
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
++mPicId;
OMX_BUFFERHEADERTYPE *header = new OMX_BUFFERHEADERTYPE;
memset(header, 0, sizeof(OMX_BUFFERHEADERTYPE));
header->nTimeStamp = inHeader->nTimeStamp;
header->nFlags = inHeader->nFlags;
if (header->nFlags & OMX_BUFFERFLAG_EOS) {
mEOSStatus = INPUT_EOS_SEEN;
}
mPicToHeaderMap.add(mPicId, header);
inQueue.erase(inQueue.begin());
H264SwDecInput inPicture;
H264SwDecOutput outPicture;
memset(&inPicture, 0, sizeof(inPicture));
inPicture.dataLen = inHeader->nFilledLen;
inPicture.pStream = inHeader->pBuffer + inHeader->nOffset;
inPicture.picId = mPicId;
inPicture.intraConcealmentMethod = 1;
H264SwDecPicture decodedPicture;
while (inPicture.dataLen > 0) {
ret = H264SwDecDecode(mHandle, &inPicture, &outPicture);
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY ||
ret == H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY) {
inPicture.dataLen -= (u32)(outPicture.pStrmCurrPos - inPicture.pStream);
inPicture.pStream = outPicture.pStrmCurrPos;
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY) {
mHeadersDecoded = true;
H264SwDecInfo decoderInfo;
CHECK(H264SwDecGetInfo(mHandle, &decoderInfo) == H264SWDEC_OK);
SoftVideoDecoderOMXComponent::CropSettingsMode cropSettingsMode =
handleCropParams(decoderInfo);
handlePortSettingsChange(
&portWillReset, decoderInfo.picWidth, decoderInfo.picHeight,
cropSettingsMode);
}
} else {
if (portWillReset) {
if (H264SwDecNextPicture(mHandle, &decodedPicture, 0)
== H264SWDEC_PIC_RDY) {
saveFirstOutputBuffer(
decodedPicture.picId,
(uint8_t *)decodedPicture.pOutputPicture);
}
}
inPicture.dataLen = 0;
if (ret < 0) {
ALOGE("Decoder failed: %d", ret);
notify(OMX_EventError, OMX_ErrorUndefined,
ERROR_MALFORMED, NULL);
mSignalledError = true;
return;
}
}
}
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
if (portWillReset) {
return;
}
if (mFirstPicture && !outQueue.empty()) {
drainOneOutputBuffer(mFirstPictureId, mFirstPicture);
delete[] mFirstPicture;
mFirstPicture = NULL;
mFirstPictureId = -1;
}
drainAllOutputBuffers(false /* eos */);
}
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
CWE ID: CWE-20 | void SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
if (mHeadersDecoded) {
drainAllOutputBuffers(false /* eos */);
}
H264SwDecRet ret = H264SWDEC_PIC_RDY;
bool portWillReset = false;
while ((mEOSStatus != INPUT_DATA_AVAILABLE || !inQueue.empty())
&& outQueue.size() == kNumOutputBuffers) {
if (mEOSStatus == INPUT_EOS_SEEN) {
drainAllOutputBuffers(true /* eos */);
return;
}
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
++mPicId;
OMX_BUFFERHEADERTYPE *header = new OMX_BUFFERHEADERTYPE;
memset(header, 0, sizeof(OMX_BUFFERHEADERTYPE));
header->nTimeStamp = inHeader->nTimeStamp;
header->nFlags = inHeader->nFlags;
if (header->nFlags & OMX_BUFFERFLAG_EOS) {
mEOSStatus = INPUT_EOS_SEEN;
}
mPicToHeaderMap.add(mPicId, header);
inQueue.erase(inQueue.begin());
H264SwDecInput inPicture;
H264SwDecOutput outPicture;
memset(&inPicture, 0, sizeof(inPicture));
inPicture.dataLen = inHeader->nFilledLen;
inPicture.pStream = inHeader->pBuffer + inHeader->nOffset;
inPicture.picId = mPicId;
inPicture.intraConcealmentMethod = 1;
H264SwDecPicture decodedPicture;
while (inPicture.dataLen > 0) {
ret = H264SwDecDecode(mHandle, &inPicture, &outPicture);
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY ||
ret == H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY) {
inPicture.dataLen -= (u32)(outPicture.pStrmCurrPos - inPicture.pStream);
inPicture.pStream = outPicture.pStrmCurrPos;
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY) {
mHeadersDecoded = true;
H264SwDecInfo decoderInfo;
CHECK(H264SwDecGetInfo(mHandle, &decoderInfo) == H264SWDEC_OK);
SoftVideoDecoderOMXComponent::CropSettingsMode cropSettingsMode =
handleCropParams(decoderInfo);
handlePortSettingsChange(
&portWillReset, decoderInfo.picWidth, decoderInfo.picHeight,
cropSettingsMode);
}
} else {
if (portWillReset) {
if (H264SwDecNextPicture(mHandle, &decodedPicture, 0)
== H264SWDEC_PIC_RDY) {
saveFirstOutputBuffer(
decodedPicture.picId,
(uint8_t *)decodedPicture.pOutputPicture);
}
}
inPicture.dataLen = 0;
if (ret < 0) {
ALOGE("Decoder failed: %d", ret);
notify(OMX_EventError, OMX_ErrorUndefined,
ERROR_MALFORMED, NULL);
mSignalledError = true;
return;
}
}
}
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
if (portWillReset) {
return;
}
if (mFirstPicture && !outQueue.empty()) {
if (!drainOneOutputBuffer(mFirstPictureId, mFirstPicture)) {
ALOGE("Drain failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
delete[] mFirstPicture;
mFirstPicture = NULL;
mFirstPictureId = -1;
}
drainAllOutputBuffers(false /* eos */);
}
}
| 174,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PopupContainer::showInRect(const IntRect& r, FrameView* v, int index)
{
listBox()->setBaseWidth(max(r.width() - kBorderSize * 2, 0));
listBox()->updateFromElement();
IntPoint location = v->contentsToWindow(r.location());
location.move(0, r.height());
m_originalFrameRect = IntRect(location, r.size());
setFrameRect(m_originalFrameRect);
showPopup(v);
}
Commit Message: [REGRESSION] Refreshed autofill popup renders garbage
https://bugs.webkit.org/show_bug.cgi?id=83255
http://code.google.com/p/chromium/issues/detail?id=118374
The code used to update only the PopupContainer coordinates as if they were the coordinates relative
to the root view. Instead, a WebWidget positioned relative to the screen origin holds the PopupContainer,
so it is the WebWidget that should be positioned in PopupContainer::refresh(), and the PopupContainer's
location should be (0, 0) (and their sizes should always be equal).
Reviewed by Kent Tamura.
No new tests, as the popup appearance is not testable in WebKit.
* platform/chromium/PopupContainer.cpp:
(WebCore::PopupContainer::layoutAndCalculateWidgetRect): Variable renamed.
(WebCore::PopupContainer::showPopup): Use m_originalFrameRect rather than frameRect()
for passing into chromeClient.
(WebCore::PopupContainer::showInRect): Set up the correct frameRect() for the container.
(WebCore::PopupContainer::refresh): Resize the container and position the WebWidget correctly.
* platform/chromium/PopupContainer.h:
(PopupContainer):
git-svn-id: svn://svn.chromium.org/blink/trunk@113418 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void PopupContainer::showInRect(const IntRect& r, FrameView* v, int index)
{
listBox()->setBaseWidth(max(r.width() - kBorderSize * 2, 0));
listBox()->updateFromElement();
IntPoint location = v->contentsToWindow(r.location());
location.move(0, r.height());
m_originalFrameRect = IntRect(location, r.size());
// Position at (0, 0) since the frameRect().location() is relative to the parent WebWidget.
setFrameRect(IntRect(IntPoint(), r.size()));
showPopup(v);
}
| 171,028 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LoginHtmlDialog::GetDialogSize(gfx::Size* size) const {
size->SetSize(width_, height_);
}
Commit Message: cros: The next 100 clang plugin errors.
BUG=none
TEST=none
TBR=dpolukhin
Review URL: http://codereview.chromium.org/7022008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85418 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void LoginHtmlDialog::GetDialogSize(gfx::Size* size) const {
bool LoginHtmlDialog::ShouldShowDialogTitle() const {
return true;
}
void LoginHtmlDialog::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type.value == NotificationType::LOAD_COMPLETED_MAIN_FRAME);
if (bubble_frame_view_)
bubble_frame_view_->StopThrobber();
}
| 170,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: views::View* AutofillDialogViews::CreateFootnoteView() {
footnote_view_ = new LayoutPropagationView();
footnote_view_->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical,
kDialogEdgePadding,
kDialogEdgePadding,
0));
footnote_view_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
footnote_view_->set_background(
views::Background::CreateSolidBackground(kShadingColor));
legal_document_view_ = new views::StyledLabel(base::string16(), this);
footnote_view_->AddChildView(legal_document_view_);
footnote_view_->SetVisible(false);
return footnote_view_;
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20 | views::View* AutofillDialogViews::CreateFootnoteView() {
footnote_view_ = new LayoutPropagationView();
footnote_view_->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical,
kDialogEdgePadding,
kDialogEdgePadding,
0));
footnote_view_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
footnote_view_->set_background(
views::Background::CreateSolidBackground(kLightShadingColor));
legal_document_view_ = new views::StyledLabel(base::string16(), this);
footnote_view_->AddChildView(legal_document_view_);
footnote_view_->SetVisible(false);
return footnote_view_;
}
| 171,139 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
__uint128_t tmp;
void *valp = &tmp;
u64 off;
int err = 0;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (validate_core_offset(reg))
return -EINVAL;
if (KVM_REG_SIZE(reg->id) > sizeof(tmp))
return -EINVAL;
if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) {
err = -EFAULT;
goto out;
}
if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) {
u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK;
switch (mode) {
case PSR_AA32_MODE_USR:
case PSR_AA32_MODE_FIQ:
case PSR_AA32_MODE_IRQ:
case PSR_AA32_MODE_SVC:
case PSR_AA32_MODE_ABT:
case PSR_AA32_MODE_UND:
case PSR_MODE_EL0t:
case PSR_MODE_EL1t:
case PSR_MODE_EL1h:
break;
default:
err = -EINVAL;
goto out;
}
}
memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id));
out:
return err;
}
Commit Message: arm64: KVM: Sanitize PSTATE.M when being set from userspace
Not all execution modes are valid for a guest, and some of them
depend on what the HW actually supports. Let's verify that what
userspace provides is compatible with both the VM settings and
the HW capabilities.
Cc: <[email protected]>
Fixes: 0d854a60b1d7 ("arm64: KVM: enable initialization of a 32bit vcpu")
Reviewed-by: Christoffer Dall <[email protected]>
Reviewed-by: Mark Rutland <[email protected]>
Reviewed-by: Dave Martin <[email protected]>
Signed-off-by: Marc Zyngier <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
CWE ID: CWE-20 | static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
__uint128_t tmp;
void *valp = &tmp;
u64 off;
int err = 0;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (validate_core_offset(reg))
return -EINVAL;
if (KVM_REG_SIZE(reg->id) > sizeof(tmp))
return -EINVAL;
if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) {
err = -EFAULT;
goto out;
}
if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) {
u64 mode = (*(u64 *)valp) & PSR_AA32_MODE_MASK;
switch (mode) {
case PSR_AA32_MODE_USR:
if (!system_supports_32bit_el0())
return -EINVAL;
break;
case PSR_AA32_MODE_FIQ:
case PSR_AA32_MODE_IRQ:
case PSR_AA32_MODE_SVC:
case PSR_AA32_MODE_ABT:
case PSR_AA32_MODE_UND:
if (!vcpu_el1_is_32bit(vcpu))
return -EINVAL;
break;
case PSR_MODE_EL0t:
case PSR_MODE_EL1t:
case PSR_MODE_EL1h:
if (vcpu_el1_is_32bit(vcpu))
return -EINVAL;
break;
default:
err = -EINVAL;
goto out;
}
}
memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id));
out:
return err;
}
| 170,159 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserContextDestroyer::RenderProcessHostDestroyed(
content::RenderProcessHost* host) {
DCHECK_GT(pending_hosts_, 0U);
if (--pending_hosts_ != 0) {
return;
}
//// static
if (content::RenderProcessHost::run_renderer_in_process()) {
FinishDestroyContext();
} else {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&BrowserContextDestroyer::FinishDestroyContext,
base::Unretained(this)));
}
}
Commit Message:
CWE ID: CWE-20 | void BrowserContextDestroyer::RenderProcessHostDestroyed(
content::RenderProcessHost* host) {
DCHECK_GT(pending_host_ids_.size(), 0U);
size_t erased = pending_host_ids_.erase(host->GetID());
DCHECK_GT(erased, 0U);
MaybeScheduleFinishDestroyContext(host);
}
//// static
void BrowserContextDestroyer::DestroyContext(
std::unique_ptr<BrowserContext> context) {
bool has_live_otr_context = false;
uint32_t otr_contexts_pending_deletion = 0;
if (!context->IsOffTheRecord()) {
// If |context| is not an OTR BrowserContext, we need to keep track of how
// many OTR BrowserContexts that were owned by it are scheduled for deletion
// but still exist, as |context| must outlive these
for (auto* destroyer : g_contexts_pending_deletion.Get()) {
if (destroyer->context_->IsOffTheRecord() &&
destroyer->context_->GetOriginalContext() == context.get()) {
++otr_contexts_pending_deletion;
}
}
// If |context| is not an OTR BrowserContext but currently owns a live OTR
// BrowserContext, then we have to outlive that
has_live_otr_context = context->HasOffTheRecordContext();
} else {
// If |context| is an OTR BrowserContext and its owner has already been
// scheduled for deletion, then we need to prevent the owner from being
// deleted until after |context|
BrowserContextDestroyer* orig_destroyer =
GetForContext(context->GetOriginalContext());
if (orig_destroyer) {
CHECK(!orig_destroyer->finish_destroy_scheduled_);
++orig_destroyer->otr_contexts_pending_deletion_;
}
}
// Get all of the live RenderProcessHosts that are using |context|
std::set<content::RenderProcessHost*> hosts =
GetHostsForContext(context.get());
content::BrowserContext::NotifyWillBeDestroyed(context.get());
// |hosts| might not be empty if the application released its BrowserContext
// too early, or if |context| is an OTR context or this application is single
// process
if (!hosts.empty() ||
otr_contexts_pending_deletion > 0 ||
has_live_otr_context) {
// |context| is not safe to delete yet
new BrowserContextDestroyer(std::move(context),
hosts,
otr_contexts_pending_deletion);
}
}
| 165,421 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebGL2RenderingContextBase::bindSampler(GLuint unit,
WebGLSampler* sampler) {
if (isContextLost())
return;
bool deleted;
if (!CheckObjectToBeBound("bindSampler", sampler, deleted))
return;
if (deleted) {
SynthesizeGLError(GL_INVALID_OPERATION, "bindSampler",
"attempted to bind a deleted sampler");
return;
}
if (unit >= sampler_units_.size()) {
SynthesizeGLError(GL_INVALID_VALUE, "bindSampler",
"texture unit out of range");
return;
}
sampler_units_[unit] = sampler;
ContextGL()->BindSampler(unit, ObjectOrZero(sampler));
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | void WebGL2RenderingContextBase::bindSampler(GLuint unit,
WebGLSampler* sampler) {
bool deleted;
if (!CheckObjectToBeBound("bindSampler", sampler, deleted))
return;
if (deleted) {
SynthesizeGLError(GL_INVALID_OPERATION, "bindSampler",
"attempted to bind a deleted sampler");
return;
}
if (unit >= sampler_units_.size()) {
SynthesizeGLError(GL_INVALID_VALUE, "bindSampler",
"texture unit out of range");
return;
}
sampler_units_[unit] = sampler;
ContextGL()->BindSampler(unit, ObjectOrZero(sampler));
}
| 173,122 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Document::open()
{
ASSERT(!importLoader());
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader().provisionalDocumentLoader())
m_frame->loader().stopAllLoaders();
}
removeAllEventListenersRecursively();
implicitOpen(ForceSynchronousParsing);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (m_frame)
m_frame->loader().didExplicitOpen();
if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
m_loadEventProgress = LoadEventNotRun;
}
Commit Message: Don't change Document load progress in any page dismissal events.
This can confuse the logic for blocking modal dialogs.
BUG=536652
Review URL: https://codereview.chromium.org/1373113002
Cr-Commit-Position: refs/heads/master@{#351419}
CWE ID: CWE-20 | void Document::open()
{
ASSERT(!importLoader());
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader().provisionalDocumentLoader())
m_frame->loader().stopAllLoaders();
}
removeAllEventListenersRecursively();
implicitOpen(ForceSynchronousParsing);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (m_frame)
m_frame->loader().didExplicitOpen();
if (m_loadEventProgress != LoadEventInProgress && pageDismissalEventBeingDispatched() == NoDismissal)
m_loadEventProgress = LoadEventNotRun;
}
| 171,783 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.