instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
{
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
l_strnstart(netdissect_options *ndo, const char *tstr1, u_int tl1,
const char *str2, u_int l2)
{
if (!ND_TTEST2(*str2, tl1)) {
/*
* We don't have tl1 bytes worth of captured data
* for the string, so we can't check for this
* string.
*/
return 0;
}
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
| 167,885
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DrawingBuffer::Initialize(const IntSize& size, bool use_multisampling) {
ScopedStateRestorer scoped_state_restorer(this);
if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) {
return false;
}
gl_->GetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size_);
int max_sample_count = 0;
anti_aliasing_mode_ = kNone;
if (use_multisampling) {
gl_->GetIntegerv(GL_MAX_SAMPLES_ANGLE, &max_sample_count);
anti_aliasing_mode_ = kMSAAExplicitResolve;
if (extensions_util_->SupportsExtension(
"GL_EXT_multisampled_render_to_texture")) {
anti_aliasing_mode_ = kMSAAImplicitResolve;
} else if (extensions_util_->SupportsExtension(
"GL_CHROMIUM_screen_space_antialiasing")) {
anti_aliasing_mode_ = kScreenSpaceAntialiasing;
}
}
storage_texture_supported_ =
(web_gl_version_ > kWebGL1 ||
extensions_util_->SupportsExtension("GL_EXT_texture_storage")) &&
anti_aliasing_mode_ == kScreenSpaceAntialiasing;
sample_count_ = std::min(4, max_sample_count);
state_restorer_->SetFramebufferBindingDirty();
gl_->GenFramebuffers(1, &fbo_);
gl_->BindFramebuffer(GL_FRAMEBUFFER, fbo_);
if (WantExplicitResolve()) {
gl_->GenFramebuffers(1, &multisample_fbo_);
gl_->BindFramebuffer(GL_FRAMEBUFFER, multisample_fbo_);
gl_->GenRenderbuffers(1, &multisample_renderbuffer_);
}
if (!ResizeFramebufferInternal(size))
return false;
if (depth_stencil_buffer_) {
DCHECK(WantDepthOrStencil());
has_implicit_stencil_buffer_ = !want_stencil_;
}
if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) {
return false;
}
return true;
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
R=kbr@chromium.org,piman@chromium.org
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <piman@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Commit-Queue: Zhenyao Mo <zmo@chromium.org>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
|
bool DrawingBuffer::Initialize(const IntSize& size, bool use_multisampling) {
ScopedStateRestorer scoped_state_restorer(this);
if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) {
return false;
}
gl_->GetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size_);
int max_sample_count = 0;
anti_aliasing_mode_ = kNone;
if (use_multisampling) {
gl_->GetIntegerv(GL_MAX_SAMPLES_ANGLE, &max_sample_count);
anti_aliasing_mode_ = kMSAAExplicitResolve;
if (extensions_util_->SupportsExtension(
"GL_EXT_multisampled_render_to_texture")) {
anti_aliasing_mode_ = kMSAAImplicitResolve;
} else if (extensions_util_->SupportsExtension(
"GL_CHROMIUM_screen_space_antialiasing")) {
anti_aliasing_mode_ = kScreenSpaceAntialiasing;
}
}
storage_texture_supported_ =
(webgl_version_ > kWebGL1 ||
extensions_util_->SupportsExtension("GL_EXT_texture_storage")) &&
anti_aliasing_mode_ == kScreenSpaceAntialiasing;
sample_count_ = std::min(4, max_sample_count);
state_restorer_->SetFramebufferBindingDirty();
gl_->GenFramebuffers(1, &fbo_);
gl_->BindFramebuffer(GL_FRAMEBUFFER, fbo_);
if (WantExplicitResolve()) {
gl_->GenFramebuffers(1, &multisample_fbo_);
gl_->BindFramebuffer(GL_FRAMEBUFFER, multisample_fbo_);
gl_->GenRenderbuffers(1, &multisample_renderbuffer_);
}
if (!ResizeFramebufferInternal(size))
return false;
if (depth_stencil_buffer_) {
DCHECK(WantDepthOrStencil());
has_implicit_stencil_buffer_ = !want_stencil_;
}
if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) {
return false;
}
return true;
}
| 172,293
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xsltNumberFormat(xsltTransformContextPtr ctxt,
xsltNumberDataPtr data,
xmlNodePtr node)
{
xmlBufferPtr output = NULL;
int amount, i;
double number;
xsltFormat tokens;
int tempformat = 0;
if ((data->format == NULL) && (data->has_format != 0)) {
data->format = xsltEvalAttrValueTemplate(ctxt, data->node,
(const xmlChar *) "format",
XSLT_NAMESPACE);
tempformat = 1;
}
if (data->format == NULL) {
return;
}
output = xmlBufferCreate();
if (output == NULL)
goto XSLT_NUMBER_FORMAT_END;
xsltNumberFormatTokenize(data->format, &tokens);
/*
* Evaluate the XPath expression to find the value(s)
*/
if (data->value) {
amount = xsltNumberFormatGetValue(ctxt->xpathCtxt,
node,
data->value,
&number);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (data->level) {
if (xmlStrEqual(data->level, (const xmlChar *) "single")) {
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number,
1,
data->doc,
data->node);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "multiple")) {
double numarray[1024];
int max = sizeof(numarray)/sizeof(numarray[0]);
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
numarray,
max,
data->doc,
data->node);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
numarray,
amount,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "any")) {
amount = xsltNumberFormatGetAnyLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number,
data->doc,
data->node);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
}
}
/* Insert number as text node */
xsltCopyTextString(ctxt, ctxt->insert, xmlBufferContent(output), 0);
if (tokens.start != NULL)
xmlFree(tokens.start);
if (tokens.end != NULL)
xmlFree(tokens.end);
for (i = 0;i < tokens.nTokens;i++) {
if (tokens.tokens[i].separator != NULL)
xmlFree(tokens.tokens[i].separator);
}
XSLT_NUMBER_FORMAT_END:
if (tempformat == 1) {
/* The format need to be recomputed each time */
data->format = NULL;
}
if (output != NULL)
xmlBufferFree(output);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
|
xsltNumberFormat(xsltTransformContextPtr ctxt,
xsltNumberDataPtr data,
xmlNodePtr node)
{
xmlBufferPtr output = NULL;
int amount, i;
double number;
xsltFormat tokens;
if (data->format != NULL) {
xsltNumberFormatTokenize(data->format, &tokens);
}
else {
xmlChar *format;
/* The format needs to be recomputed each time */
if (data->has_format == 0)
return;
format = xsltEvalAttrValueTemplate(ctxt, data->node,
(const xmlChar *) "format",
XSLT_NAMESPACE);
if (format == NULL)
return;
xsltNumberFormatTokenize(format, &tokens);
xmlFree(format);
}
output = xmlBufferCreate();
if (output == NULL)
goto XSLT_NUMBER_FORMAT_END;
/*
* Evaluate the XPath expression to find the value(s)
*/
if (data->value) {
amount = xsltNumberFormatGetValue(ctxt->xpathCtxt,
node,
data->value,
&number);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (data->level) {
if (xmlStrEqual(data->level, (const xmlChar *) "single")) {
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number,
1);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "multiple")) {
double numarray[1024];
int max = sizeof(numarray)/sizeof(numarray[0]);
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
numarray,
max);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
numarray,
amount,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "any")) {
amount = xsltNumberFormatGetAnyLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
}
}
/* Insert number as text node */
xsltCopyTextString(ctxt, ctxt->insert, xmlBufferContent(output), 0);
xmlBufferFree(output);
XSLT_NUMBER_FORMAT_END:
if (tokens.start != NULL)
xmlFree(tokens.start);
if (tokens.end != NULL)
xmlFree(tokens.end);
for (i = 0;i < tokens.nTokens;i++) {
if (tokens.tokens[i].separator != NULL)
xmlFree(tokens.tokens[i].separator);
}
}
| 173,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: void ChromeRenderProcessObserver::OnSetTcmallocHeapProfiling(
bool profiling, const std::string& filename_prefix) {
#if !defined(OS_WIN)
if (profiling)
HeapProfilerStart(filename_prefix.c_str());
else
HeapProfilerStop();
#endif
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
TBR=darin@chromium.org
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void ChromeRenderProcessObserver::OnSetTcmallocHeapProfiling(
| 170,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 php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC)
{
int err_code = 0;
int found = 0;
php_mb_regex_t *retval = NULL, **rc = NULL;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc);
if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) {
if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str);
retval = NULL;
goto out;
}
zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL);
} else if (found == SUCCESS) {
retval = *rc;
}
out:
return retval;
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415
|
static php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC)
{
int err_code = 0;
int found = 0;
php_mb_regex_t *retval = NULL, **rc = NULL;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc);
if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) {
if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str);
retval = NULL;
goto out;
}
zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL);
} else if (found == SUCCESS) {
retval = *rc;
}
out:
return retval;
}
| 167,123
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MemBackendImpl::DoomEntriesBetween(Time initial_time,
Time end_time,
const CompletionCallback& callback) {
if (end_time.is_null())
end_time = Time::Max();
DCHECK_GE(end_time, initial_time);
base::LinkNode<MemEntryImpl>* node = lru_list_.head();
while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time)
node = node->next();
while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) {
MemEntryImpl* to_doom = node->value();
node = node->next();
to_doom->Doom();
}
return net::OK;
}
Commit Message: [MemCache] Fix bug while iterating LRU list in range doom
This is exact same thing as https://chromium-review.googlesource.com/c/chromium/src/+/987919
but on explicit mass-erase rather than eviction.
Thanks to nedwilliamson@ (on gmail) for the report and testcase.
Bug: 831963
Change-Id: I96a46700c1f058f7feebe038bcf983dc40eb7102
Reviewed-on: https://chromium-review.googlesource.com/1014023
Commit-Queue: Maks Orlovich <morlovich@chromium.org>
Reviewed-by: Josh Karlin <jkarlin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#551205}
CWE ID: CWE-416
|
int MemBackendImpl::DoomEntriesBetween(Time initial_time,
Time end_time,
const CompletionCallback& callback) {
if (end_time.is_null())
end_time = Time::Max();
DCHECK_GE(end_time, initial_time);
base::LinkNode<MemEntryImpl>* node = lru_list_.head();
while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time)
node = node->next();
while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) {
MemEntryImpl* to_doom = node->value();
node = NextSkippingChildren(lru_list_, node);
to_doom->Doom();
}
return net::OK;
}
| 173,257
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual ~InputMethodLibraryImpl() {
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual ~InputMethodLibraryImpl() {
ibus_controller_->RemoveObserver(this);
}
| 170,516
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) {
if (node.isNull() || !node.document().frame()) {
return;
}
if (is_preview_enabled_) {
print_preview_context_.InitWithNode(node);
RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
} else {
WebKit::WebNode duplicate_node(node);
Print(duplicate_node.document().frame(), duplicate_node);
}
}
Commit Message: Guard against the same PrintWebViewHelper being re-entered.
BUG=159165
Review URL: https://chromiumcodereview.appspot.com/11367076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) {
if (node.isNull() || !node.document().frame()) {
return;
}
if (print_node_in_progress_) {
// This can happen as a result of processing sync messages when printing
// from ppapi plugins. It's a rare case, so its OK to just fail here.
// See http://crbug.com/159165.
return;
}
print_node_in_progress_ = true;
if (is_preview_enabled_) {
print_preview_context_.InitWithNode(node);
RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
} else {
WebKit::WebNode duplicate_node(node);
Print(duplicate_node.document().frame(), duplicate_node);
}
print_node_in_progress_ = false;
}
| 170,697
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
|
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
size_t j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
file->namelen = MIN(sizeof file->name, len);
memcpy(file->name, d, file->namelen);
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
| 169,075
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Track* Tracks::GetTrackByNumber(long tn) const
{
if (tn < 0)
return NULL;
Track** i = m_trackEntries;
Track** const j = m_trackEntriesEnd;
while (i != j)
{
Track* const pTrack = *i++;
if (pTrack == NULL)
continue;
if (tn == pTrack->GetNumber())
return pTrack;
}
return NULL; //not found
}
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 Track* Tracks::GetTrackByNumber(long tn) const
| 174,371
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void copy_fields(const FieldMatchContext *fm, AVFrame *dst,
const AVFrame *src, int field)
{
int plane;
for (plane = 0; plane < 4 && src->data[plane]; plane++)
av_image_copy_plane(dst->data[plane] + field*dst->linesize[plane], dst->linesize[plane] << 1,
src->data[plane] + field*src->linesize[plane], src->linesize[plane] << 1,
get_width(fm, src, plane), get_height(fm, src, plane) / 2);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
CWE ID: CWE-119
|
static void copy_fields(const FieldMatchContext *fm, AVFrame *dst,
const AVFrame *src, int field)
{
int plane;
for (plane = 0; plane < 4 && src->data[plane] && src->linesize[plane]; plane++)
av_image_copy_plane(dst->data[plane] + field*dst->linesize[plane], dst->linesize[plane] << 1,
src->data[plane] + field*src->linesize[plane], src->linesize[plane] << 1,
get_width(fm, src, plane), get_height(fm, src, plane) / 2);
}
| 165,999
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 worker_process(int fd, debugger_request_t& request) {
std::string tombstone_path;
int tombstone_fd = -1;
switch (request.action) {
case DEBUGGER_ACTION_DUMP_TOMBSTONE:
case DEBUGGER_ACTION_CRASH:
tombstone_fd = open_tombstone(&tombstone_path);
if (tombstone_fd == -1) {
ALOGE("debuggerd: failed to open tombstone file: %s\n", strerror(errno));
exit(1);
}
break;
case DEBUGGER_ACTION_DUMP_BACKTRACE:
break;
default:
ALOGE("debuggerd: unexpected request action: %d", request.action);
exit(1);
}
if (ptrace(PTRACE_ATTACH, request.tid, 0, 0) != 0) {
ALOGE("debuggerd: ptrace attach failed: %s", strerror(errno));
exit(1);
}
bool attach_gdb = should_attach_gdb(request);
if (attach_gdb) {
if (init_getevent() != 0) {
ALOGE("debuggerd: failed to initialize input device, not waiting for gdb");
attach_gdb = false;
}
}
std::set<pid_t> siblings;
if (!attach_gdb) {
ptrace_siblings(request.pid, request.tid, siblings);
}
std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(request.pid));
int amfd = -1;
std::unique_ptr<std::string> amfd_data;
if (request.action == DEBUGGER_ACTION_CRASH) {
amfd = activity_manager_connect();
amfd_data.reset(new std::string);
}
bool succeeded = false;
if (!drop_privileges()) {
ALOGE("debuggerd: failed to drop privileges, exiting");
_exit(1);
}
int crash_signal = SIGKILL;
succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings,
&crash_signal, amfd_data.get());
if (succeeded) {
if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
if (!tombstone_path.empty()) {
android::base::WriteFully(fd, tombstone_path.c_str(), tombstone_path.length());
}
}
}
if (attach_gdb) {
if (!send_signal(request.pid, 0, SIGSTOP)) {
ALOGE("debuggerd: failed to stop process for gdb attach: %s", strerror(errno));
attach_gdb = false;
}
}
if (!attach_gdb) {
activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get());
}
if (ptrace(PTRACE_DETACH, request.tid, 0, 0) != 0) {
ALOGE("debuggerd: ptrace detach from %d failed: %s", request.tid, strerror(errno));
}
for (pid_t sibling : siblings) {
ptrace(PTRACE_DETACH, sibling, 0, 0);
}
if (!attach_gdb && request.action == DEBUGGER_ACTION_CRASH) {
if (!send_signal(request.pid, request.tid, crash_signal)) {
ALOGE("debuggerd: failed to kill process %d: %s", request.pid, strerror(errno));
}
}
if (attach_gdb) {
wait_for_user_action(request);
activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get());
if (!send_signal(request.pid, 0, SIGCONT)) {
ALOGE("debuggerd: failed to resume process %d: %s", request.pid, strerror(errno));
}
uninit_getevent();
}
close(amfd);
exit(!succeeded);
}
Commit Message: debuggerd: verify that traced threads belong to the right process.
Fix two races in debuggerd's PTRACE_ATTACH logic:
1. The target thread in a crash dump request could exit between the
/proc/<pid>/task/<tid> check and the PTRACE_ATTACH.
2. Sibling threads could exit between listing /proc/<pid>/task and the
PTRACE_ATTACH.
Bug: http://b/29555636
Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591
CWE ID: CWE-264
|
static void worker_process(int fd, debugger_request_t& request) {
std::string tombstone_path;
int tombstone_fd = -1;
switch (request.action) {
case DEBUGGER_ACTION_DUMP_TOMBSTONE:
case DEBUGGER_ACTION_CRASH:
tombstone_fd = open_tombstone(&tombstone_path);
if (tombstone_fd == -1) {
ALOGE("debuggerd: failed to open tombstone file: %s\n", strerror(errno));
exit(1);
}
break;
case DEBUGGER_ACTION_DUMP_BACKTRACE:
break;
default:
ALOGE("debuggerd: unexpected request action: %d", request.action);
exit(1);
}
if (!ptrace_attach_thread(request.pid, request.tid)) {
ALOGE("debuggerd: ptrace attach failed: %s", strerror(errno));
exit(1);
}
// DEBUGGER_ACTION_CRASH requests can come from arbitrary processes and the tid field in the
// request is sent from the other side. If an attacker can cause a process to be spawned with the
// pid of their process, they could trick debuggerd into dumping that process by exiting after
// sending the request. Validate the trusted request.uid/gid to defend against this.
if (request.action == DEBUGGER_ACTION_CRASH) {
pid_t pid;
uid_t uid;
gid_t gid;
if (get_process_info(request.tid, &pid, &uid, &gid) != 0) {
ALOGE("debuggerd: failed to get process info for tid '%d'", request.tid);
exit(1);
}
if (pid != request.pid || uid != request.uid || gid != request.gid) {
ALOGE(
"debuggerd: attached task %d does not match request: "
"expected pid=%d,uid=%d,gid=%d, actual pid=%d,uid=%d,gid=%d",
request.tid, request.pid, request.uid, request.gid, pid, uid, gid);
exit(1);
}
}
bool attach_gdb = should_attach_gdb(request);
if (attach_gdb) {
if (init_getevent() != 0) {
ALOGE("debuggerd: failed to initialize input device, not waiting for gdb");
attach_gdb = false;
}
}
std::set<pid_t> siblings;
if (!attach_gdb) {
ptrace_siblings(request.pid, request.tid, siblings);
}
std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(request.pid));
int amfd = -1;
std::unique_ptr<std::string> amfd_data;
if (request.action == DEBUGGER_ACTION_CRASH) {
amfd = activity_manager_connect();
amfd_data.reset(new std::string);
}
bool succeeded = false;
if (!drop_privileges()) {
ALOGE("debuggerd: failed to drop privileges, exiting");
_exit(1);
}
int crash_signal = SIGKILL;
succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings,
&crash_signal, amfd_data.get());
if (succeeded) {
if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
if (!tombstone_path.empty()) {
android::base::WriteFully(fd, tombstone_path.c_str(), tombstone_path.length());
}
}
}
if (attach_gdb) {
if (!send_signal(request.pid, 0, SIGSTOP)) {
ALOGE("debuggerd: failed to stop process for gdb attach: %s", strerror(errno));
attach_gdb = false;
}
}
if (!attach_gdb) {
activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get());
}
if (ptrace(PTRACE_DETACH, request.tid, 0, 0) != 0) {
ALOGE("debuggerd: ptrace detach from %d failed: %s", request.tid, strerror(errno));
}
for (pid_t sibling : siblings) {
ptrace(PTRACE_DETACH, sibling, 0, 0);
}
if (!attach_gdb && request.action == DEBUGGER_ACTION_CRASH) {
if (!send_signal(request.pid, request.tid, crash_signal)) {
ALOGE("debuggerd: failed to kill process %d: %s", request.pid, strerror(errno));
}
}
if (attach_gdb) {
wait_for_user_action(request);
activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get());
if (!send_signal(request.pid, 0, SIGCONT)) {
ALOGE("debuggerd: failed to resume process %d: %s", request.pid, strerror(errno));
}
uninit_getevent();
}
close(amfd);
exit(!succeeded);
}
| 173,408
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers(
extensions::Dispatcher* dispatcher,
extensions::ModuleSystem* module_system,
extensions::ScriptContext* context) {
module_system->RegisterNativeHandler(
"app", std::unique_ptr<NativeHandler>(
new extensions::AppBindings(dispatcher, context)));
module_system->RegisterNativeHandler(
"sync_file_system",
std::unique_ptr<NativeHandler>(
new extensions::SyncFileSystemCustomBindings(context)));
module_system->RegisterNativeHandler(
"file_browser_handler",
std::unique_ptr<NativeHandler>(
new extensions::FileBrowserHandlerCustomBindings(context)));
module_system->RegisterNativeHandler(
"file_manager_private",
std::unique_ptr<NativeHandler>(
new extensions::FileManagerPrivateCustomBindings(context)));
module_system->RegisterNativeHandler(
"notifications_private",
std::unique_ptr<NativeHandler>(
new extensions::NotificationsNativeHandler(context)));
module_system->RegisterNativeHandler(
"mediaGalleries",
std::unique_ptr<NativeHandler>(
new extensions::MediaGalleriesCustomBindings(context)));
module_system->RegisterNativeHandler(
"page_capture", std::unique_ptr<NativeHandler>(
new extensions::PageCaptureCustomBindings(context)));
module_system->RegisterNativeHandler(
"platform_keys_natives",
std::unique_ptr<NativeHandler>(
new extensions::PlatformKeysNatives(context)));
module_system->RegisterNativeHandler(
"tabs", std::unique_ptr<NativeHandler>(
new extensions::TabsCustomBindings(context)));
module_system->RegisterNativeHandler(
"webstore", std::unique_ptr<NativeHandler>(
new extensions::WebstoreBindings(context)));
#if defined(ENABLE_WEBRTC)
module_system->RegisterNativeHandler(
"cast_streaming_natives",
std::unique_ptr<NativeHandler>(
new extensions::CastStreamingNativeHandler(context)));
#endif
module_system->RegisterNativeHandler(
"automationInternal",
std::unique_ptr<NativeHandler>(
new extensions::AutomationInternalCustomBindings(context)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284
|
void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers(
extensions::Dispatcher* dispatcher,
extensions::ModuleSystem* module_system,
extensions::ScriptContext* context) {
module_system->RegisterNativeHandler(
"app", std::unique_ptr<NativeHandler>(
new extensions::AppBindings(dispatcher, context)));
module_system->RegisterNativeHandler(
"sync_file_system",
std::unique_ptr<NativeHandler>(
new extensions::SyncFileSystemCustomBindings(context)));
module_system->RegisterNativeHandler(
"file_browser_handler",
std::unique_ptr<NativeHandler>(
new extensions::FileBrowserHandlerCustomBindings(context)));
module_system->RegisterNativeHandler(
"file_manager_private",
std::unique_ptr<NativeHandler>(
new extensions::FileManagerPrivateCustomBindings(context)));
module_system->RegisterNativeHandler(
"notifications_private",
std::unique_ptr<NativeHandler>(
new extensions::NotificationsNativeHandler(context)));
module_system->RegisterNativeHandler(
"mediaGalleries",
std::unique_ptr<NativeHandler>(
new extensions::MediaGalleriesCustomBindings(context)));
module_system->RegisterNativeHandler(
"page_capture", std::unique_ptr<NativeHandler>(
new extensions::PageCaptureCustomBindings(context)));
module_system->RegisterNativeHandler(
"platform_keys_natives",
std::unique_ptr<NativeHandler>(
new extensions::PlatformKeysNatives(context)));
module_system->RegisterNativeHandler(
"tabs", std::unique_ptr<NativeHandler>(
new extensions::TabsCustomBindings(context)));
module_system->RegisterNativeHandler(
"webstore", std::unique_ptr<NativeHandler>(
new extensions::WebstoreBindings(context)));
#if defined(ENABLE_WEBRTC)
module_system->RegisterNativeHandler(
"cast_streaming_natives",
std::unique_ptr<NativeHandler>(
new extensions::CastStreamingNativeHandler(context)));
#endif
module_system->RegisterNativeHandler(
"automationInternal",
std::unique_ptr<NativeHandler>(
new extensions::AutomationInternalCustomBindings(context)));
// The following are native handlers that are defined in //extensions, but
// are only used for APIs defined in Chrome.
// TODO(devlin): We should clean this up. If an API is defined in Chrome,
// there's no reason to have its native handlers residing and being compiled
// in //extensions.
module_system->RegisterNativeHandler(
"i18n",
scoped_ptr<NativeHandler>(new extensions::I18NCustomBindings(context)));
module_system->RegisterNativeHandler(
"lazy_background_page",
scoped_ptr<NativeHandler>(
new extensions::LazyBackgroundPageNativeHandler(context)));
}
| 172,243
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: X11SurfaceFactory::GetAllowedGLImplementations() {
std::vector<gl::GLImplementation> impls;
impls.push_back(gl::kGLImplementationEGLGLES2);
impls.push_back(gl::kGLImplementationDesktopGL);
impls.push_back(gl::kGLImplementationOSMesaGL);
return impls;
}
Commit Message: Add ThreadChecker for Ozone X11 GPU.
Ensure Ozone X11 tests the same thread constraints we have in Ozone GBM.
BUG=none
Review-Url: https://codereview.chromium.org/2366643002
Cr-Commit-Position: refs/heads/master@{#421817}
CWE ID: CWE-284
|
X11SurfaceFactory::GetAllowedGLImplementations() {
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<gl::GLImplementation> impls;
impls.push_back(gl::kGLImplementationEGLGLES2);
impls.push_back(gl::kGLImplementationDesktopGL);
impls.push_back(gl::kGLImplementationOSMesaGL);
return impls;
}
| 171,602
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: vmxnet3_io_bar0_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
VMXNET3State *s = opaque;
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_TXPROD,
VMXNET3_DEVICE_MAX_TX_QUEUES, VMXNET3_REG_ALIGN)) {
int tx_queue_idx =
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) {
int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_REG_ALIGN);
VMW_CBPRN("Interrupt mask for line %d written: 0x%" PRIx64, l, val);
vmxnet3_on_interrupt_mask_changed(s, l, val);
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN) ||
VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD2,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN)) {
return;
}
VMW_WRPRN("BAR0 unknown write [%" PRIx64 "] = %" PRIx64 ", size %d",
(uint64_t) addr, val, size);
}
Commit Message:
CWE ID: CWE-416
|
vmxnet3_io_bar0_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
VMXNET3State *s = opaque;
if (!s->device_active) {
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_TXPROD,
VMXNET3_DEVICE_MAX_TX_QUEUES, VMXNET3_REG_ALIGN)) {
int tx_queue_idx =
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) {
int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_REG_ALIGN);
VMW_CBPRN("Interrupt mask for line %d written: 0x%" PRIx64, l, val);
vmxnet3_on_interrupt_mask_changed(s, l, val);
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN) ||
VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD2,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN)) {
return;
}
VMW_WRPRN("BAR0 unknown write [%" PRIx64 "] = %" PRIx64 ", size %d",
(uint64_t) addr, val, size);
}
| 164,953
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void encode_share_access(struct xdr_stream *xdr, int open_flags)
{
__be32 *p;
RESERVE_SPACE(8);
switch (open_flags & (FMODE_READ|FMODE_WRITE)) {
case FMODE_READ:
WRITE32(NFS4_SHARE_ACCESS_READ);
break;
case FMODE_WRITE:
WRITE32(NFS4_SHARE_ACCESS_WRITE);
break;
case FMODE_READ|FMODE_WRITE:
WRITE32(NFS4_SHARE_ACCESS_BOTH);
break;
default:
BUG();
}
WRITE32(0); /* for linux, share_deny = 0 always */
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
static void encode_share_access(struct xdr_stream *xdr, int open_flags)
static void encode_share_access(struct xdr_stream *xdr, fmode_t fmode)
{
__be32 *p;
RESERVE_SPACE(8);
switch (fmode & (FMODE_READ|FMODE_WRITE)) {
case FMODE_READ:
WRITE32(NFS4_SHARE_ACCESS_READ);
break;
case FMODE_WRITE:
WRITE32(NFS4_SHARE_ACCESS_WRITE);
break;
case FMODE_READ|FMODE_WRITE:
WRITE32(NFS4_SHARE_ACCESS_BOTH);
break;
default:
WRITE32(0);
}
WRITE32(0); /* for linux, share_deny = 0 always */
}
| 165,715
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) {
return (OMX_BUFFERHEADERTYPE *)buffer;
}
Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32
Bug: 20634516
Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c
(cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4)
CWE ID: CWE-119
|
OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) {
| 173,357
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionViewGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached() && (params.url.GetOrigin() != url_.GetOrigin())) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EVG_BAD_ORIGIN);
}
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
CWE ID: CWE-284
|
void ExtensionViewGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached() && !url::IsSameOriginWith(params.url, url_)) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EVG_BAD_ORIGIN);
}
}
| 172,283
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: unsigned long Segment::GetCount() const
{
return m_clusterCount;
}
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
|
unsigned long Segment::GetCount() const
| 174,299
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
Commit Message: ...
CWE ID: CWE-20
|
ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
| 170,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: int rose_parse_facilities(unsigned char *p,
struct rose_facilities_struct *facilities)
{
int facilities_len, len;
facilities_len = *p++;
if (facilities_len == 0)
return 0;
while (facilities_len > 0) {
if (*p == 0x00) {
facilities_len--;
p++;
switch (*p) {
case FAC_NATIONAL: /* National */
len = rose_parse_national(p + 1, facilities, facilities_len - 1);
facilities_len -= len + 1;
p += len + 1;
break;
case FAC_CCITT: /* CCITT */
len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1);
facilities_len -= len + 1;
p += len + 1;
break;
default:
printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p);
facilities_len--;
p++;
break;
}
} else
break; /* Error in facilities format */
}
return 1;
}
Commit Message: ROSE: prevent heap corruption with bad facilities
When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for
a remote host to provide more digipeaters than expected, resulting in
heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and
abort facilities parsing on failure.
Additionally, when parsing the FAC_CCITT_DEST_NSAP and
FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length
of less than 10, resulting in an underflow in a memcpy size, causing a
kernel panic due to massive heap corruption. A length of greater than
20 results in a stack overflow of the callsign array. Abort facilities
parsing on these invalid length values.
Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com>
Cc: stable@kernel.org
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20
|
int rose_parse_facilities(unsigned char *p,
struct rose_facilities_struct *facilities)
{
int facilities_len, len;
facilities_len = *p++;
if (facilities_len == 0)
return 0;
while (facilities_len > 0) {
if (*p == 0x00) {
facilities_len--;
p++;
switch (*p) {
case FAC_NATIONAL: /* National */
len = rose_parse_national(p + 1, facilities, facilities_len - 1);
if (len < 0)
return 0;
facilities_len -= len + 1;
p += len + 1;
break;
case FAC_CCITT: /* CCITT */
len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1);
if (len < 0)
return 0;
facilities_len -= len + 1;
p += len + 1;
break;
default:
printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p);
facilities_len--;
p++;
break;
}
} else
break; /* Error in facilities format */
}
return 1;
}
| 165,672
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tls1_cbc_remove_padding(const SSL* s,
SSL3_RECORD *rec,
unsigned block_size,
unsigned mac_size)
{
unsigned padding_length, good, to_check, i;
const char has_explicit_iv =
s->version >= TLS1_1_VERSION || s->version == DTLS1_VERSION;
const unsigned overhead = 1 /* padding length byte */ +
mac_size +
(has_explicit_iv ? block_size : 0);
/* These lengths are all public so we can test them in non-constant
* time. */
if (overhead > rec->length)
return 0;
padding_length = rec->data[rec->length-1];
/* NB: if compression is in operation the first packet may not be of
padding_length--;
}
Commit Message:
CWE ID: CWE-310
|
int tls1_cbc_remove_padding(const SSL* s,
SSL3_RECORD *rec,
unsigned block_size,
unsigned mac_size)
{
unsigned padding_length, good, to_check, i;
const char has_explicit_iv =
s->version >= TLS1_1_VERSION || s->version == DTLS1_VERSION;
const unsigned overhead = 1 /* padding length byte */ +
mac_size +
(has_explicit_iv ? block_size : 0);
/* These lengths are all public so we can test them in non-constant
* time. */
if (overhead > rec->length)
return 0;
/* We can always safely skip the explicit IV. We check at the beginning
* of this function that the record has at least enough space for the
* IV, MAC and padding length byte. (These can be checked in
* non-constant time because it's all public information.) So, if the
* padding was invalid, then we didn't change |rec->length| and this is
* safe. If the padding was valid then we know that we have at least
* overhead+padding_length bytes of space and so this is still safe
* because overhead accounts for the explicit IV. */
if (has_explicit_iv)
{
rec->data += block_size;
rec->input += block_size;
rec->length -= block_size;
}
padding_length = rec->data[rec->length-1];
/* NB: if compression is in operation the first packet may not be of
padding_length--;
}
| 164,868
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ps_parser_skip_PS_token( PS_Parser parser )
{
/* Note: PostScript allows any non-delimiting, non-whitespace */
/* character in a name (PS Ref Manual, 3rd ed, p31). */
/* PostScript delimiters are (, ), <, >, [, ], {, }, /, and %. */
FT_Byte* cur = parser->cursor;
FT_Byte* limit = parser->limit;
FT_Error error = FT_Err_Ok;
skip_spaces( &cur, limit ); /* this also skips comments */
if ( cur >= limit )
goto Exit;
/* self-delimiting, single-character tokens */
if ( *cur == '[' || *cur == ']' )
{
cur++;
goto Exit;
}
/* skip balanced expressions (procedures and strings) */
if ( *cur == '{' ) /* {...} */
{
error = skip_procedure( &cur, limit );
goto Exit;
}
if ( *cur == '(' ) /* (...) */
{
error = skip_literal_string( &cur, limit );
goto Exit;
}
if ( *cur == '<' ) /* <...> */
{
if ( cur + 1 < limit && *(cur + 1) == '<' ) /* << */
{
cur++;
cur++;
}
else
error = skip_string( &cur, limit );
goto Exit;
}
if ( *cur == '>' )
{
cur++;
if ( cur >= limit || *cur != '>' ) /* >> */
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" unexpected closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
goto Exit;
}
if ( *cur == '/' )
cur++;
/* anything else */
while ( cur < limit )
{
/* *cur might be invalid (e.g., ')' or '}'), but this */
/* is handled by the test `cur == parser->cursor' below */
if ( IS_PS_DELIM( *cur ) )
break;
cur++;
}
Exit:
if ( cur < limit && cur == parser->cursor )
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" current token is `%c' which is self-delimiting\n"
" "
" but invalid at this point\n",
*cur ));
error = FT_THROW( Invalid_File_Format );
}
parser->error = error;
parser->cursor = cur;
}
Commit Message:
CWE ID: CWE-125
|
ps_parser_skip_PS_token( PS_Parser parser )
{
/* Note: PostScript allows any non-delimiting, non-whitespace */
/* character in a name (PS Ref Manual, 3rd ed, p31). */
/* PostScript delimiters are (, ), <, >, [, ], {, }, /, and %. */
FT_Byte* cur = parser->cursor;
FT_Byte* limit = parser->limit;
FT_Error error = FT_Err_Ok;
skip_spaces( &cur, limit ); /* this also skips comments */
if ( cur >= limit )
goto Exit;
/* self-delimiting, single-character tokens */
if ( *cur == '[' || *cur == ']' )
{
cur++;
goto Exit;
}
/* skip balanced expressions (procedures and strings) */
if ( *cur == '{' ) /* {...} */
{
error = skip_procedure( &cur, limit );
goto Exit;
}
if ( *cur == '(' ) /* (...) */
{
error = skip_literal_string( &cur, limit );
goto Exit;
}
if ( *cur == '<' ) /* <...> */
{
if ( cur + 1 < limit && *(cur + 1) == '<' ) /* << */
{
cur++;
cur++;
}
else
error = skip_string( &cur, limit );
goto Exit;
}
if ( *cur == '>' )
{
cur++;
if ( cur >= limit || *cur != '>' ) /* >> */
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" unexpected closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
goto Exit;
}
if ( *cur == '/' )
cur++;
/* anything else */
while ( cur < limit )
{
/* *cur might be invalid (e.g., ')' or '}'), but this */
/* is handled by the test `cur == parser->cursor' below */
if ( IS_PS_DELIM( *cur ) )
break;
cur++;
}
Exit:
if ( cur < limit && cur == parser->cursor )
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" current token is `%c' which is self-delimiting\n"
" "
" but invalid at this point\n",
*cur ));
error = FT_THROW( Invalid_File_Format );
}
if ( cur > limit )
cur = limit;
parser->error = error;
parser->cursor = cur;
}
| 165,427
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ext4_invalidatepage(struct page *page, unsigned long offset)
{
journal_t *journal = EXT4_JOURNAL(page->mapping->host);
/*
* If it's a full truncate we just forget about the pending dirtying
*/
if (offset == 0)
ClearPageChecked(page);
if (journal)
jbd2_journal_invalidatepage(journal, page, offset);
else
block_invalidatepage(page, offset);
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
static void ext4_invalidatepage(struct page *page, unsigned long offset)
{
journal_t *journal = EXT4_JOURNAL(page->mapping->host);
/*
* free any io_end structure allocated for buffers to be discarded
*/
if (ext4_should_dioread_nolock(page->mapping->host))
ext4_invalidatepage_free_endio(page, offset);
/*
* If it's a full truncate we just forget about the pending dirtying
*/
if (offset == 0)
ClearPageChecked(page);
if (journal)
jbd2_journal_invalidatepage(journal, page, offset);
else
block_invalidatepage(page, offset);
}
| 167,547
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void perform_gamma_scale16_tests(png_modifier *pm)
{
# ifndef PNG_MAX_GAMMA_8
# define PNG_MAX_GAMMA_8 11
# endif
# define SBIT_16_TO_8 PNG_MAX_GAMMA_8
/* Include the alpha cases here. Note that sbit matches the internal value
* used by the library - otherwise we will get spurious errors from the
* internal sbit style approximation.
*
* The threshold test is here because otherwise the 16 to 8 conversion will
* proceed *without* gamma correction, and the tests above will fail (but not
* by much) - this could be fixed, it only appears with the -g option.
*/
unsigned int i, j;
for (i=0; i<pm->ngamma_tests; ++i)
{
for (j=0; j<pm->ngamma_tests; ++j)
{
if (i != j &&
fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
{
gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
}
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
static void perform_gamma_scale16_tests(png_modifier *pm)
{
# ifndef PNG_MAX_GAMMA_8
# define PNG_MAX_GAMMA_8 11
# endif
# if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700
# define SBIT_16_TO_8 PNG_MAX_GAMMA_8
# else
# define SBIT_16_TO_8 16
# endif
/* Include the alpha cases here. Note that sbit matches the internal value
* used by the library - otherwise we will get spurious errors from the
* internal sbit style approximation.
*
* The threshold test is here because otherwise the 16 to 8 conversion will
* proceed *without* gamma correction, and the tests above will fail (but not
* by much) - this could be fixed, it only appears with the -g option.
*/
unsigned int i, j;
for (i=0; i<pm->ngamma_tests; ++i)
{
for (j=0; j<pm->ngamma_tests; ++j)
{
if (i != j &&
fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
{
gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
}
}
}
}
| 173,681
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(SplFileObject, setCsvControl)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = ',', enclosure = '"', escape='\\';
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 3:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 2:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 1:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 0:
break;
}
intern->u.file.delimiter = delimiter;
intern->u.file.enclosure = enclosure;
intern->u.file.escape = escape;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, setCsvControl)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = ',', enclosure = '"', escape='\\';
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 3:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 2:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 1:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 0:
break;
}
intern->u.file.delimiter = delimiter;
intern->u.file.enclosure = enclosure;
intern->u.file.escape = escape;
}
}
| 167,063
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: _rsvg_io_get_file_path (const gchar * filename,
const gchar * base_uri)
{
gchar *absolute_filename;
if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) {
absolute_filename = g_strdup (filename);
} else {
gchar *tmpcdir;
gchar *base_filename;
if (base_uri) {
base_filename = g_filename_from_uri (base_uri, NULL, NULL);
if (base_filename != NULL) {
tmpcdir = g_path_get_dirname (base_filename);
g_free (base_filename);
} else
return NULL;
} else
tmpcdir = g_get_current_dir ();
absolute_filename = g_build_filename (tmpcdir, filename, NULL);
g_free (tmpcdir);
}
return absolute_filename;
}
Commit Message: Fixed possible credentials leaking reported by Alex Birsan.
CWE ID:
|
_rsvg_io_get_file_path (const gchar * filename,
const gchar * base_uri)
{
gchar *absolute_filename;
if (g_path_is_absolute (filename)) {
absolute_filename = g_strdup (filename);
} else {
gchar *tmpcdir;
gchar *base_filename;
if (base_uri) {
base_filename = g_filename_from_uri (base_uri, NULL, NULL);
if (base_filename != NULL) {
tmpcdir = g_path_get_dirname (base_filename);
g_free (base_filename);
} else
return NULL;
} else
tmpcdir = g_get_current_dir ();
absolute_filename = g_build_filename (tmpcdir, filename, NULL);
g_free (tmpcdir);
}
return absolute_filename;
}
| 170,157
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cluster* Segment::FindOrPreloadCluster(long long requested_pos)
{
if (requested_pos < 0)
return 0;
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j)
{
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < requested_pos)
i = k + 1;
else if (pos > requested_pos)
j = k;
else
return pCluster;
}
assert(i == j);
Cluster* const pCluster = Cluster::Create(
this,
-1,
requested_pos);
assert(pCluster);
const ptrdiff_t idx = i - m_clusters;
PreloadCluster(pCluster, idx);
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster;
}
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 Cluster* Segment::FindOrPreloadCluster(long long requested_pos)
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j) {
// INVARIANT:
//[ii, i) < pTP->m_pos
//[i, j) ?
//[j, jj) > pTP->m_pos
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
// const long long pos_ = pCluster->m_pos;
// assert(pos_);
// const long long pos = pos_ * ((pos_ < 0) ? -1 : 1);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < requested_pos)
i = k + 1;
else if (pos > requested_pos)
j = k;
else
return pCluster;
}
assert(i == j);
// assert(Cluster::HasBlockEntries(this, tp.m_pos));
Cluster* const pCluster = Cluster::Create(this, -1, requested_pos);
//-1);
assert(pCluster);
const ptrdiff_t idx = i - m_clusters;
PreloadCluster(pCluster, idx);
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster;
}
| 174,280
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg, *funcname;
gss_buffer_desc client_name, service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
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;
funcname = "kadm5_purgekeys";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL))) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp);
} else {
ret.code = kadm5_purgekeys((void *)handle, arg->princ,
arg->keepkvno);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, 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
|
purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg, *funcname;
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;
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;
funcname = "kadm5_purgekeys";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL))) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp);
} else {
ret.code = kadm5_purgekeys((void *)handle, arg->princ,
arg->keepkvno);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, 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,522
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static BT_HDR *create_pbuf(UINT16 len, UINT8 *data)
{
BT_HDR* p_buf = GKI_getbuf((UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR)));
if (p_buf) {
UINT8* pbuf_data;
p_buf->len = len;
p_buf->offset = BTA_HH_MIN_OFFSET;
pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset;
memcpy(pbuf_data, data, len);
}
return p_buf;
}
Commit Message: DO NOT MERGE btif: check overflow on create_pbuf size
Bug: 27930580
Change-Id: Ieb1f23f9a8a937b21f7c5eca92da3b0b821400e6
CWE ID: CWE-119
|
static BT_HDR *create_pbuf(UINT16 len, UINT8 *data)
{
UINT16 buflen = (UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR));
if (buflen < len) {
android_errorWriteWithInfoLog(0x534e4554, "28672558", -1, NULL, 0);
return NULL;
}
BT_HDR* p_buf = GKI_getbuf(buflen);
if (p_buf) {
UINT8* pbuf_data;
p_buf->len = len;
p_buf->offset = BTA_HH_MIN_OFFSET;
pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset;
memcpy(pbuf_data, data, len);
}
return p_buf;
}
| 173,757
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: gs_heap_alloc_bytes(gs_memory_t * mem, uint size, client_name_t cname)
{
gs_malloc_memory_t *mmem = (gs_malloc_memory_t *) mem;
byte *ptr = 0;
#ifdef DEBUG
const char *msg;
static const char *const ok_msg = "OK";
# define set_msg(str) (msg = (str))
#else
# define set_msg(str) DO_NOTHING
#endif
/* Exclusive acces so our decisions and changes are 'atomic' */
if (mmem->monitor)
gx_monitor_enter(mmem->monitor);
if (size > mmem->limit - sizeof(gs_malloc_block_t)) {
/* Definitely too large to allocate; also avoids overflow. */
set_msg("exceeded limit");
} else {
uint added = size + sizeof(gs_malloc_block_t);
if (mmem->limit - added < mmem->used)
set_msg("exceeded limit");
else if ((ptr = (byte *) Memento_label(malloc(added), cname)) == 0)
set_msg("failed");
else {
gs_malloc_block_t *bp = (gs_malloc_block_t *) ptr;
/*
* We would like to check that malloc aligns blocks at least as
* strictly as the compiler (as defined by ARCH_ALIGN_MEMORY_MOD).
* However, Microsoft VC 6 does not satisfy this requirement.
* See gsmemory.h for more explanation.
*/
set_msg(ok_msg);
if (mmem->allocated)
mmem->allocated->prev = bp;
bp->next = mmem->allocated;
bp->prev = 0;
bp->size = size;
bp->type = &st_bytes;
bp->cname = cname;
mmem->allocated = bp;
ptr = (byte *) (bp + 1);
mmem->used += size + sizeof(gs_malloc_block_t);
if (mmem->used > mmem->max_used)
mmem->max_used = mmem->used;
}
}
if (mmem->monitor)
gx_monitor_leave(mmem->monitor); /* Done with exclusive access */
/* We don't want to 'fill' under mutex to keep the window smaller */
if (ptr)
gs_alloc_fill(ptr, gs_alloc_fill_alloc, size);
#ifdef DEBUG
if (gs_debug_c('a') || msg != ok_msg)
dmlprintf6(mem, "[a+]gs_malloc(%s)(%u) = 0x%lx: %s, used=%ld, max=%ld\n",
client_name_string(cname), size, (ulong) ptr, msg, mmem->used, mmem->max_used);
#endif
return ptr;
#undef set_msg
}
Commit Message:
CWE ID: CWE-189
|
gs_heap_alloc_bytes(gs_memory_t * mem, uint size, client_name_t cname)
{
gs_malloc_memory_t *mmem = (gs_malloc_memory_t *) mem;
byte *ptr = 0;
#ifdef DEBUG
const char *msg;
static const char *const ok_msg = "OK";
# define set_msg(str) (msg = (str))
#else
# define set_msg(str) DO_NOTHING
#endif
/* Exclusive acces so our decisions and changes are 'atomic' */
if (mmem->monitor)
gx_monitor_enter(mmem->monitor);
if (size > mmem->limit - sizeof(gs_malloc_block_t)) {
/* Definitely too large to allocate; also avoids overflow. */
set_msg("exceeded limit");
} else {
uint added = size + sizeof(gs_malloc_block_t);
if (added <= size || mmem->limit - added < mmem->used)
set_msg("exceeded limit");
else if ((ptr = (byte *) Memento_label(malloc(added), cname)) == 0)
set_msg("failed");
else {
gs_malloc_block_t *bp = (gs_malloc_block_t *) ptr;
/*
* We would like to check that malloc aligns blocks at least as
* strictly as the compiler (as defined by ARCH_ALIGN_MEMORY_MOD).
* However, Microsoft VC 6 does not satisfy this requirement.
* See gsmemory.h for more explanation.
*/
set_msg(ok_msg);
if (mmem->allocated)
mmem->allocated->prev = bp;
bp->next = mmem->allocated;
bp->prev = 0;
bp->size = size;
bp->type = &st_bytes;
bp->cname = cname;
mmem->allocated = bp;
ptr = (byte *) (bp + 1);
mmem->used += size + sizeof(gs_malloc_block_t);
if (mmem->used > mmem->max_used)
mmem->max_used = mmem->used;
}
}
if (mmem->monitor)
gx_monitor_leave(mmem->monitor); /* Done with exclusive access */
/* We don't want to 'fill' under mutex to keep the window smaller */
if (ptr)
gs_alloc_fill(ptr, gs_alloc_fill_alloc, size);
#ifdef DEBUG
if (gs_debug_c('a') || msg != ok_msg)
dmlprintf6(mem, "[a+]gs_malloc(%s)(%u) = 0x%lx: %s, used=%ld, max=%ld\n",
client_name_string(cname), size, (ulong) ptr, msg, mmem->used, mmem->max_used);
#endif
return ptr;
#undef set_msg
}
| 164,715
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
size_t *len,
struct iovec **iovec,
bool compat)
{
ssize_t ret;
*nr_segs = *len;
#ifdef CONFIG_COMPAT
if (compat)
ret = compat_rw_copy_check_uvector(rw,
(struct compat_iovec __user *)buf,
*nr_segs, UIO_FASTIOV, *iovec, iovec);
else
#endif
ret = rw_copy_check_uvector(rw,
(struct iovec __user *)buf,
*nr_segs, UIO_FASTIOV, *iovec, iovec);
if (ret < 0)
return ret;
/* len now reflect bytes instead of segs */
*len = ret;
return 0;
}
Commit Message: aio: lift iov_iter_init() into aio_setup_..._rw()
the only non-trivial detail is that we do it before rw_verify_area(),
so we'd better cap the length ourselves in aio_setup_single_rw()
case (for vectored case rw_copy_check_uvector() will do that for us).
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID:
|
static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
size_t *len,
struct iovec **iovec,
bool compat,
struct iov_iter *iter)
{
ssize_t ret;
*nr_segs = *len;
#ifdef CONFIG_COMPAT
if (compat)
ret = compat_rw_copy_check_uvector(rw,
(struct compat_iovec __user *)buf,
*nr_segs, UIO_FASTIOV, *iovec, iovec);
else
#endif
ret = rw_copy_check_uvector(rw,
(struct iovec __user *)buf,
*nr_segs, UIO_FASTIOV, *iovec, iovec);
if (ret < 0)
return ret;
/* len now reflect bytes instead of segs */
*len = ret;
iov_iter_init(iter, rw, *iovec, *nr_segs, *len);
return 0;
}
| 170,003
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: base::string16 GetAppForProtocolUsingAssocQuery(const GURL& url) {
base::string16 url_scheme = base::ASCIIToUTF16(url.scheme());
if (url_scheme.empty())
return base::string16();
wchar_t out_buffer[1024];
DWORD buffer_size = arraysize(out_buffer);
HRESULT hr = AssocQueryString(ASSOCF_IS_PROTOCOL,
ASSOCSTR_FRIENDLYAPPNAME,
url_scheme.c_str(),
NULL,
out_buffer,
&buffer_size);
if (FAILED(hr)) {
DLOG(WARNING) << "AssocQueryString failed!";
return base::string16();
}
return base::string16(out_buffer);
}
Commit Message: Validate external protocols before launching on Windows
Bug: 889459
Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef
Reviewed-on: https://chromium-review.googlesource.com/c/1256208
Reviewed-by: Greg Thompson <grt@chromium.org>
Commit-Queue: Mustafa Emre Acer <meacer@chromium.org>
Cr-Commit-Position: refs/heads/master@{#597611}
CWE ID: CWE-20
|
base::string16 GetAppForProtocolUsingAssocQuery(const GURL& url) {
const base::string16 url_scheme = base::ASCIIToUTF16(url.scheme());
if (!IsValidCustomProtocol(url_scheme))
return base::string16();
wchar_t out_buffer[1024];
DWORD buffer_size = arraysize(out_buffer);
HRESULT hr =
AssocQueryString(ASSOCF_IS_PROTOCOL, ASSOCSTR_FRIENDLYAPPNAME,
url_scheme.c_str(), NULL, out_buffer, &buffer_size);
if (FAILED(hr)) {
DLOG(WARNING) << "AssocQueryString failed!";
return base::string16();
}
return base::string16(out_buffer);
}
| 172,635
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftAMRNBEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPortFormat:
{
OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
formatParams->eEncoding =
(formatParams->nPortIndex == 0)
? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAMR;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (amrParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
amrParams->nChannels = 1;
amrParams->nBitRate = mBitRate;
amrParams->eAMRBandMode = (OMX_AUDIO_AMRBANDMODETYPE)(mMode + 1);
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelCF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = kSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftAMRNBEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPortFormat:
{
OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
formatParams->eEncoding =
(formatParams->nPortIndex == 0)
? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAMR;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (!isValidOMXParam(amrParams)) {
return OMX_ErrorBadParameter;
}
if (amrParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
amrParams->nChannels = 1;
amrParams->nBitRate = mBitRate;
amrParams->eAMRBandMode = (OMX_AUDIO_AMRBANDMODETYPE)(mMode + 1);
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelCF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = kSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,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: xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((ctxt->options & XML_PARSE_OLD10) == 0) {
/*
* Use the new checks of production [4] [4a] amd [5] of the
* Update 5 of XML-1.0
*/
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
(c == '_') || (c == ':') ||
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) || /* !start */
(c == '_') || (c == ':') ||
(c == '-') || (c == '.') || (c == 0xB7) || /* !start */
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x300) && (c <= 0x36F)) || /* !start */
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x203F) && (c <= 0x2040)) || /* !start */
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))
)) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
} else {
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!IS_LETTER(c) && (c != '_') &&
(c != ':'))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
}
if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
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
|
xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
c = CUR_CHAR(l);
if ((ctxt->options & XML_PARSE_OLD10) == 0) {
/*
* Use the new checks of production [4] [4a] amd [5] of the
* Update 5 of XML-1.0
*/
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
(c == '_') || (c == ':') ||
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) || /* !start */
(c == '_') || (c == ':') ||
(c == '-') || (c == '.') || (c == 0xB7) || /* !start */
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x300) && (c <= 0x36F)) || /* !start */
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x203F) && (c <= 0x2040)) || /* !start */
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))
)) {
if (count++ > 100) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
} else {
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!IS_LETTER(c) && (c != '_') &&
(c != ':'))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))) {
if (count++ > 100) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
}
if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
| 171,297
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: setv4key_principal_2_svc(setv4key_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;
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->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_SETKEY, arg->princ, NULL)) {
ret.code = kadm5_setv4key_principal((void *)handle, arg->princ,
arg->keyblock);
} else {
log_unauth("kadm5_setv4key_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_SETKEY;
}
if(ret.code != KADM5_AUTH_SETKEY) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_setv4key_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
|
setv4key_principal_2_svc(setv4key_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;
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->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_SETKEY, arg->princ, NULL)) {
ret.code = kadm5_setv4key_principal((void *)handle, arg->princ,
arg->keyblock);
} else {
log_unauth("kadm5_setv4key_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_SETKEY;
}
if(ret.code != KADM5_AUTH_SETKEY) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_setv4key_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,527
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
int step=n/book->dim;
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j,o;
if (!v) return -1;
for (j=0;j<step;j++){
if(decode_map(book,b,v,point))return -1;
for(i=0,o=j;i<book->dim;i++,o+=step)
a[o]+=v[i];
}
}
return 0;
}
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
|
long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
int step=n/book->dim;
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j,o;
if (!v) return -1;
for (j=0;j<step;j++){
if(decode_map(book,b,v,point))return -1;
for(i=0,o=j;i<book->dim;i++,o+=step)
a[o]+=v[i];
}
}
return 0;
}
| 173,988
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: fm_mgr_config_init
(
OUT p_fm_config_conx_hdlt *p_hdl,
IN int instance,
OPTIONAL IN char *rem_address,
OPTIONAL IN char *community
)
{
fm_config_conx_hdl *hdl;
fm_mgr_config_errno_t res = FM_CONF_OK;
if ( (hdl = calloc(1,sizeof(fm_config_conx_hdl))) == NULL )
{
res = FM_CONF_NO_MEM;
goto cleanup;
}
hdl->instance = instance;
*p_hdl = hdl;
if(!rem_address || (strcmp(rem_address,"localhost") == 0))
{
if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_SM) == FM_CONF_INIT_ERR )
{
res = FM_CONF_INIT_ERR;
goto cleanup;
}
if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_PM) == FM_CONF_INIT_ERR )
{
res = FM_CONF_INIT_ERR;
goto cleanup;
}
if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_FE) == FM_CONF_INIT_ERR )
{
res = FM_CONF_INIT_ERR;
goto cleanup;
}
}
return res;
cleanup:
if ( hdl ) {
free(hdl);
hdl = NULL;
}
return res;
}
Commit Message: Fix scripts and code that use well-known tmp files.
CWE ID: CWE-362
|
fm_mgr_config_init
(
OUT p_fm_config_conx_hdlt *p_hdl,
IN int instance,
OPTIONAL IN char *rem_address,
OPTIONAL IN char *community
)
{
fm_config_conx_hdl *hdl;
fm_mgr_config_errno_t res = FM_CONF_OK;
if ( (hdl = calloc(1,sizeof(fm_config_conx_hdl))) == NULL )
{
res = FM_CONF_NO_MEM;
goto cleanup;
}
hdl->instance = instance;
*p_hdl = hdl;
if(!rem_address || (strcmp(rem_address,"localhost") == 0))
{
if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_SM) == FM_CONF_INIT_ERR )
{
res = FM_CONF_INIT_ERR;
goto cleanup;
}
if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_PM) == FM_CONF_INIT_ERR )
{
res = FM_CONF_INIT_ERR;
goto cleanup;
}
if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_FE) == FM_CONF_INIT_ERR )
{
res = FM_CONF_INIT_ERR;
goto cleanup;
}
}
cleanup:
return res;
}
| 170,130
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.xxpStatus = ppresXxpIncomplete;
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
CWE ID: CWE-20
|
ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
else
{
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
| 168,890
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
{
png_debug1(1, "in %s storage function", "tIME");
if (png_ptr == NULL || info_ptr == NULL ||
(png_ptr->mode & PNG_WROTE_tIME))
return;
png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof(png_time));
info_ptr->valid |= PNG_INFO_tIME;
}
Commit Message: third_party/libpng: update to 1.2.54
TBR=darin@chromium.org
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
|
png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
{
png_debug1(1, "in %s storage function", "tIME");
if (png_ptr == NULL || info_ptr == NULL ||
(png_ptr->mode & PNG_WROTE_tIME))
return;
if (mod_time->month == 0 || mod_time->month > 12 ||
mod_time->day == 0 || mod_time->day > 31 ||
mod_time->hour > 23 || mod_time->minute > 59 ||
mod_time->second > 60)
{
png_warning(png_ptr, "Ignoring invalid time value");
return;
}
png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof(png_time));
info_ptr->valid |= PNG_INFO_tIME;
}
| 172,184
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: t1_parse_font_matrix( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
FT_Int result;
result = T1_ToFixedArray( parser, 6, temp, 3 );
if ( result < 0 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale );
/* we need to scale the values by 1.0/temp_scale */
if ( temp_scale != 0x10000L )
{
temp[0] = FT_DivFix( temp[0], temp_scale );
temp[1] = FT_DivFix( temp[1], temp_scale );
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
}
Commit Message:
CWE ID: CWE-20
|
t1_parse_font_matrix( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
FT_Int result;
result = T1_ToFixedArray( parser, 6, temp, 3 );
if ( result < 6 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale );
/* we need to scale the values by 1.0/temp_scale */
if ( temp_scale != 0x10000L )
{
temp[0] = FT_DivFix( temp[0], temp_scale );
temp[1] = FT_DivFix( temp[1], temp_scale );
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
}
| 165,342
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Block::GetFrameCount() const
{
return m_frame_count;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
int Block::GetFrameCount() const
| 174,325
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::WorkerRestarted(int worker_process_id,
int worker_route_id) {
DCHECK_EQ(WORKER_TERMINATED, state_);
state_ = WORKER_NOT_READY;
worker_process_id_ = worker_process_id;
worker_route_id_ = worker_route_id;
RenderProcessHost* host = RenderProcessHost::FromID(worker_process_id_);
for (DevToolsSession* session : sessions())
session->SetRenderer(host, nullptr);
}
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 <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void ServiceWorkerDevToolsAgentHost::WorkerRestarted(int worker_process_id,
int worker_route_id) {
DCHECK_EQ(WORKER_TERMINATED, state_);
state_ = WORKER_NOT_READY;
worker_process_id_ = worker_process_id;
worker_route_id_ = worker_route_id;
for (DevToolsSession* session : sessions())
session->SetRenderer(worker_process_id_, nullptr);
}
| 172,786
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderViewHostManager::ShouldSwapProcessesForNavigation(
const NavigationEntry* curr_entry,
const NavigationEntryImpl* new_entry) const {
DCHECK(new_entry);
const GURL& current_url = (curr_entry) ? curr_entry->GetURL() :
render_view_host_->GetSiteInstance()->GetSiteURL();
BrowserContext* browser_context =
delegate_->GetControllerForRenderManager().GetBrowserContext();
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, current_url)) {
if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
browser_context, new_entry->GetURL(), false)) {
return true;
}
} else {
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, new_entry->GetURL())) {
return true;
}
}
if (GetContentClient()->browser()->ShouldSwapProcessesForNavigation(
curr_entry ? curr_entry->GetURL() : GURL(), new_entry->GetURL())) {
return true;
}
if (!curr_entry)
return false;
if (curr_entry->IsViewSourceMode() != new_entry->IsViewSourceMode())
return true;
return false;
}
Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances.
BUG=174943
TEST=Can't post message to CWS. See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/12301013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool RenderViewHostManager::ShouldSwapProcessesForNavigation(
const NavigationEntry* curr_entry,
const NavigationEntryImpl* new_entry) const {
DCHECK(new_entry);
const GURL& current_url = (curr_entry) ? curr_entry->GetURL() :
render_view_host_->GetSiteInstance()->GetSiteURL();
BrowserContext* browser_context =
delegate_->GetControllerForRenderManager().GetBrowserContext();
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, current_url)) {
if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
browser_context, new_entry->GetURL(), false)) {
return true;
}
} else {
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, new_entry->GetURL())) {
return true;
}
}
if (GetContentClient()->browser()->ShouldSwapProcessesForNavigation(
render_view_host_->GetSiteInstance(),
curr_entry ? curr_entry->GetURL() : GURL(),
new_entry->GetURL())) {
return true;
}
if (!curr_entry)
return false;
if (curr_entry->IsViewSourceMode() != new_entry->IsViewSourceMode())
return true;
return false;
}
| 171,437
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (connect(sock, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
goto error;
if (send(sock, &type, 1, 0) != 1)
goto error;
if (send(sock, &length, 2, 0) != 2)
goto error;
if (send(sock, packet, length, 0) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (TEMP_FAILURE_RETRY(connect(sock, (const struct sockaddr *)&addr, sizeof(addr))) == -1)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, &type, 1, 0)) != 1)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, &length, 2, 0)) != 2)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, packet, length, 0)) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
| 173,492
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual InputMethodDescriptor current_input_method() const {
return current_input_method_;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual InputMethodDescriptor current_input_method() const {
virtual input_method::InputMethodDescriptor current_input_method() const {
return current_input_method_;
}
| 170,513
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int main(int argc, char *argv[])
{
libettercap_init();
ef_globals_alloc();
select_text_interface();
libettercap_ui_init();
/* etterfilter copyright */
fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n",
PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS);
/* initialize the line number */
EF_GBL->lineno = 1;
/* getopt related parsing... */
parse_options(argc, argv);
/* set the input for source file */
if (EF_GBL_OPTIONS->source_file) {
yyin = fopen(EF_GBL_OPTIONS->source_file, "r");
if (yyin == NULL)
FATAL_ERROR("Input file not found !");
} else {
FATAL_ERROR("No source file.");
}
/* no buffering */
setbuf(yyin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
/* load the tables in etterfilter.tbl */
load_tables();
/* load the constants in etterfilter.cnt */
load_constants();
/* print the message */
fprintf(stdout, "\n Parsing source file \'%s\' ", EF_GBL_OPTIONS->source_file);
fflush(stdout);
ef_debug(1, "\n");
/* begin the parsing */
if (yyparse() == 0)
fprintf(stdout, " done.\n\n");
else
fprintf(stdout, "\n\nThe script contains errors...\n\n");
/* write to file */
if (write_output() != E_SUCCESS)
FATAL_ERROR("Cannot write output file (%s)", EF_GBL_OPTIONS->output_file);
ef_globals_free();
return 0;
}
Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782)
CWE ID: CWE-125
|
int main(int argc, char *argv[])
{
int ret_value = 0;
libettercap_init();
ef_globals_alloc();
select_text_interface();
libettercap_ui_init();
/* etterfilter copyright */
fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n",
PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS);
/* initialize the line number */
EF_GBL->lineno = 1;
/* getopt related parsing... */
parse_options(argc, argv);
/* set the input for source file */
if (EF_GBL_OPTIONS->source_file) {
yyin = fopen(EF_GBL_OPTIONS->source_file, "r");
if (yyin == NULL)
FATAL_ERROR("Input file not found !");
} else {
FATAL_ERROR("No source file.");
}
/* no buffering */
setbuf(yyin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
/* load the tables in etterfilter.tbl */
load_tables();
/* load the constants in etterfilter.cnt */
load_constants();
/* print the message */
fprintf(stdout, "\n Parsing source file \'%s\' ", EF_GBL_OPTIONS->source_file);
fflush(stdout);
ef_debug(1, "\n");
/* begin the parsing */
if (yyparse() == 0)
fprintf(stdout, " done.\n\n");
else
fprintf(stdout, "\n\nThe script contains errors...\n\n");
/* write to file */
ret_value = write_output();
if (ret_value == -E_NOTHANDLED)
FATAL_ERROR("Cannot write output file (%s): the filter is not correctly handled.", EF_GBL_OPTIONS->output_file);
else if (ret_value == -E_INVALID)
FATAL_ERROR("Cannot write output file (%s): the filter format is not correct. ", EF_GBL_OPTIONS->output_file);
ef_globals_free();
return 0;
}
| 168,337
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
PHP_FUNCTION( locale_get_script )
PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,182
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Predict(MB_PREDICTION_MODE mode) {
mbptr_->mode_info_context->mbmi.mode = mode;
REGISTER_STATE_CHECK(pred_fn_(mbptr_,
data_ptr_[0] - kStride,
data_ptr_[0] - 1, kStride,
data_ptr_[0], kStride));
}
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 Predict(MB_PREDICTION_MODE mode) {
mbptr_->mode_info_context->mbmi.mode = mode;
ASM_REGISTER_STATE_CHECK(pred_fn_(mbptr_,
data_ptr_[0] - kStride,
data_ptr_[0] - 1, kStride,
data_ptr_[0], kStride));
}
| 174,566
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: transform_enable(PNG_CONST char *name)
{
/* Everything starts out enabled, so if we see an 'enable' disabled
* everything else the first time round.
*/
static int all_disabled = 0;
int found_it = 0;
image_transform *list = image_transform_first;
while (list != &image_transform_end)
{
if (strcmp(list->name, name) == 0)
{
list->enable = 1;
found_it = 1;
}
else if (!all_disabled)
list->enable = 0;
list = list->list;
}
all_disabled = 1;
if (!found_it)
{
fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
name);
exit(99);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
transform_enable(PNG_CONST char *name)
image_transform_png_set_invert_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type & 4)
that->alpha_inverted = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_invert_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* Only has an effect on pixels with alpha: */
return (colour_type & 4) != 0;
}
IT(invert_alpha);
#undef PT
#define PT ITSTRUCT(invert_alpha)
#endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
/* png_set_bgr */
#ifdef PNG_READ_BGR_SUPPORTED
/* Swap R,G,B channels to order B,G,R.
*
* png_set_bgr(png_structrp png_ptr)
*
* This only has an effect on RGB and RGBA pixels.
*/
static void
image_transform_png_set_bgr_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_bgr(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_bgr_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_RGBA)
that->swap_rgb = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_bgr_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_RGBA;
}
IT(bgr);
#undef PT
#define PT ITSTRUCT(bgr)
#endif /* PNG_READ_BGR_SUPPORTED */
/* png_set_swap_alpha */
#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
/* Put the alpha channel first.
*
* png_set_swap_alpha(png_structrp png_ptr)
*
* This only has an effect on GA and RGBA pixels.
*/
static void
image_transform_png_set_swap_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_swap_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_swap_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_GA ||
that->colour_type == PNG_COLOR_TYPE_RGBA)
that->alpha_first = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_swap_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type == PNG_COLOR_TYPE_GA ||
colour_type == PNG_COLOR_TYPE_RGBA;
}
IT(swap_alpha);
#undef PT
#define PT ITSTRUCT(swap_alpha)
#endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
/* png_set_swap */
#ifdef PNG_READ_SWAP_SUPPORTED
/* Byte swap 16-bit components.
*
* png_set_swap(png_structrp png_ptr)
*/
static void
image_transform_png_set_swap_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_swap(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_swap_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth == 16)
that->swap16 = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_swap_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth == 16;
}
IT(swap);
#undef PT
#define PT ITSTRUCT(swap)
#endif /* PNG_READ_SWAP_SUPPORTED */
#ifdef PNG_READ_FILLER_SUPPORTED
/* Add a filler byte to 8-bit Gray or 24-bit RGB images.
*
* png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
*
* Flags:
*
* PNG_FILLER_BEFORE
* PNG_FILLER_AFTER
*/
#define data ITDATA(filler)
static struct
{
png_uint_32 filler;
int flags;
} data;
static void
image_transform_png_set_filler_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Need a random choice for 'before' and 'after' as well as for the
* filler. The 'filler' value has all 32 bits set, but only bit_depth
* will be used. At this point we don't know bit_depth.
*/
RANDOMIZE(data.filler);
data.flags = random_choice();
png_set_filler(pp, data.filler, data.flags);
/* The standard display handling stuff also needs to know that
* there is a filler, so set that here.
*/
that->this.filler = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_filler_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth >= 8 &&
(that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_GRAY))
{
const unsigned int max = (1U << that->bit_depth)-1;
that->alpha = data.filler & max;
that->alphaf = ((double)that->alpha) / max;
that->alphae = 0;
/* The filler has been stored in the alpha channel, we must record
* that this has been done for the checking later on, the color
* type is faked to have an alpha channel, but libpng won't report
* this; the app has to know the extra channel is there and this
* was recording in standard_display::filler above.
*/
that->colour_type |= 4; /* alpha added */
that->alpha_first = data.flags == PNG_FILLER_BEFORE;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_filler_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_GRAY);
}
#undef data
IT(filler);
#undef PT
#define PT ITSTRUCT(filler)
/* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
#define data ITDATA(add_alpha)
static struct
{
png_uint_32 filler;
int flags;
} data;
static void
image_transform_png_set_add_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Need a random choice for 'before' and 'after' as well as for the
* filler. The 'filler' value has all 32 bits set, but only bit_depth
* will be used. At this point we don't know bit_depth.
*/
RANDOMIZE(data.filler);
data.flags = random_choice();
png_set_add_alpha(pp, data.filler, data.flags);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_add_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth >= 8 &&
(that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_GRAY))
{
const unsigned int max = (1U << that->bit_depth)-1;
that->alpha = data.filler & max;
that->alphaf = ((double)that->alpha) / max;
that->alphae = 0;
that->colour_type |= 4; /* alpha added */
that->alpha_first = data.flags == PNG_FILLER_BEFORE;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_add_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_GRAY);
}
#undef data
IT(add_alpha);
#undef PT
#define PT ITSTRUCT(add_alpha)
#endif /* PNG_READ_FILLER_SUPPORTED */
/* png_set_packing */
#ifdef PNG_READ_PACK_SUPPORTED
/* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
*
* png_set_packing(png_structrp png_ptr)
*
* This should only affect grayscale and palette images with less than 8 bits
* per pixel.
*/
static void
image_transform_png_set_packing_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_packing(pp);
that->unpacked = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_packing_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
/* The general expand case depends on what the colour type is,
* low bit-depth pixel values are unpacked into bytes without
* scaling, so sample_depth is not changed.
*/
if (that->bit_depth < 8) /* grayscale or palette */
that->bit_depth = 8;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_packing_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* Nothing should happen unless the bit depth is less than 8: */
return bit_depth < 8;
}
IT(packing);
#undef PT
#define PT ITSTRUCT(packing)
#endif /* PNG_READ_PACK_SUPPORTED */
/* png_set_packswap */
#ifdef PNG_READ_PACKSWAP_SUPPORTED
/* Swap pixels packed into bytes; reverses the order on screen so that
* the high order bits correspond to the rightmost pixels.
*
* png_set_packswap(png_structrp png_ptr)
*/
static void
image_transform_png_set_packswap_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_packswap(pp);
that->this.littleendian = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_packswap_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth < 8)
that->littleendian = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_packswap_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth < 8;
}
IT(packswap);
#undef PT
#define PT ITSTRUCT(packswap)
#endif /* PNG_READ_PACKSWAP_SUPPORTED */
/* png_set_invert_mono */
#ifdef PNG_READ_INVERT_MONO_SUPPORTED
/* Invert the gray channel
*
* png_set_invert_mono(png_structrp png_ptr)
*/
static void
image_transform_png_set_invert_mono_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_invert_mono(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_invert_mono_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type & 4)
that->mono_inverted = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_invert_mono_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* Only has an effect on pixels with no colour: */
return (colour_type & 2) == 0;
}
IT(invert_mono);
#undef PT
#define PT ITSTRUCT(invert_mono)
#endif /* PNG_READ_INVERT_MONO_SUPPORTED */
#ifdef PNG_READ_SHIFT_SUPPORTED
/* png_set_shift(png_structp, png_const_color_8p true_bits)
*
* The output pixels will be shifted by the given true_bits
* values.
*/
#define data ITDATA(shift)
static png_color_8 data;
static void
image_transform_png_set_shift_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Get a random set of shifts. The shifts need to do something
* to test the transform, so they are limited to the bit depth
* of the input image. Notice that in the following the 'gray'
* field is randomized independently. This acts as a check that
* libpng does use the correct field.
*/
const unsigned int depth = that->this.bit_depth;
data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
png_set_shift(pp, &data);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_shift_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
/* Copy the correct values into the sBIT fields, libpng does not do
* anything to palette data:
*/
if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
{
that->sig_bits = 1;
/* The sBIT fields are reset to the values previously sent to
* png_set_shift according to the colour type.
* does.
*/
if (that->colour_type & 2) /* RGB channels */
{
that->red_sBIT = data.red;
that->green_sBIT = data.green;
that->blue_sBIT = data.blue;
}
else /* One grey channel */
that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
that->alpha_sBIT = data.alpha;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_shift_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type != PNG_COLOR_TYPE_PALETTE;
}
IT(shift);
#undef PT
#define PT ITSTRUCT(shift)
#endif /* PNG_READ_SHIFT_SUPPORTED */
#ifdef THIS_IS_THE_PROFORMA
static void
image_transform_png_set_@_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_@(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_@_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_@_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return 1;
}
IT(@);
#endif
/* This may just be 'end' if all the transforms are disabled! */
static image_transform *const image_transform_first = &PT;
static void
transform_enable(const char *name)
{
/* Everything starts out enabled, so if we see an 'enable' disabled
* everything else the first time round.
*/
static int all_disabled = 0;
int found_it = 0;
image_transform *list = image_transform_first;
while (list != &image_transform_end)
{
if (strcmp(list->name, name) == 0)
{
list->enable = 1;
found_it = 1;
}
else if (!all_disabled)
list->enable = 0;
list = list->list;
}
all_disabled = 1;
if (!found_it)
{
fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
name);
exit(99);
}
}
| 173,713
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
p += sizeof ( short );
for ( i = 0; i < string_count && i < 64; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= FT_MIN( string_count, 64 ) )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
Commit Message:
CWE ID: CWE-119
|
parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
string_count = FT_MIN( 64, string_count );
p += sizeof ( short );
for ( i = 0; i < string_count; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= string_count )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
| 164,842
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vnc_async_encoding_start(VncState *orig, VncState *local)
{
local->vnc_encoding = orig->vnc_encoding;
local->features = orig->features;
local->ds = orig->ds;
local->vd = orig->vd;
local->lossy_rect = orig->lossy_rect;
local->write_pixels = orig->write_pixels;
local->clientds = orig->clientds;
local->tight = orig->tight;
local->zlib = orig->zlib;
local->hextile = orig->hextile;
local->output = queue->buffer;
local->csock = -1; /* Don't do any network work on this thread */
buffer_reset(&local->output);
}
Commit Message:
CWE ID: CWE-125
|
static void vnc_async_encoding_start(VncState *orig, VncState *local)
{
local->vnc_encoding = orig->vnc_encoding;
local->features = orig->features;
local->ds = orig->ds;
local->vd = orig->vd;
local->lossy_rect = orig->lossy_rect;
local->write_pixels = orig->write_pixels;
local->client_pf = orig->client_pf;
local->client_be = orig->client_be;
local->tight = orig->tight;
local->zlib = orig->zlib;
local->hextile = orig->hextile;
local->output = queue->buffer;
local->csock = -1; /* Don't do any network work on this thread */
buffer_reset(&local->output);
}
| 165,469
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: l2tp_q931_cc_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
print_16bits_val(ndo, (const uint16_t *)dat);
ND_PRINT((ndo, ", %02x", dat[2]));
if (length > 3) {
ND_PRINT((ndo, " "));
print_string(ndo, dat+3, length-3);
}
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
l2tp_q931_cc_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
if (length < 3) {
ND_PRINT((ndo, "AVP too short"));
return;
}
print_16bits_val(ndo, (const uint16_t *)dat);
ND_PRINT((ndo, ", %02x", dat[2]));
dat += 3;
length -= 3;
if (length != 0) {
ND_PRINT((ndo, " "));
print_string(ndo, dat, length);
}
}
| 167,901
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
OnigCompileInfo* ci, OnigErrorInfo* einfo)
{
int r;
UChar *cpat, *cpat_end;
if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;
if (ci->pattern_enc != ci->target_enc) {
r = conv_encoding(ci->pattern_enc, ci->target_enc, pattern, pattern_end,
&cpat, &cpat_end);
if (r != 0) return r;
}
else {
cpat = (UChar* )pattern;
cpat_end = (UChar* )pattern_end;
}
*reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(*reg)) {
r = ONIGERR_MEMORY;
goto err2;
}
r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,
ci->syntax);
if (r != 0) goto err;
r = onig_compile(*reg, cpat, cpat_end, einfo);
if (r != 0) {
err:
onig_free(*reg);
*reg = NULL;
}
err2:
if (cpat != pattern) xfree(cpat);
return r;
}
Commit Message: Fix CVE-2019-13224: don't allow different encodings for onig_new_deluxe()
CWE ID: CWE-416
|
onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
OnigCompileInfo* ci, OnigErrorInfo* einfo)
{
int r;
UChar *cpat, *cpat_end;
if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;
if (ci->pattern_enc != ci->target_enc) {
return ONIGERR_NOT_SUPPORTED_ENCODING_COMBINATION;
}
else {
cpat = (UChar* )pattern;
cpat_end = (UChar* )pattern_end;
}
*reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(*reg)) {
r = ONIGERR_MEMORY;
goto err2;
}
r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,
ci->syntax);
if (r != 0) goto err;
r = onig_compile(*reg, cpat, cpat_end, einfo);
if (r != 0) {
err:
onig_free(*reg);
*reg = NULL;
}
err2:
if (cpat != pattern) xfree(cpat);
return r;
}
| 169,613
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Include U+0517 in set of Cyrillic/Latin lookalikes.
Cyrillic letter U+0517 (ԗ) looks somewhat similar to the Latin letter p.
This CL adds this character to the set of Cyrillic characters that look
like Latin characters. Domains made up entirely of Cyrillic/Latin
lookalikes are displayed as punycode in URLs.
Bug: 863663
Change-Id: I4340c48d124c9c4cd3d3b5d0f9d3865d709e082d
Reviewed-on: https://chromium-review.googlesource.com/c/1286825
Commit-Queue: Joe DeBlasio <jdeblasio@chromium.org>
Commit-Queue: Peter Kasting <pkasting@chromium.org>
Reviewed-by: Peter Kasting <pkasting@chromium.org>
Cr-Commit-Position: refs/heads/master@{#600582}
CWE ID: CWE-20
|
IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,116
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: LogLuvSetupEncode(TIFF* tif)
{
static const char module[] = "LogLuvSetupEncode";
LogLuvState* sp = EncoderState(tif);
TIFFDirectory* td = &tif->tif_dir;
switch (td->td_photometric) {
case PHOTOMETRIC_LOGLUV:
if (!LogLuvInitState(tif))
break;
if (td->td_compression == COMPRESSION_SGILOG24) {
tif->tif_encoderow = LogLuvEncode24;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = Luv24fromXYZ;
break;
case SGILOGDATAFMT_16BIT:
sp->tfunc = Luv24fromLuv48;
break;
case SGILOGDATAFMT_RAW:
break;
default:
goto notsupported;
}
} else {
tif->tif_encoderow = LogLuvEncode32;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = Luv32fromXYZ;
break;
case SGILOGDATAFMT_16BIT:
sp->tfunc = Luv32fromLuv48;
break;
case SGILOGDATAFMT_RAW:
break;
default:
goto notsupported;
}
}
break;
case PHOTOMETRIC_LOGL:
if (!LogL16InitState(tif))
break;
tif->tif_encoderow = LogL16Encode;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = L16fromY;
break;
case SGILOGDATAFMT_16BIT:
break;
default:
goto notsupported;
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Inappropriate photometric interpretation %d for SGILog compression; %s",
td->td_photometric, "must be either LogLUV or LogL");
break;
}
return (1);
notsupported:
TIFFErrorExt(tif->tif_clientdata, module,
"SGILog compression supported only for %s, or raw data",
td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
return (0);
}
Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer
overflow on generation of PixarLog / LUV compressed files, with
ColorMap, TransferFunction attached and nasty plays with bitspersample.
The fix for LUV has not been tested, but suffers from the same kind
of issue of PixarLog.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604
CWE ID: CWE-125
|
LogLuvSetupEncode(TIFF* tif)
{
static const char module[] = "LogLuvSetupEncode";
LogLuvState* sp = EncoderState(tif);
TIFFDirectory* td = &tif->tif_dir;
switch (td->td_photometric) {
case PHOTOMETRIC_LOGLUV:
if (!LogLuvInitState(tif))
break;
if (td->td_compression == COMPRESSION_SGILOG24) {
tif->tif_encoderow = LogLuvEncode24;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = Luv24fromXYZ;
break;
case SGILOGDATAFMT_16BIT:
sp->tfunc = Luv24fromLuv48;
break;
case SGILOGDATAFMT_RAW:
break;
default:
goto notsupported;
}
} else {
tif->tif_encoderow = LogLuvEncode32;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = Luv32fromXYZ;
break;
case SGILOGDATAFMT_16BIT:
sp->tfunc = Luv32fromLuv48;
break;
case SGILOGDATAFMT_RAW:
break;
default:
goto notsupported;
}
}
break;
case PHOTOMETRIC_LOGL:
if (!LogL16InitState(tif))
break;
tif->tif_encoderow = LogL16Encode;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = L16fromY;
break;
case SGILOGDATAFMT_16BIT:
break;
default:
goto notsupported;
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Inappropriate photometric interpretation %d for SGILog compression; %s",
td->td_photometric, "must be either LogLUV or LogL");
break;
}
sp->encoder_state = 1;
return (1);
notsupported:
TIFFErrorExt(tif->tif_clientdata, module,
"SGILog compression supported only for %s, or raw data",
td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
return (0);
}
| 168,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: static int dcbnl_ieee_fill(struct sk_buff *skb, struct net_device *netdev)
{
struct nlattr *ieee, *app;
struct dcb_app_type *itr;
const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops;
int dcbx;
int err;
if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name))
return -EMSGSIZE;
ieee = nla_nest_start(skb, DCB_ATTR_IEEE);
if (!ieee)
return -EMSGSIZE;
if (ops->ieee_getets) {
struct ieee_ets ets;
err = ops->ieee_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_getmaxrate) {
struct ieee_maxrate maxrate;
err = ops->ieee_getmaxrate(netdev, &maxrate);
if (!err) {
err = nla_put(skb, DCB_ATTR_IEEE_MAXRATE,
sizeof(maxrate), &maxrate);
if (err)
return -EMSGSIZE;
}
}
if (ops->ieee_getpfc) {
struct ieee_pfc pfc;
err = ops->ieee_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
app = nla_nest_start(skb, DCB_ATTR_IEEE_APP_TABLE);
if (!app)
return -EMSGSIZE;
spin_lock(&dcb_lock);
list_for_each_entry(itr, &dcb_app_list, list) {
if (itr->ifindex == netdev->ifindex) {
err = nla_put(skb, DCB_ATTR_IEEE_APP, sizeof(itr->app),
&itr->app);
if (err) {
spin_unlock(&dcb_lock);
return -EMSGSIZE;
}
}
}
if (netdev->dcbnl_ops->getdcbx)
dcbx = netdev->dcbnl_ops->getdcbx(netdev);
else
dcbx = -EOPNOTSUPP;
spin_unlock(&dcb_lock);
nla_nest_end(skb, app);
/* get peer info if available */
if (ops->ieee_peer_getets) {
struct ieee_ets ets;
err = ops->ieee_peer_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_peer_getpfc) {
struct ieee_pfc pfc;
err = ops->ieee_peer_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
if (ops->peer_getappinfo && ops->peer_getapptable) {
err = dcbnl_build_peer_app(netdev, skb,
DCB_ATTR_IEEE_PEER_APP,
DCB_ATTR_IEEE_APP_UNSPEC,
DCB_ATTR_IEEE_APP);
if (err)
return -EMSGSIZE;
}
nla_nest_end(skb, ieee);
if (dcbx >= 0) {
err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx);
if (err)
return -EMSGSIZE;
}
return 0;
}
Commit Message: dcbnl: fix various netlink info leaks
The dcb netlink interface leaks stack memory in various places:
* perm_addr[] buffer is only filled at max with 12 of the 32 bytes but
copied completely,
* no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand,
so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes
for ieee_pfc structs, etc.,
* the same is true for CEE -- no in-kernel driver fills the whole
struct,
Prevent all of the above stack info leaks by properly initializing the
buffers/structures involved.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-399
|
static int dcbnl_ieee_fill(struct sk_buff *skb, struct net_device *netdev)
{
struct nlattr *ieee, *app;
struct dcb_app_type *itr;
const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops;
int dcbx;
int err;
if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name))
return -EMSGSIZE;
ieee = nla_nest_start(skb, DCB_ATTR_IEEE);
if (!ieee)
return -EMSGSIZE;
if (ops->ieee_getets) {
struct ieee_ets ets;
memset(&ets, 0, sizeof(ets));
err = ops->ieee_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_getmaxrate) {
struct ieee_maxrate maxrate;
memset(&maxrate, 0, sizeof(maxrate));
err = ops->ieee_getmaxrate(netdev, &maxrate);
if (!err) {
err = nla_put(skb, DCB_ATTR_IEEE_MAXRATE,
sizeof(maxrate), &maxrate);
if (err)
return -EMSGSIZE;
}
}
if (ops->ieee_getpfc) {
struct ieee_pfc pfc;
memset(&pfc, 0, sizeof(pfc));
err = ops->ieee_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
app = nla_nest_start(skb, DCB_ATTR_IEEE_APP_TABLE);
if (!app)
return -EMSGSIZE;
spin_lock(&dcb_lock);
list_for_each_entry(itr, &dcb_app_list, list) {
if (itr->ifindex == netdev->ifindex) {
err = nla_put(skb, DCB_ATTR_IEEE_APP, sizeof(itr->app),
&itr->app);
if (err) {
spin_unlock(&dcb_lock);
return -EMSGSIZE;
}
}
}
if (netdev->dcbnl_ops->getdcbx)
dcbx = netdev->dcbnl_ops->getdcbx(netdev);
else
dcbx = -EOPNOTSUPP;
spin_unlock(&dcb_lock);
nla_nest_end(skb, app);
/* get peer info if available */
if (ops->ieee_peer_getets) {
struct ieee_ets ets;
memset(&ets, 0, sizeof(ets));
err = ops->ieee_peer_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_peer_getpfc) {
struct ieee_pfc pfc;
memset(&pfc, 0, sizeof(pfc));
err = ops->ieee_peer_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
if (ops->peer_getappinfo && ops->peer_getapptable) {
err = dcbnl_build_peer_app(netdev, skb,
DCB_ATTR_IEEE_PEER_APP,
DCB_ATTR_IEEE_APP_UNSPEC,
DCB_ATTR_IEEE_APP);
if (err)
return -EMSGSIZE;
}
nla_nest_end(skb, ieee);
if (dcbx >= 0) {
err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx);
if (err)
return -EMSGSIZE;
}
return 0;
}
| 166,059
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 adev_open_output_stream(struct audio_hw_device *dev,
audio_io_handle_t handle,
audio_devices_t devices,
audio_output_flags_t flags,
struct audio_config *config,
struct audio_stream_out **stream_out,
const char *address)
{
struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
struct a2dp_stream_out *out;
int ret = 0;
int i;
UNUSED(address);
UNUSED(handle);
UNUSED(devices);
UNUSED(flags);
INFO("opening output");
out = (struct a2dp_stream_out *)calloc(1, sizeof(struct a2dp_stream_out));
if (!out)
return -ENOMEM;
out->stream.common.get_sample_rate = out_get_sample_rate;
out->stream.common.set_sample_rate = out_set_sample_rate;
out->stream.common.get_buffer_size = out_get_buffer_size;
out->stream.common.get_channels = out_get_channels;
out->stream.common.get_format = out_get_format;
out->stream.common.set_format = out_set_format;
out->stream.common.standby = out_standby;
out->stream.common.dump = out_dump;
out->stream.common.set_parameters = out_set_parameters;
out->stream.common.get_parameters = out_get_parameters;
out->stream.common.add_audio_effect = out_add_audio_effect;
out->stream.common.remove_audio_effect = out_remove_audio_effect;
out->stream.get_latency = out_get_latency;
out->stream.set_volume = out_set_volume;
out->stream.write = out_write;
out->stream.get_render_position = out_get_render_position;
out->stream.get_presentation_position = out_get_presentation_position;
/* initialize a2dp specifics */
a2dp_stream_common_init(&out->common);
out->common.cfg.channel_flags = AUDIO_STREAM_DEFAULT_CHANNEL_FLAG;
out->common.cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
out->common.cfg.rate = AUDIO_STREAM_DEFAULT_RATE;
/* set output config values */
if (config)
{
config->format = out_get_format((const struct audio_stream *)&out->stream);
config->sample_rate = out_get_sample_rate((const struct audio_stream *)&out->stream);
config->channel_mask = out_get_channels((const struct audio_stream *)&out->stream);
}
*stream_out = &out->stream;
a2dp_dev->output = out;
a2dp_open_ctrl_path(&out->common);
if (out->common.ctrl_fd == AUDIO_SKT_DISCONNECTED)
{
ERROR("ctrl socket failed to connect (%s)", strerror(errno));
ret = -1;
goto err_open;
}
DEBUG("success");
/* Delay to ensure Headset is in proper state when START is initiated
from DUT immediately after the connection due to ongoing music playback. */
usleep(250000);
return 0;
err_open:
free(out);
*stream_out = NULL;
a2dp_dev->output = NULL;
ERROR("failed");
return ret;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static int adev_open_output_stream(struct audio_hw_device *dev,
audio_io_handle_t handle,
audio_devices_t devices,
audio_output_flags_t flags,
struct audio_config *config,
struct audio_stream_out **stream_out,
const char *address)
{
struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
struct a2dp_stream_out *out;
int ret = 0;
int i;
UNUSED(address);
UNUSED(handle);
UNUSED(devices);
UNUSED(flags);
INFO("opening output");
out = (struct a2dp_stream_out *)calloc(1, sizeof(struct a2dp_stream_out));
if (!out)
return -ENOMEM;
out->stream.common.get_sample_rate = out_get_sample_rate;
out->stream.common.set_sample_rate = out_set_sample_rate;
out->stream.common.get_buffer_size = out_get_buffer_size;
out->stream.common.get_channels = out_get_channels;
out->stream.common.get_format = out_get_format;
out->stream.common.set_format = out_set_format;
out->stream.common.standby = out_standby;
out->stream.common.dump = out_dump;
out->stream.common.set_parameters = out_set_parameters;
out->stream.common.get_parameters = out_get_parameters;
out->stream.common.add_audio_effect = out_add_audio_effect;
out->stream.common.remove_audio_effect = out_remove_audio_effect;
out->stream.get_latency = out_get_latency;
out->stream.set_volume = out_set_volume;
out->stream.write = out_write;
out->stream.get_render_position = out_get_render_position;
out->stream.get_presentation_position = out_get_presentation_position;
/* initialize a2dp specifics */
a2dp_stream_common_init(&out->common);
out->common.cfg.channel_flags = AUDIO_STREAM_DEFAULT_CHANNEL_FLAG;
out->common.cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
out->common.cfg.rate = AUDIO_STREAM_DEFAULT_RATE;
/* set output config values */
if (config)
{
config->format = out_get_format((const struct audio_stream *)&out->stream);
config->sample_rate = out_get_sample_rate((const struct audio_stream *)&out->stream);
config->channel_mask = out_get_channels((const struct audio_stream *)&out->stream);
}
*stream_out = &out->stream;
a2dp_dev->output = out;
a2dp_open_ctrl_path(&out->common);
if (out->common.ctrl_fd == AUDIO_SKT_DISCONNECTED)
{
ERROR("ctrl socket failed to connect (%s)", strerror(errno));
ret = -1;
goto err_open;
}
DEBUG("success");
/* Delay to ensure Headset is in proper state when START is initiated
from DUT immediately after the connection due to ongoing music playback. */
TEMP_FAILURE_RETRY(usleep(250000));
return 0;
err_open:
free(out);
*stream_out = NULL;
a2dp_dev->output = NULL;
ERROR("failed");
return ret;
}
| 173,425
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
#ifdef AUTOKEY
filegen_register(statsdir, "cryptostats", &cryptostats);
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
filegen_register(statsdir, "timingstats", &timingstats);
#endif /* DEBUG_TIMING */
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
Commit Message: [Bug 1773] openssl not detected during ./configure.
[Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL.
CWE ID: CWE-20
|
init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
filegen_register(statsdir, "cryptostats", &cryptostats);
filegen_register(statsdir, "timingstats", &timingstats);
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
| 168,876
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Response StorageHandler::TrackCacheStorageForOrigin(const std::string& origin) {
if (!process_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&CacheStorageObserver::TrackOriginOnIOThread,
base::Unretained(GetCacheStorageObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
Response StorageHandler::TrackCacheStorageForOrigin(const std::string& origin) {
if (!storage_partition_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&CacheStorageObserver::TrackOriginOnIOThread,
base::Unretained(GetCacheStorageObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
| 172,776
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: lha_read_file_header_1(struct archive_read *a, struct lha *lha)
{
const unsigned char *p;
size_t extdsize;
int i, err, err2;
int namelen, padding;
unsigned char headersum, sum_calculated;
err = ARCHIVE_OK;
if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)
return (truncated_error(a));
lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;
headersum = p[H1_HEADER_SUM_OFFSET];
/* Note: An extended header size is included in a compsize. */
lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);
lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);
lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);
namelen = p[H1_NAME_LEN_OFFSET];
/* Calculate a padding size. The result will be normally 0 only(?) */
padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;
if (namelen > 230 || padding < 0)
goto invalid;
if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)
return (truncated_error(a));
for (i = 0; i < namelen; i++) {
if (p[i + H1_FILE_NAME_OFFSET] == 0xff)
goto invalid;/* Invalid filename. */
}
archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);
lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);
lha->setflag |= CRC_IS_SET;
sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);
/* Consume used bytes but not include `next header size' data
* since it will be consumed in lha_read_file_extended_header(). */
__archive_read_consume(a, lha->header_size - 2);
/* Read extended headers */
err2 = lha_read_file_extended_header(a, lha, NULL, 2,
(size_t)(lha->compsize + 2), &extdsize);
if (err2 < ARCHIVE_WARN)
return (err2);
if (err2 < err)
err = err2;
/* Get a real compressed file size. */
lha->compsize -= extdsize - 2;
if (sum_calculated != headersum) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"LHa header sum error");
return (ARCHIVE_FATAL);
}
return (err);
invalid:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid LHa header");
return (ARCHIVE_FATAL);
}
Commit Message: Fail with negative lha->compsize in lha_read_file_header_1()
Fixes a heap buffer overflow reported in Secunia SA74169
CWE ID: CWE-125
|
lha_read_file_header_1(struct archive_read *a, struct lha *lha)
{
const unsigned char *p;
size_t extdsize;
int i, err, err2;
int namelen, padding;
unsigned char headersum, sum_calculated;
err = ARCHIVE_OK;
if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)
return (truncated_error(a));
lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;
headersum = p[H1_HEADER_SUM_OFFSET];
/* Note: An extended header size is included in a compsize. */
lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);
lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);
lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);
namelen = p[H1_NAME_LEN_OFFSET];
/* Calculate a padding size. The result will be normally 0 only(?) */
padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;
if (namelen > 230 || padding < 0)
goto invalid;
if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)
return (truncated_error(a));
for (i = 0; i < namelen; i++) {
if (p[i + H1_FILE_NAME_OFFSET] == 0xff)
goto invalid;/* Invalid filename. */
}
archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);
lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);
lha->setflag |= CRC_IS_SET;
sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);
/* Consume used bytes but not include `next header size' data
* since it will be consumed in lha_read_file_extended_header(). */
__archive_read_consume(a, lha->header_size - 2);
/* Read extended headers */
err2 = lha_read_file_extended_header(a, lha, NULL, 2,
(size_t)(lha->compsize + 2), &extdsize);
if (err2 < ARCHIVE_WARN)
return (err2);
if (err2 < err)
err = err2;
/* Get a real compressed file size. */
lha->compsize -= extdsize - 2;
if (lha->compsize < 0)
goto invalid; /* Invalid compressed file size */
if (sum_calculated != headersum) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"LHa header sum error");
return (ARCHIVE_FATAL);
}
return (err);
invalid:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid LHa header");
return (ARCHIVE_FATAL);
}
| 168,381
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: modifier_current_encoding(PNG_CONST png_modifier *pm, color_encoding *ce)
{
if (pm->current_encoding != 0)
*ce = *pm->current_encoding;
else
memset(ce, 0, sizeof *ce);
ce->gamma = pm->current_gamma;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
modifier_current_encoding(PNG_CONST png_modifier *pm, color_encoding *ce)
modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
{
if (pm->current_encoding != 0)
*ce = *pm->current_encoding;
else
memset(ce, 0, sizeof *ce);
ce->gamma = pm->current_gamma;
}
| 173,669
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int get_gate_page(struct mm_struct *mm, unsigned long address,
unsigned int gup_flags, struct vm_area_struct **vma,
struct page **page)
{
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
int ret = -EFAULT;
/* user gate pages are read-only */
if (gup_flags & FOLL_WRITE)
return -EFAULT;
if (address > TASK_SIZE)
pgd = pgd_offset_k(address);
else
pgd = pgd_offset_gate(mm, address);
BUG_ON(pgd_none(*pgd));
p4d = p4d_offset(pgd, address);
BUG_ON(p4d_none(*p4d));
pud = pud_offset(p4d, address);
BUG_ON(pud_none(*pud));
pmd = pmd_offset(pud, address);
if (!pmd_present(*pmd))
return -EFAULT;
VM_BUG_ON(pmd_trans_huge(*pmd));
pte = pte_offset_map(pmd, address);
if (pte_none(*pte))
goto unmap;
*vma = get_gate_vma(mm);
if (!page)
goto out;
*page = vm_normal_page(*vma, address, *pte);
if (!*page) {
if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
goto unmap;
*page = pte_page(*pte);
/*
* This should never happen (a device public page in the gate
* area).
*/
if (is_device_public_page(*page))
goto unmap;
}
get_page(*page);
out:
ret = 0;
unmap:
pte_unmap(pte);
return ret;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416
|
static int get_gate_page(struct mm_struct *mm, unsigned long address,
unsigned int gup_flags, struct vm_area_struct **vma,
struct page **page)
{
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
int ret = -EFAULT;
/* user gate pages are read-only */
if (gup_flags & FOLL_WRITE)
return -EFAULT;
if (address > TASK_SIZE)
pgd = pgd_offset_k(address);
else
pgd = pgd_offset_gate(mm, address);
BUG_ON(pgd_none(*pgd));
p4d = p4d_offset(pgd, address);
BUG_ON(p4d_none(*p4d));
pud = pud_offset(p4d, address);
BUG_ON(pud_none(*pud));
pmd = pmd_offset(pud, address);
if (!pmd_present(*pmd))
return -EFAULT;
VM_BUG_ON(pmd_trans_huge(*pmd));
pte = pte_offset_map(pmd, address);
if (pte_none(*pte))
goto unmap;
*vma = get_gate_vma(mm);
if (!page)
goto out;
*page = vm_normal_page(*vma, address, *pte);
if (!*page) {
if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
goto unmap;
*page = pte_page(*pte);
/*
* This should never happen (a device public page in the gate
* area).
*/
if (is_device_public_page(*page))
goto unmap;
}
if (unlikely(!try_get_page(*page))) {
ret = -ENOMEM;
goto unmap;
}
out:
ret = 0;
unmap:
pte_unmap(pte);
return ret;
}
| 170,224
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 drm_mode_dirtyfb_ioctl(struct drm_device *dev,
void *data, struct drm_file *file_priv)
{
struct drm_clip_rect __user *clips_ptr;
struct drm_clip_rect *clips = NULL;
struct drm_mode_fb_dirty_cmd *r = data;
struct drm_mode_object *obj;
struct drm_framebuffer *fb;
unsigned flags;
int num_clips;
int ret = 0;
if (!drm_core_check_feature(dev, DRIVER_MODESET))
return -EINVAL;
mutex_lock(&dev->mode_config.mutex);
obj = drm_mode_object_find(dev, r->fb_id, DRM_MODE_OBJECT_FB);
if (!obj) {
DRM_ERROR("invalid framebuffer id\n");
ret = -EINVAL;
goto out_err1;
}
fb = obj_to_fb(obj);
num_clips = r->num_clips;
clips_ptr = (struct drm_clip_rect *)(unsigned long)r->clips_ptr;
if (!num_clips != !clips_ptr) {
ret = -EINVAL;
goto out_err1;
}
flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
/* If userspace annotates copy, clips must come in pairs */
if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
ret = -EINVAL;
goto out_err1;
}
if (num_clips && clips_ptr) {
clips = kzalloc(num_clips * sizeof(*clips), GFP_KERNEL);
if (!clips) {
ret = -ENOMEM;
goto out_err1;
}
ret = copy_from_user(clips, clips_ptr,
num_clips * sizeof(*clips));
if (ret) {
ret = -EFAULT;
goto out_err2;
}
}
if (fb->funcs->dirty) {
ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
clips, num_clips);
} else {
ret = -ENOSYS;
goto out_err2;
}
out_err2:
kfree(clips);
out_err1:
mutex_unlock(&dev->mode_config.mutex);
return ret;
}
Commit Message: drm: integer overflow in drm_mode_dirtyfb_ioctl()
There is a potential integer overflow in drm_mode_dirtyfb_ioctl()
if userspace passes in a large num_clips. The call to kmalloc would
allocate a small buffer, and the call to fb->funcs->dirty may result
in a memory corruption.
Reported-by: Haogang Chen <haogangchen@gmail.com>
Signed-off-by: Xi Wang <xi.wang@gmail.com>
Cc: stable@kernel.org
Signed-off-by: Dave Airlie <airlied@redhat.com>
CWE ID: CWE-189
|
int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
void *data, struct drm_file *file_priv)
{
struct drm_clip_rect __user *clips_ptr;
struct drm_clip_rect *clips = NULL;
struct drm_mode_fb_dirty_cmd *r = data;
struct drm_mode_object *obj;
struct drm_framebuffer *fb;
unsigned flags;
int num_clips;
int ret = 0;
if (!drm_core_check_feature(dev, DRIVER_MODESET))
return -EINVAL;
mutex_lock(&dev->mode_config.mutex);
obj = drm_mode_object_find(dev, r->fb_id, DRM_MODE_OBJECT_FB);
if (!obj) {
DRM_ERROR("invalid framebuffer id\n");
ret = -EINVAL;
goto out_err1;
}
fb = obj_to_fb(obj);
num_clips = r->num_clips;
clips_ptr = (struct drm_clip_rect *)(unsigned long)r->clips_ptr;
if (!num_clips != !clips_ptr) {
ret = -EINVAL;
goto out_err1;
}
flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
/* If userspace annotates copy, clips must come in pairs */
if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
ret = -EINVAL;
goto out_err1;
}
if (num_clips && clips_ptr) {
if (num_clips < 0 || num_clips > DRM_MODE_FB_DIRTY_MAX_CLIPS) {
ret = -EINVAL;
goto out_err1;
}
clips = kzalloc(num_clips * sizeof(*clips), GFP_KERNEL);
if (!clips) {
ret = -ENOMEM;
goto out_err1;
}
ret = copy_from_user(clips, clips_ptr,
num_clips * sizeof(*clips));
if (ret) {
ret = -EFAULT;
goto out_err2;
}
}
if (fb->funcs->dirty) {
ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
clips, num_clips);
} else {
ret = -ENOSYS;
goto out_err2;
}
out_err2:
kfree(clips);
out_err1:
mutex_unlock(&dev->mode_config.mutex);
return ret;
}
| 165,655
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(SplFileInfo, getPathInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
int path_len;
char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC);
if (path) {
char *dpath = estrndup(path, path_len);
path_len = php_dirname(dpath, path_len);
spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC);
efree(dpath);
}
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileInfo, getPathInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
int path_len;
char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC);
if (path) {
char *dpath = estrndup(path, path_len);
path_len = php_dirname(dpath, path_len);
spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC);
efree(dpath);
}
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
| 167,043
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 send_write(struct svcxprt_rdma *xprt, struct svc_rqst *rqstp,
u32 rmr, u64 to,
u32 xdr_off, int write_len,
struct svc_rdma_req_map *vec)
{
struct ib_rdma_wr write_wr;
struct ib_sge *sge;
int xdr_sge_no;
int sge_no;
int sge_bytes;
int sge_off;
int bc;
struct svc_rdma_op_ctxt *ctxt;
if (vec->count > RPCSVC_MAXPAGES) {
pr_err("svcrdma: Too many pages (%lu)\n", vec->count);
return -EIO;
}
dprintk("svcrdma: RDMA_WRITE rmr=%x, to=%llx, xdr_off=%d, "
"write_len=%d, vec->sge=%p, vec->count=%lu\n",
rmr, (unsigned long long)to, xdr_off,
write_len, vec->sge, vec->count);
ctxt = svc_rdma_get_context(xprt);
ctxt->direction = DMA_TO_DEVICE;
sge = ctxt->sge;
/* Find the SGE associated with xdr_off */
for (bc = xdr_off, xdr_sge_no = 1; bc && xdr_sge_no < vec->count;
xdr_sge_no++) {
if (vec->sge[xdr_sge_no].iov_len > bc)
break;
bc -= vec->sge[xdr_sge_no].iov_len;
}
sge_off = bc;
bc = write_len;
sge_no = 0;
/* Copy the remaining SGE */
while (bc != 0) {
sge_bytes = min_t(size_t,
bc, vec->sge[xdr_sge_no].iov_len-sge_off);
sge[sge_no].length = sge_bytes;
sge[sge_no].addr =
dma_map_xdr(xprt, &rqstp->rq_res, xdr_off,
sge_bytes, DMA_TO_DEVICE);
xdr_off += sge_bytes;
if (ib_dma_mapping_error(xprt->sc_cm_id->device,
sge[sge_no].addr))
goto err;
svc_rdma_count_mappings(xprt, ctxt);
sge[sge_no].lkey = xprt->sc_pd->local_dma_lkey;
ctxt->count++;
sge_off = 0;
sge_no++;
xdr_sge_no++;
if (xdr_sge_no > vec->count) {
pr_err("svcrdma: Too many sges (%d)\n", xdr_sge_no);
goto err;
}
bc -= sge_bytes;
if (sge_no == xprt->sc_max_sge)
break;
}
/* Prepare WRITE WR */
memset(&write_wr, 0, sizeof write_wr);
ctxt->cqe.done = svc_rdma_wc_write;
write_wr.wr.wr_cqe = &ctxt->cqe;
write_wr.wr.sg_list = &sge[0];
write_wr.wr.num_sge = sge_no;
write_wr.wr.opcode = IB_WR_RDMA_WRITE;
write_wr.wr.send_flags = IB_SEND_SIGNALED;
write_wr.rkey = rmr;
write_wr.remote_addr = to;
/* Post It */
atomic_inc(&rdma_stat_write);
if (svc_rdma_send(xprt, &write_wr.wr))
goto err;
return write_len - bc;
err:
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 0);
return -EIO;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
static int send_write(struct svcxprt_rdma *xprt, struct svc_rqst *rqstp,
static int svc_rdma_dma_map_page(struct svcxprt_rdma *rdma,
struct svc_rdma_op_ctxt *ctxt,
unsigned int sge_no,
struct page *page,
unsigned int offset,
unsigned int len)
{
struct ib_device *dev = rdma->sc_cm_id->device;
dma_addr_t dma_addr;
dma_addr = ib_dma_map_page(dev, page, offset, len, DMA_TO_DEVICE);
if (ib_dma_mapping_error(dev, dma_addr))
return -EIO;
ctxt->sge[sge_no].addr = dma_addr;
ctxt->sge[sge_no].length = len;
ctxt->sge[sge_no].lkey = rdma->sc_pd->local_dma_lkey;
svc_rdma_count_mappings(rdma, ctxt);
return 0;
}
/**
* svc_rdma_map_reply_hdr - DMA map the transport header buffer
* @rdma: controlling transport
* @ctxt: op_ctxt for the Send WR
* @rdma_resp: buffer containing transport header
* @len: length of transport header
*
* Returns:
* %0 if the header is DMA mapped,
* %-EIO if DMA mapping failed.
*/
int svc_rdma_map_reply_hdr(struct svcxprt_rdma *rdma,
struct svc_rdma_op_ctxt *ctxt,
__be32 *rdma_resp,
unsigned int len)
{
ctxt->direction = DMA_TO_DEVICE;
ctxt->pages[0] = virt_to_page(rdma_resp);
ctxt->count = 1;
return svc_rdma_dma_map_page(rdma, ctxt, 0, ctxt->pages[0], 0, len);
}
| 168,169
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: cJSON *cJSON_CreateFloat( double num )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_Number;
item->valuefloat = num;
item->valueint = num;
}
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
cJSON *cJSON_CreateFloat( double num )
| 167,272
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void OnGetDevicesOnServiceThread(
const std::vector<UsbDeviceFilter>& filters,
const base::Callback<void(mojo::Array<DeviceInfoPtr>)>& callback,
scoped_refptr<base::TaskRunner> callback_task_runner,
const std::vector<scoped_refptr<UsbDevice>>& devices) {
mojo::Array<DeviceInfoPtr> mojo_devices(0);
for (size_t i = 0; i < devices.size(); ++i) {
if (UsbDeviceFilter::MatchesAny(devices[i], filters))
mojo_devices.push_back(DeviceInfo::From(*devices[i]));
}
callback_task_runner->PostTask(
FROM_HERE, base::Bind(callback, base::Passed(&mojo_devices)));
}
Commit Message: Connect WebUSB client interface to the devices app
This provides a basic WebUSB client interface in
content/renderer. Most of the interface is unimplemented,
but this CL hooks up navigator.usb.getDevices() to the
browser's Mojo devices app to enumerate available USB
devices.
BUG=492204
Review URL: https://codereview.chromium.org/1293253002
Cr-Commit-Position: refs/heads/master@{#344881}
CWE ID: CWE-399
|
void OnGetDevicesOnServiceThread(
const std::vector<UsbDeviceFilter>& filters,
const base::Callback<void(mojo::Array<DeviceInfoPtr>)>& callback,
scoped_refptr<base::TaskRunner> callback_task_runner,
const std::vector<scoped_refptr<UsbDevice>>& devices) {
mojo::Array<DeviceInfoPtr> mojo_devices(0);
for (size_t i = 0; i < devices.size(); ++i) {
if (UsbDeviceFilter::MatchesAny(devices[i], filters) || filters.empty())
mojo_devices.push_back(DeviceInfo::From(*devices[i]));
}
callback_task_runner->PostTask(
FROM_HERE, base::Bind(callback, base::Passed(&mojo_devices)));
}
| 171,698
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 long Chapters::Atom::GetStartTime(const Chapters* pChapters) const
{
return GetTime(pChapters, m_start_timecode);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const
| 174,355
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UsbDeviceHandle::TransferCallback& callback() const {
return callback_;
}
Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback
Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback
migration, as they are copied and passed to others.
This CL updates them to pass new callbacks for each use to avoid the
copy of callbacks.
Bug: 714018
Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0
Reviewed-on: https://chromium-review.googlesource.com/527549
Reviewed-by: Ken Rockot <rockot@chromium.org>
Commit-Queue: Taiju Tsuiki <tzik@chromium.org>
Cr-Commit-Position: refs/heads/master@{#478549}
CWE ID:
|
const UsbDeviceHandle::TransferCallback& callback() const {
UsbDeviceHandle::TransferCallback GetCallback() {
return base::Bind(&TestCompletionCallback::SetResult,
base::Unretained(this));
}
| 171,978
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GM2TabStyle::PaintTabBackground(gfx::Canvas* canvas,
bool active,
int fill_id,
int y_inset,
const SkPath* clip) const {
DCHECK(!y_inset || fill_id);
const SkColor active_color =
tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE);
const SkColor inactive_color =
tab_->GetThemeProvider()->GetDisplayProperty(
ThemeProperties::SHOULD_FILL_BACKGROUND_TAB_COLOR)
? tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE)
: SK_ColorTRANSPARENT;
const SkColor stroke_color =
tab_->controller()->GetToolbarTopSeparatorColor();
const bool paint_hover_effect = !active && IsHoverActive();
const float stroke_thickness = GetStrokeThickness(active);
PaintTabBackgroundFill(canvas, active, paint_hover_effect, active_color,
inactive_color, fill_id, y_inset);
if (stroke_thickness > 0) {
gfx::ScopedCanvas scoped_canvas(clip ? canvas : nullptr);
if (clip)
canvas->sk_canvas()->clipPath(*clip, SkClipOp::kDifference, true);
PaintBackgroundStroke(canvas, active, stroke_color);
}
PaintSeparators(canvas);
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <bsep@chromium.org>
Reviewed-by: Taylor Bergquist <tbergquist@chromium.org>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20
|
void GM2TabStyle::PaintTabBackground(gfx::Canvas* canvas,
TabState active_state,
int fill_id,
int y_inset,
const SkPath* clip) const {
DCHECK(!y_inset || fill_id);
const SkColor stroke_color =
tab_->controller()->GetToolbarTopSeparatorColor();
const bool paint_hover_effect =
active_state == TAB_INACTIVE && IsHoverActive();
const float stroke_thickness = GetStrokeThickness(active_state == TAB_ACTIVE);
PaintTabBackgroundFill(canvas, active_state, paint_hover_effect, fill_id,
y_inset);
if (stroke_thickness > 0) {
gfx::ScopedCanvas scoped_canvas(clip ? canvas : nullptr);
if (clip)
canvas->sk_canvas()->clipPath(*clip, SkClipOp::kDifference, true);
PaintBackgroundStroke(canvas, active_state, stroke_color);
}
PaintSeparators(canvas);
}
| 172,525
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
int use_input_precision, int scale16, int expand16,
int do_background, PNG_CONST png_color_16 *pointer_to_the_background_color,
double background_gamma)
{
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->file_gamma = file_gamma;
dp->screen_gamma = screen_gamma;
dp->background_gamma = background_gamma;
dp->sbit = sbit;
dp->threshold_test = threshold_test;
dp->use_input_precision = use_input_precision;
dp->scale16 = scale16;
dp->expand16 = expand16;
dp->do_background = do_background;
if (do_background && pointer_to_the_background_color != 0)
dp->background_color = *pointer_to_the_background_color;
else
memset(&dp->background_color, 0, sizeof dp->background_color);
/* Local variable fields */
dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
int use_input_precision, int scale16, int expand16,
int do_background, const png_color_16 *pointer_to_the_background_color,
double background_gamma)
{
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->file_gamma = file_gamma;
dp->screen_gamma = screen_gamma;
dp->background_gamma = background_gamma;
dp->sbit = sbit;
dp->threshold_test = threshold_test;
dp->use_input_precision = use_input_precision;
dp->scale16 = scale16;
dp->expand16 = expand16;
dp->do_background = do_background;
if (do_background && pointer_to_the_background_color != 0)
dp->background_color = *pointer_to_the_background_color;
else
memset(&dp->background_color, 0, sizeof dp->background_color);
/* Local variable fields */
dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
}
| 173,611
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BufCompressedFill (BufFilePtr f)
{
CompressedFile *file;
register char_type *stackp, *de_stack;
register char_type finchar;
register code_int code, oldcode, incode;
BufChar *buf, *bufend;
file = (CompressedFile *) f->private;
buf = f->buffer;
bufend = buf + BUFFILESIZE;
stackp = file->stackp;
de_stack = file->de_stack;
finchar = file->finchar;
oldcode = file->oldcode;
while (buf < bufend) {
while (stackp > de_stack && buf < bufend)
*buf++ = *--stackp;
if (buf == bufend)
break;
if (oldcode == -1)
break;
code = getcode (file);
if (code == -1)
break;
if ( (code == CLEAR) && file->block_compress ) {
for ( code = 255; code >= 0; code-- )
file->tab_prefix[code] = 0;
file->clear_flg = 1;
file->free_ent = FIRST - 1;
if ( (code = getcode (file)) == -1 ) /* O, untimely death! */
break;
}
incode = code;
/*
* Special case for KwKwK string.
*/
if ( code >= file->free_ent ) {
*stackp++ = finchar;
code = oldcode;
}
/*
* Generate output characters in reverse order
*/
while ( code >= 256 )
{
*stackp++ = file->tab_suffix[code];
code = file->tab_prefix[code];
}
/*
* Generate the new entry.
*/
if ( (code=file->free_ent) < file->maxmaxcode ) {
file->tab_prefix[code] = (unsigned short)oldcode;
file->tab_suffix[code] = finchar;
file->free_ent = code+1;
}
/*
* Remember previous code.
*/
oldcode = incode;
}
file->oldcode = oldcode;
file->stackp = stackp;
file->finchar = finchar;
if (buf == f->buffer) {
f->left = 0;
return BUFFILEEOF;
}
f->bufp = f->buffer + 1;
f->left = (buf - f->buffer) - 1;
return f->buffer[0];
}
Commit Message:
CWE ID: CWE-119
|
BufCompressedFill (BufFilePtr f)
{
CompressedFile *file;
register char_type *stackp, *de_stack;
register char_type finchar;
register code_int code, oldcode, incode;
BufChar *buf, *bufend;
file = (CompressedFile *) f->private;
buf = f->buffer;
bufend = buf + BUFFILESIZE;
stackp = file->stackp;
de_stack = file->de_stack;
finchar = file->finchar;
oldcode = file->oldcode;
while (buf < bufend) {
while (stackp > de_stack && buf < bufend)
*buf++ = *--stackp;
if (buf == bufend)
break;
if (oldcode == -1)
break;
code = getcode (file);
if (code == -1)
break;
if ( (code == CLEAR) && file->block_compress ) {
for ( code = 255; code >= 0; code-- )
file->tab_prefix[code] = 0;
file->clear_flg = 1;
file->free_ent = FIRST - 1;
if ( (code = getcode (file)) == -1 ) /* O, untimely death! */
break;
}
incode = code;
/*
* Special case for KwKwK string.
*/
if ( code >= file->free_ent ) {
*stackp++ = finchar;
code = oldcode;
}
/*
* Generate output characters in reverse order
*/
while ( code >= 256 )
{
if (stackp - de_stack >= STACK_SIZE - 1)
return BUFFILEEOF;
*stackp++ = file->tab_suffix[code];
code = file->tab_prefix[code];
}
/*
* Generate the new entry.
*/
if ( (code=file->free_ent) < file->maxmaxcode ) {
file->tab_prefix[code] = (unsigned short)oldcode;
file->tab_suffix[code] = finchar;
file->free_ent = code+1;
}
/*
* Remember previous code.
*/
oldcode = incode;
}
file->oldcode = oldcode;
file->stackp = stackp;
file->finchar = finchar;
if (buf == f->buffer) {
f->left = 0;
return BUFFILEEOF;
}
f->bufp = f->buffer + 1;
f->left = (buf - f->buffer) - 1;
return f->buffer[0];
}
| 164,651
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) {
}
Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32
Bug: 20634516
Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c
(cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4)
CWE ID: CWE-119
|
void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) {
| 173,359
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: IPV6DefragReverseSimpleTest(void)
{
DefragContext *dc = NULL;
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p3, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p1, NULL);
if (reassembled == NULL)
goto end;
/* 40 bytes in we should find 8 bytes of A. */
for (i = 40; i < 40 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 48; i < 48 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 56; i < 56 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358
|
IPV6DefragReverseSimpleTest(void)
{
DefragContext *dc = NULL;
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p3, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p1, NULL);
if (reassembled == NULL)
goto end;
/* 40 bytes in we should find 8 bytes of A. */
for (i = 40; i < 40 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 48; i < 48 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 56; i < 56 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
| 168,310
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 k90_show_macro_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
const char *macro_mode;
char data[8];
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_GET_MODE,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 2,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial mode (error %d).\n",
ret);
return -EIO;
}
switch (data[0]) {
case K90_MACRO_MODE_HW:
macro_mode = "HW";
break;
case K90_MACRO_MODE_SW:
macro_mode = "SW";
break;
default:
dev_warn(dev, "K90 in unknown mode: %02hhx.\n",
data[0]);
return -EIO;
}
return snprintf(buf, PAGE_SIZE, "%s\n", macro_mode);
}
Commit Message: HID: corsair: fix DMA buffers on stack
Not all platforms support DMA to the stack, and specifically since v4.9
this is no longer supported on x86 with VMAP_STACK either.
Note that the macro-mode buffer was larger than necessary.
Fixes: 6f78193ee9ea ("HID: corsair: Add Corsair Vengeance K90 driver")
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID: CWE-119
|
static ssize_t k90_show_macro_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
const char *macro_mode;
char *data;
data = kmalloc(2, GFP_KERNEL);
if (!data)
return -ENOMEM;
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_GET_MODE,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 2,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial mode (error %d).\n",
ret);
ret = -EIO;
goto out;
}
switch (data[0]) {
case K90_MACRO_MODE_HW:
macro_mode = "HW";
break;
case K90_MACRO_MODE_SW:
macro_mode = "SW";
break;
default:
dev_warn(dev, "K90 in unknown mode: %02hhx.\n",
data[0]);
ret = -EIO;
goto out;
}
ret = snprintf(buf, PAGE_SIZE, "%s\n", macro_mode);
out:
kfree(data);
return ret;
}
| 168,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: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_,
long long& val) {
assert(pReader);
assert(pos >= 0);
long long total, available;
const long status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
if (status < 0)
return false;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
if ((unsigned long)id != id_)
return false;
pos += len; // consume id
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert(size <= 8);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
pos += len; // consume length of size of payload
val = UnserializeUInt(pReader, pos, size);
assert(val >= 0);
pos += size; // consume size of payload
return true;
}
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
|
bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_,
bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id,
long long& val) {
if (!pReader || pos < 0)
return false;
long long total = 0;
long long available = 0;
const long status = pReader->Length(&total, &available);
if (status < 0 || (total >= 0 && available > total))
return false;
long len = 0;
const long long id = ReadID(pReader, pos, len);
if (id < 0 || (available - pos) > len)
return false;
if (static_cast<unsigned long>(id) != expected_id)
return false;
pos += len; // consume id
const long long size = ReadUInt(pReader, pos, len);
if (size < 0 || size > 8 || len < 1 || len > 8 || (available - pos) > len)
return false;
pos += len; // consume length of size of payload
val = UnserializeUInt(pReader, pos, size);
if (val < 0)
return false;
pos += size; // consume size of payload
return true;
}
| 173,832
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 qrio_prstcfg(u8 bit, u8 mode)
{
u32 prstcfg;
u8 i;
void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE;
prstcfg = in_be32(qrio_base + PRSTCFG_OFF);
for (i = 0; i < 2; i++) {
if (mode & (1<<i))
set_bit(2*bit+i, &prstcfg);
else
clear_bit(2*bit+i, &prstcfg);
}
out_be32(qrio_base + PRSTCFG_OFF, prstcfg);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
|
void qrio_prstcfg(u8 bit, u8 mode)
{
u32 prstcfg;
u8 i;
void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE;
prstcfg = in_be32(qrio_base + PRSTCFG_OFF);
for (i = 0; i < 2; i++) {
if (mode & (1 << i))
set_bit(2 * bit + i, &prstcfg);
else
clear_bit(2 * bit + i, &prstcfg);
}
out_be32(qrio_base + PRSTCFG_OFF, prstcfg);
}
| 169,625
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static cJSON *create_reference( cJSON *item )
{
cJSON *ref;
if ( ! ( ref = cJSON_New_Item() ) )
return 0;
memcpy( ref, item, sizeof(cJSON) );
ref->string = 0;
ref->type |= cJSON_IsReference;
ref->next = ref->prev = 0;
return ref;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
static cJSON *create_reference( cJSON *item )
| 167,299
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {
RASN1Object *object;
RCMS *container;
if (!buffer || !length) {
return NULL;
}
container = R_NEW0 (RCMS);
if (!container) {
return NULL;
}
object = r_asn1_create_object (buffer, length);
if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {
r_asn1_free_object (object);
free (container);
return NULL;
}
container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);
r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);
r_asn1_free_object (object);
return container;
}
Commit Message: Fix #7152 - Null deref in cms
CWE ID: CWE-476
|
RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {
RASN1Object *object;
RCMS *container;
if (!buffer || !length) {
return NULL;
}
container = R_NEW0 (RCMS);
if (!container) {
return NULL;
}
object = r_asn1_create_object (buffer, length);
if (!object || object->list.length != 2 || !object->list.objects ||
!object->list.objects[0] || !object->list.objects[1] ||
object->list.objects[1]->list.length != 1) {
r_asn1_free_object (object);
free (container);
return NULL;
}
container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);
r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);
r_asn1_free_object (object);
return container;
}
| 168,287
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::GetLast(const BlockEntry*& pLast) const
{
for (;;)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pLast = NULL;
return status;
}
if (status > 0) //no new block
break;
}
if (m_entries_count <= 0)
{
pLast = NULL;
return 0;
}
assert(m_entries);
const long idx = m_entries_count - 1;
pLast = m_entries[idx];
assert(pLast);
return 0;
}
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::GetLast(const BlockEntry*& pLast) const
if (m_entries_count <= 0) {
pLast = NULL;
return 0;
}
assert(m_entries);
const long idx = m_entries_count - 1;
pLast = m_entries[idx];
assert(pLast);
return 0;
}
| 174,338
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BlobURLRequestJob::ComputeBytesToRead() const {
int64 current_item_remaining_bytes =
item_length_list_[current_item_index_] - current_item_offset_;
int64 remaining_bytes = std::min(current_item_remaining_bytes,
remaining_bytes_);
return static_cast<int>(std::min(
static_cast<int64>(read_buf_->BytesRemaining()),
remaining_bytes));
}
Commit Message: Avoid integer overflows in BlobURLRequestJob.
BUG=169685
Review URL: https://chromiumcodereview.appspot.com/12047012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
int BlobURLRequestJob::ComputeBytesToRead() const {
int64 current_item_length = item_length_list_[current_item_index_];
int64 item_remaining = current_item_length - current_item_offset_;
int64 buf_remaining = read_buf_->BytesRemaining();
int64 max_remaining = std::numeric_limits<int>::max();
int64 min = std::min(std::min(std::min(item_remaining,
buf_remaining),
remaining_bytes_),
max_remaining);
return static_cast<int>(min);
}
| 171,397
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error)
{
if (strcmp (incoming, "/org/freedesktop/DBus/GLib/Tests/MyTestObject"))
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"invalid incoming object");
return FALSE;
}
*outgoing = "/org/freedesktop/DBus/GLib/Tests/MyTestObject2";
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error)
| 165,114
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeOSSendHandwritingStroke(InputMethodStatusConnection* connection,
const HandwritingStroke& stroke) {
g_return_if_fail(connection);
connection->SendHandwritingStroke(stroke);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void ChromeOSSendHandwritingStroke(InputMethodStatusConnection* connection,
virtual void SendHandwritingStroke(const HandwritingStroke& stroke) {
}
virtual void CancelHandwriting(int n_strokes) {
}
};
IBusController* IBusController::Create() {
#if defined(HAVE_IBUS)
return IBusControllerImpl::GetInstance();
#else
return new IBusControllerStubImpl;
#endif
}
| 170,525
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: struct tcp_conn_t *tcp_conn_accept(struct tcp_sock_t *sock)
{
struct tcp_conn_t *conn = calloc(1, sizeof *conn);
if (conn == NULL) {
ERR("Calloc for connection struct failed");
goto error;
}
conn->sd = accept(sock->sd, NULL, NULL);
if (conn->sd < 0) {
ERR("accept failed");
goto error;
}
return conn;
error:
if (conn != NULL)
free(conn);
return NULL;
}
Commit Message: SECURITY FIX: Actually restrict the access to the printer to localhost
Before, any machine in any network connected by any of the interfaces (as
listed by "ifconfig") could access to an IPP-over-USB printer on the assigned
port, allowing users on remote machines to print and to access the web
configuration interface of a IPP-over-USB printer in contrary to conventional
USB printers which are only accessible locally.
CWE ID: CWE-264
|
struct tcp_conn_t *tcp_conn_accept(struct tcp_sock_t *sock)
struct tcp_conn_t *tcp_conn_select(struct tcp_sock_t *sock,
struct tcp_sock_t *sock6)
{
struct tcp_conn_t *conn = calloc(1, sizeof *conn);
if (conn == NULL) {
ERR("Calloc for connection struct failed");
goto error;
}
fd_set rfds;
struct timeval tv;
int retval = 0;
int nfds = 0;
while (retval == 0) {
FD_ZERO(&rfds);
if (sock) {
FD_SET(sock->sd, &rfds);
nfds = sock->sd;
}
if (sock6) {
FD_SET(sock6->sd, &rfds);
if (sock6->sd > nfds)
nfds = sock6->sd;
}
if (nfds == 0) {
ERR("No valid TCP socket supplied.");
goto error;
}
nfds += 1;
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(nfds, &rfds, NULL, NULL, &tv);
if (retval == -1) {
ERR("Failed to open tcp connection");
goto error;
}
}
if (sock && FD_ISSET(sock->sd, &rfds)) {
conn->sd = accept(sock->sd, NULL, NULL);
NOTE ("Using IPv4");
} else if (sock6 && FD_ISSET(sock6->sd, &rfds)) {
conn->sd = accept(sock6->sd, NULL, NULL);
NOTE ("Using IPv6");
} else {
ERR("select failed");
goto error;
}
if (conn->sd < 0) {
ERR("accept failed");
goto error;
}
return conn;
error:
if (conn != NULL)
free(conn);
return NULL;
}
| 166,589
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 processInputBuffer(client *c) {
server.current_client = c;
/* Keep processing while there is something in the input buffer */
while(sdslen(c->querybuf)) {
/* Return if clients are paused. */
if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break;
/* Immediately abort if the client is in the middle of something. */
if (c->flags & CLIENT_BLOCKED) break;
/* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is
* written to the client. Make sure to not let the reply grow after
* this flag has been set (i.e. don't process more commands). */
if (c->flags & CLIENT_CLOSE_AFTER_REPLY) break;
/* Determine request type when unknown. */
if (!c->reqtype) {
if (c->querybuf[0] == '*') {
c->reqtype = PROTO_REQ_MULTIBULK;
} else {
c->reqtype = PROTO_REQ_INLINE;
}
}
if (c->reqtype == PROTO_REQ_INLINE) {
if (processInlineBuffer(c) != C_OK) break;
} else if (c->reqtype == PROTO_REQ_MULTIBULK) {
if (processMultibulkBuffer(c) != C_OK) break;
} else {
serverPanic("Unknown request type");
}
/* Multibulk processing could see a <= 0 length. */
if (c->argc == 0) {
resetClient(c);
} else {
/* Only reset the client when the command was executed. */
if (processCommand(c) == C_OK)
resetClient(c);
/* freeMemoryIfNeeded may flush slave output buffers. This may result
* into a slave, that may be the active client, to be freed. */
if (server.current_client == NULL) break;
}
}
server.current_client = NULL;
}
Commit Message: Security: Cross Protocol Scripting protection.
This is an attempt at mitigating problems due to cross protocol
scripting, an attack targeting services using line oriented protocols
like Redis that can accept HTTP requests as valid protocol, by
discarding the invalid parts and accepting the payloads sent, for
example, via a POST request.
For this to be effective, when we detect POST and Host: and terminate
the connection asynchronously, the networking code was modified in order
to never process further input. It was later verified that in a
pipelined request containing a POST command, the successive commands are
not executed.
CWE ID: CWE-254
|
void processInputBuffer(client *c) {
server.current_client = c;
/* Keep processing while there is something in the input buffer */
while(sdslen(c->querybuf)) {
/* Return if clients are paused. */
if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break;
/* Immediately abort if the client is in the middle of something. */
if (c->flags & CLIENT_BLOCKED) break;
/* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is
* written to the client. Make sure to not let the reply grow after
* this flag has been set (i.e. don't process more commands).
*
* The same applies for clients we want to terminate ASAP. */
if (c->flags & (CLIENT_CLOSE_AFTER_REPLY|CLIENT_CLOSE_ASAP)) break;
/* Determine request type when unknown. */
if (!c->reqtype) {
if (c->querybuf[0] == '*') {
c->reqtype = PROTO_REQ_MULTIBULK;
} else {
c->reqtype = PROTO_REQ_INLINE;
}
}
if (c->reqtype == PROTO_REQ_INLINE) {
if (processInlineBuffer(c) != C_OK) break;
} else if (c->reqtype == PROTO_REQ_MULTIBULK) {
if (processMultibulkBuffer(c) != C_OK) break;
} else {
serverPanic("Unknown request type");
}
/* Multibulk processing could see a <= 0 length. */
if (c->argc == 0) {
resetClient(c);
} else {
/* Only reset the client when the command was executed. */
if (processCommand(c) == C_OK)
resetClient(c);
/* freeMemoryIfNeeded may flush slave output buffers. This may result
* into a slave, that may be the active client, to be freed. */
if (server.current_client == NULL) break;
}
}
server.current_client = NULL;
}
| 168,453
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OnZipAnalysisFinished(const zip_analyzer::Results& results) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(ClientDownloadRequest::ZIPPED_EXECUTABLE, type_);
if (!service_)
return;
if (results.success) {
zipped_executable_ = results.has_executable;
archived_binary_.CopyFrom(results.archived_binary);
DVLOG(1) << "Zip analysis finished for " << item_->GetFullPath().value()
<< ", has_executable=" << results.has_executable
<< " has_archive=" << results.has_archive;
} else {
DVLOG(1) << "Zip analysis failed for " << item_->GetFullPath().value();
}
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasExecutable",
zipped_executable_);
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasArchiveButNoExecutable",
results.has_archive && !zipped_executable_);
UMA_HISTOGRAM_TIMES("SBClientDownload.ExtractZipFeaturesTime",
base::TimeTicks::Now() - zip_analysis_start_time_);
for (const auto& file_extension : results.archived_archive_filetypes)
RecordArchivedArchiveFileExtensionType(file_extension);
if (!zipped_executable_ && !results.has_archive) {
PostFinishTask(UNKNOWN, REASON_ARCHIVE_WITHOUT_BINARIES);
return;
}
if (!zipped_executable_ && results.has_archive)
type_ = ClientDownloadRequest::ZIPPED_ARCHIVE;
OnFileFeatureExtractionDone();
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
R=isherman@chromium.org, kenrb@chromium.org, mattm@chromium.org, thestig@chromium.org
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID:
|
void OnZipAnalysisFinished(const zip_analyzer::Results& results) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(ClientDownloadRequest::ZIPPED_EXECUTABLE, type_);
if (!service_)
return;
if (results.success) {
archived_executable_ = results.has_executable;
archived_binary_.CopyFrom(results.archived_binary);
DVLOG(1) << "Zip analysis finished for " << item_->GetFullPath().value()
<< ", has_executable=" << results.has_executable
<< " has_archive=" << results.has_archive;
} else {
DVLOG(1) << "Zip analysis failed for " << item_->GetFullPath().value();
}
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasExecutable",
archived_executable_);
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasArchiveButNoExecutable",
results.has_archive && !archived_executable_);
UMA_HISTOGRAM_TIMES("SBClientDownload.ExtractZipFeaturesTime",
base::TimeTicks::Now() - zip_analysis_start_time_);
for (const auto& file_extension : results.archived_archive_filetypes)
RecordArchivedArchiveFileExtensionType(file_extension);
if (!archived_executable_ && !results.has_archive) {
PostFinishTask(UNKNOWN, REASON_ARCHIVE_WITHOUT_BINARIES);
return;
}
if (!archived_executable_ && results.has_archive)
type_ = ClientDownloadRequest::ZIPPED_ARCHIVE;
OnFileFeatureExtractionDone();
}
| 171,713
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual void TearDown() {
vpx_free(src_);
delete[] ref_;
vpx_free(sec_);
libvpx_test::ClearSystemState();
}
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 TearDown() {
vpx_free(src_);
delete[] ref_;
libvpx_test::ClearSystemState();
}
protected:
void RefTest_mse();
void RefTest_sse();
void MaxTest_mse();
void MaxTest_sse();
ACMRandom rnd;
uint8_t* src_;
uint8_t* ref_;
int width_, log2width_;
int height_, log2height_;
int block_size_;
MseFunctionType mse_;
};
template<typename MseFunctionType>
void MseTest<MseFunctionType>::RefTest_mse() {
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < block_size_; j++) {
src_[j] = rnd.Rand8();
ref_[j] = rnd.Rand8();
}
unsigned int sse1, sse2;
const int stride_coeff = 1;
ASM_REGISTER_STATE_CHECK(mse_(src_, width_, ref_, width_, &sse1));
variance_ref(src_, ref_, log2width_, log2height_, stride_coeff,
stride_coeff, &sse2, false, VPX_BITS_8);
EXPECT_EQ(sse1, sse2);
}
}
template<typename MseFunctionType>
void MseTest<MseFunctionType>::RefTest_sse() {
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < block_size_; j++) {
src_[j] = rnd.Rand8();
ref_[j] = rnd.Rand8();
}
unsigned int sse2;
unsigned int var1;
const int stride_coeff = 1;
ASM_REGISTER_STATE_CHECK(var1 = mse_(src_, width_, ref_, width_));
variance_ref(src_, ref_, log2width_, log2height_, stride_coeff,
stride_coeff, &sse2, false, VPX_BITS_8);
EXPECT_EQ(var1, sse2);
}
}
template<typename MseFunctionType>
void MseTest<MseFunctionType>::MaxTest_mse() {
memset(src_, 255, block_size_);
memset(ref_, 0, block_size_);
unsigned int sse;
ASM_REGISTER_STATE_CHECK(mse_(src_, width_, ref_, width_, &sse));
const unsigned int expected = block_size_ * 255 * 255;
EXPECT_EQ(expected, sse);
}
template<typename MseFunctionType>
void MseTest<MseFunctionType>::MaxTest_sse() {
memset(src_, 255, block_size_);
memset(ref_, 0, block_size_);
unsigned int var;
ASM_REGISTER_STATE_CHECK(var = mse_(src_, width_, ref_, width_));
const unsigned int expected = block_size_ * 255 * 255;
EXPECT_EQ(expected, var);
}
static uint32_t subpel_avg_variance_ref(const uint8_t *ref,
const uint8_t *src,
const uint8_t *second_pred,
int l2w, int l2h,
int xoff, int yoff,
uint32_t *sse_ptr,
bool use_high_bit_depth,
vpx_bit_depth_t bit_depth) {
int64_t se = 0;
uint64_t sse = 0;
const int w = 1 << l2w;
const int h = 1 << l2h;
xoff <<= 1;
yoff <<= 1;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
// bilinear interpolation at a 16th pel step
if (!use_high_bit_depth) {
const int a1 = ref[(w + 1) * (y + 0) + x + 0];
const int a2 = ref[(w + 1) * (y + 0) + x + 1];
const int b1 = ref[(w + 1) * (y + 1) + x + 0];
const int b2 = ref[(w + 1) * (y + 1) + x + 1];
const int a = a1 + (((a2 - a1) * xoff + 8) >> 4);
const int b = b1 + (((b2 - b1) * xoff + 8) >> 4);
const int r = a + (((b - a) * yoff + 8) >> 4);
const int diff = ((r + second_pred[w * y + x] + 1) >> 1) - src[w * y + x];
se += diff;
sse += diff * diff;
#if CONFIG_VP9_HIGHBITDEPTH
} else {
uint16_t *ref16 = CONVERT_TO_SHORTPTR(ref);
uint16_t *src16 = CONVERT_TO_SHORTPTR(src);
uint16_t *sec16 = CONVERT_TO_SHORTPTR(second_pred);
const int a1 = ref16[(w + 1) * (y + 0) + x + 0];
const int a2 = ref16[(w + 1) * (y + 0) + x + 1];
const int b1 = ref16[(w + 1) * (y + 1) + x + 0];
const int b2 = ref16[(w + 1) * (y + 1) + x + 1];
const int a = a1 + (((a2 - a1) * xoff + 8) >> 4);
const int b = b1 + (((b2 - b1) * xoff + 8) >> 4);
const int r = a + (((b - a) * yoff + 8) >> 4);
const int diff = ((r + sec16[w * y + x] + 1) >> 1) - src16[w * y + x];
se += diff;
sse += diff * diff;
#endif // CONFIG_VP9_HIGHBITDEPTH
}
}
}
RoundHighBitDepth(bit_depth, &se, &sse);
*sse_ptr = static_cast<uint32_t>(sse);
return static_cast<uint32_t>(sse -
((static_cast<int64_t>(se) * se) >>
(l2w + l2h)));
}
template<typename SubpelVarianceFunctionType>
class SubpelVarianceTest
: public ::testing::TestWithParam<tuple<int, int,
SubpelVarianceFunctionType, int> > {
public:
virtual void SetUp() {
const tuple<int, int, SubpelVarianceFunctionType, int>& params =
this->GetParam();
log2width_ = get<0>(params);
width_ = 1 << log2width_;
log2height_ = get<1>(params);
height_ = 1 << log2height_;
subpel_variance_ = get<2>(params);
if (get<3>(params)) {
bit_depth_ = (vpx_bit_depth_t) get<3>(params);
use_high_bit_depth_ = true;
} else {
bit_depth_ = VPX_BITS_8;
use_high_bit_depth_ = false;
}
mask_ = (1 << bit_depth_)-1;
rnd_.Reset(ACMRandom::DeterministicSeed());
block_size_ = width_ * height_;
if (!use_high_bit_depth_) {
src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_));
sec_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_));
ref_ = new uint8_t[block_size_ + width_ + height_ + 1];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src_ = CONVERT_TO_BYTEPTR(
reinterpret_cast<uint16_t *>(
vpx_memalign(16, block_size_*sizeof(uint16_t))));
sec_ = CONVERT_TO_BYTEPTR(
reinterpret_cast<uint16_t *>(
vpx_memalign(16, block_size_*sizeof(uint16_t))));
ref_ = CONVERT_TO_BYTEPTR(
new uint16_t[block_size_ + width_ + height_ + 1]);
#endif // CONFIG_VP9_HIGHBITDEPTH
}
ASSERT_TRUE(src_ != NULL);
ASSERT_TRUE(sec_ != NULL);
ASSERT_TRUE(ref_ != NULL);
}
virtual void TearDown() {
if (!use_high_bit_depth_) {
vpx_free(src_);
delete[] ref_;
vpx_free(sec_);
#if CONFIG_VP9_HIGHBITDEPTH
} else {
vpx_free(CONVERT_TO_SHORTPTR(src_));
delete[] CONVERT_TO_SHORTPTR(ref_);
vpx_free(CONVERT_TO_SHORTPTR(sec_));
#endif // CONFIG_VP9_HIGHBITDEPTH
}
libvpx_test::ClearSystemState();
}
| 174,592
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg,
int /* flags */) {
if (msg->iov_length != 1)
return -1;
msg->ndesc_length = 0; // Messages with descriptors aren't supported yet.
return static_cast<ssize_t>(
ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base),
msg->iov[0].length));
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg,
int /* flags */) {
if (msg->iov_length != 1)
return -1;
return static_cast<ssize_t>(
ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base),
msg->iov[0].length));
}
| 170,730
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 blkcg_init_queue(struct request_queue *q)
{
struct blkcg_gq *new_blkg, *blkg;
bool preloaded;
int ret;
new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL);
if (!new_blkg)
return -ENOMEM;
preloaded = !radix_tree_preload(GFP_KERNEL);
/*
* Make sure the root blkg exists and count the existing blkgs. As
* @q is bypassing at this point, blkg_lookup_create() can't be
* used. Open code insertion.
*/
rcu_read_lock();
spin_lock_irq(q->queue_lock);
blkg = blkg_create(&blkcg_root, q, new_blkg);
spin_unlock_irq(q->queue_lock);
rcu_read_unlock();
if (preloaded)
radix_tree_preload_end();
if (IS_ERR(blkg)) {
blkg_free(new_blkg);
return PTR_ERR(blkg);
}
q->root_blkg = blkg;
q->root_rl.blkg = blkg;
ret = blk_throtl_init(q);
if (ret) {
spin_lock_irq(q->queue_lock);
blkg_destroy_all(q);
spin_unlock_irq(q->queue_lock);
}
return ret;
}
Commit Message: blkcg: fix double free of new_blkg in blkcg_init_queue
If blkg_create fails, new_blkg passed as an argument will
be freed by blkg_create, so there is no need to free it again.
Signed-off-by: Hou Tao <houtao1@huawei.com>
Signed-off-by: Jens Axboe <axboe@fb.com>
CWE ID: CWE-415
|
int blkcg_init_queue(struct request_queue *q)
{
struct blkcg_gq *new_blkg, *blkg;
bool preloaded;
int ret;
new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL);
if (!new_blkg)
return -ENOMEM;
preloaded = !radix_tree_preload(GFP_KERNEL);
/*
* Make sure the root blkg exists and count the existing blkgs. As
* @q is bypassing at this point, blkg_lookup_create() can't be
* used. Open code insertion.
*/
rcu_read_lock();
spin_lock_irq(q->queue_lock);
blkg = blkg_create(&blkcg_root, q, new_blkg);
spin_unlock_irq(q->queue_lock);
rcu_read_unlock();
if (preloaded)
radix_tree_preload_end();
if (IS_ERR(blkg))
return PTR_ERR(blkg);
q->root_blkg = blkg;
q->root_rl.blkg = blkg;
ret = blk_throtl_init(q);
if (ret) {
spin_lock_irq(q->queue_lock);
blkg_destroy_all(q);
spin_unlock_irq(q->queue_lock);
}
return ret;
}
| 169,318
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf)
{
git_pkt *pkt;
const char *line, *line_end = NULL;
size_t line_len;
int error;
int reading_from_buf = data_pkt_buf->size > 0;
if (reading_from_buf) {
/* We had an existing partial packet, so add the new
* packet to the buffer and parse the whole thing */
git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len);
line = data_pkt_buf->ptr;
line_len = data_pkt_buf->size;
}
else {
line = data_pkt->data;
line_len = data_pkt->len;
}
while (line_len > 0) {
error = git_pkt_parse_line(&pkt, line, &line_end, line_len);
if (error == GIT_EBUFS) {
/* Buffer the data when the inner packet is split
* across multiple sideband packets */
if (!reading_from_buf)
git_buf_put(data_pkt_buf, line, line_len);
error = 0;
goto done;
}
else if (error < 0)
goto done;
/* Advance in the buffer */
line_len -= (line_end - line);
line = line_end;
/* When a valid packet with no content has been
* read, git_pkt_parse_line does not report an
* error, but the pkt pointer has not been set.
* Handle this by skipping over empty packets.
*/
if (pkt == NULL)
continue;
error = add_push_report_pkt(push, pkt);
git_pkt_free(pkt);
if (error < 0 && error != GIT_ITEROVER)
goto done;
}
error = 0;
done:
if (reading_from_buf)
git_buf_consume(data_pkt_buf, line_end);
return error;
}
Commit Message: smart_pkt: treat empty packet lines as error
The Git protocol does not specify what should happen in the case
of an empty packet line (that is a packet line "0004"). We
currently indicate success, but do not return a packet in the
case where we hit an empty line. The smart protocol was not
prepared to handle such packets in all cases, though, resulting
in a `NULL` pointer dereference.
Fix the issue by returning an error instead. As such kind of
packets is not even specified by upstream, this is the right
thing to do.
CWE ID: CWE-476
|
static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf)
{
git_pkt *pkt;
const char *line, *line_end = NULL;
size_t line_len;
int error;
int reading_from_buf = data_pkt_buf->size > 0;
if (reading_from_buf) {
/* We had an existing partial packet, so add the new
* packet to the buffer and parse the whole thing */
git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len);
line = data_pkt_buf->ptr;
line_len = data_pkt_buf->size;
}
else {
line = data_pkt->data;
line_len = data_pkt->len;
}
while (line_len > 0) {
error = git_pkt_parse_line(&pkt, line, &line_end, line_len);
if (error == GIT_EBUFS) {
/* Buffer the data when the inner packet is split
* across multiple sideband packets */
if (!reading_from_buf)
git_buf_put(data_pkt_buf, line, line_len);
error = 0;
goto done;
}
else if (error < 0)
goto done;
/* Advance in the buffer */
line_len -= (line_end - line);
line = line_end;
error = add_push_report_pkt(push, pkt);
git_pkt_free(pkt);
if (error < 0 && error != GIT_ITEROVER)
goto done;
}
error = 0;
done:
if (reading_from_buf)
git_buf_consume(data_pkt_buf, line_end);
return error;
}
| 168,528
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: cJSON *cJSON_CreateFloatArray( double *numbers, int count )
{
int i;
cJSON *n = 0, *p = 0, *a = cJSON_CreateArray();
for ( i = 0; a && i < count; ++i ) {
n = cJSON_CreateFloat( numbers[i] );
if ( ! i )
a->child = n;
else
suffix_object( p, n );
p = n;
}
return a;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
cJSON *cJSON_CreateFloatArray( double *numbers, int count )
| 167,273
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: FileMetricsProviderTest()
: create_large_files_(GetParam()),
task_runner_(new base::TestSimpleTaskRunner()),
thread_task_runner_handle_(task_runner_),
statistics_recorder_(
base::StatisticsRecorder::CreateTemporaryForTesting()),
prefs_(new TestingPrefServiceSimple) {
EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName);
FileMetricsProvider::SetTaskRunnerForTesting(task_runner_);
base::GlobalHistogramAllocator::GetCreateHistogramResultHistogram();
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <bcwhite@chromium.org>
Reviewed-by: Alexei Svitkine <asvitkine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264
|
FileMetricsProviderTest()
: create_large_files_(GetParam()),
task_runner_(new base::TestSimpleTaskRunner()),
thread_task_runner_handle_(task_runner_),
statistics_recorder_(
base::StatisticsRecorder::CreateTemporaryForTesting()),
prefs_(new TestingPrefServiceSimple) {
EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName);
FileMetricsProvider::SetTaskRunnerForTesting(task_runner_);
}
| 172,141
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: AviaryScheddPlugin::processJob(const char *key,
const char *,
int )
{
PROC_ID id;
ClassAd *jobAd;
if (!IS_JOB(key)) return false;
id = getProcByString(key);
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Failed to parse key: %s - skipping\n", key);
return false;
}
if (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) {
dprintf(D_ALWAYS,
"NOTICE: Failed to lookup ad for %s - maybe deleted\n",
key);
return false;
}
MyString submissionName;
if (GetAttributeString(id.cluster, id.proc,
ATTR_JOB_SUBMISSION,
submissionName) < 0) {
PROC_ID dagman;
if (GetAttributeInt(id.cluster, id.proc,
ATTR_DAGMAN_JOB_ID,
&dagman.cluster) >= 0) {
dagman.proc = 0;
if (GetAttributeString(dagman.cluster, dagman.proc,
ATTR_JOB_SUBMISSION,
submissionName) < 0) {
submissionName.sprintf("%s#%d", Name, dagman.cluster);
}
} else {
submissionName.sprintf("%s#%d", Name, id.cluster);
}
MyString tmp;
tmp += "\"";
tmp += submissionName;
tmp += "\"";
SetAttribute(id.cluster, id.proc,
ATTR_JOB_SUBMISSION,
tmp.Value());
}
return true;
}
Commit Message:
CWE ID: CWE-20
|
AviaryScheddPlugin::processJob(const char *key,
const char *,
int )
{
PROC_ID id;
ClassAd *jobAd;
if (!IS_JOB(key)) return false;
id = getProcByString(key);
if (id.cluster <= 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Failed to parse key: %s - skipping\n", key);
return false;
}
if (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) {
dprintf(D_ALWAYS,
"NOTICE: Failed to lookup ad for %s - maybe deleted\n",
key);
return false;
}
MyString submissionName;
if (GetAttributeString(id.cluster, id.proc,
ATTR_JOB_SUBMISSION,
submissionName) < 0) {
PROC_ID dagman;
if (GetAttributeInt(id.cluster, id.proc,
ATTR_DAGMAN_JOB_ID,
&dagman.cluster) >= 0) {
dagman.proc = 0;
if (GetAttributeString(dagman.cluster, dagman.proc,
ATTR_JOB_SUBMISSION,
submissionName) < 0) {
submissionName.sprintf("%s#%d", Name, dagman.cluster);
}
} else {
submissionName.sprintf("%s#%d", Name, id.cluster);
}
MyString tmp;
tmp += "\"";
tmp += submissionName;
tmp += "\"";
SetAttribute(id.cluster, id.proc,
ATTR_JOB_SUBMISSION,
tmp.Value());
}
return true;
}
| 164,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 DatabaseMessageFilter::OnDatabaseOpened(const string16& origin_identifier,
const string16& database_name,
const string16& description,
int64 estimated_size) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
int64 database_size = 0;
db_tracker_->DatabaseOpened(origin_identifier, database_name, description,
estimated_size, &database_size);
database_connections_.AddConnection(origin_identifier, database_name);
Send(new DatabaseMsg_UpdateSize(origin_identifier, database_name,
database_size));
}
Commit Message: WebDatabase: check path traversal in origin_identifier
BUG=172264
Review URL: https://chromiumcodereview.appspot.com/12212091
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@183141 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-22
|
void DatabaseMessageFilter::OnDatabaseOpened(const string16& origin_identifier,
const string16& database_name,
const string16& description,
int64 estimated_size) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!DatabaseUtil::IsValidOriginIdentifier(origin_identifier)) {
RecordAction(UserMetricsAction("BadMessageTerminate_DBMF"));
BadMessageReceived();
return;
}
int64 database_size = 0;
db_tracker_->DatabaseOpened(origin_identifier, database_name, description,
estimated_size, &database_size);
database_connections_.AddConnection(origin_identifier, database_name);
Send(new DatabaseMsg_UpdateSize(origin_identifier, database_name,
database_size));
}
| 171,477
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: png_get_mmx_bitdepth_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
return (png_ptr? 0: 0);
}
Commit Message: third_party/libpng: update to 1.2.54
TBR=darin@chromium.org
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
|
png_get_mmx_bitdepth_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
PNG_UNUSED(png_ptr)
return 0L;
}
| 172,166
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fdct16x16_c(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
void fdct16x16_ref(const int16_t *in, tran_low_t *out, int stride,
int /*tx_type*/) {
vpx_fdct16x16_c(in, out, stride);
}
| 174,529
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xpm_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
XPMDecContext *x = avctx->priv_data;
AVFrame *p=data;
const uint8_t *end, *ptr = avpkt->data;
int ncolors, cpp, ret, i, j;
int64_t size;
uint32_t *dst;
avctx->pix_fmt = AV_PIX_FMT_BGRA;
end = avpkt->data + avpkt->size;
while (memcmp(ptr, "/* XPM */", 9) && ptr < end - 9)
ptr++;
if (ptr >= end) {
av_log(avctx, AV_LOG_ERROR, "missing signature\n");
return AVERROR_INVALIDDATA;
}
ptr += mod_strcspn(ptr, "\"");
if (sscanf(ptr, "\"%u %u %u %u\",",
&avctx->width, &avctx->height, &ncolors, &cpp) != 4) {
av_log(avctx, AV_LOG_ERROR, "missing image parameters\n");
return AVERROR_INVALIDDATA;
}
if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0)
return ret;
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
if (cpp <= 0 || cpp >= 5) {
av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of chars per pixel: %d\n", cpp);
return AVERROR_INVALIDDATA;
}
size = 1;
for (i = 0; i < cpp; i++)
size *= 94;
if (ncolors <= 0 || ncolors > size) {
av_log(avctx, AV_LOG_ERROR, "invalid number of colors: %d\n", ncolors);
return AVERROR_INVALIDDATA;
}
size *= 4;
av_fast_padded_malloc(&x->pixels, &x->pixels_size, size);
if (!x->pixels)
return AVERROR(ENOMEM);
ptr += mod_strcspn(ptr, ",") + 1;
for (i = 0; i < ncolors; i++) {
const uint8_t *index;
int len;
ptr += mod_strcspn(ptr, "\"") + 1;
if (ptr + cpp > end)
return AVERROR_INVALIDDATA;
index = ptr;
ptr += cpp;
ptr = strstr(ptr, "c ");
if (ptr) {
ptr += 2;
} else {
return AVERROR_INVALIDDATA;
}
len = strcspn(ptr, "\" ");
if ((ret = ascii2index(index, cpp)) < 0)
return ret;
x->pixels[ret] = color_string_to_rgba(ptr, len);
ptr += mod_strcspn(ptr, ",") + 1;
}
for (i = 0; i < avctx->height; i++) {
dst = (uint32_t *)(p->data[0] + i * p->linesize[0]);
ptr += mod_strcspn(ptr, "\"") + 1;
for (j = 0; j < avctx->width; j++) {
if (ptr + cpp > end)
return AVERROR_INVALIDDATA;
if ((ret = ascii2index(ptr, cpp)) < 0)
return ret;
*dst++ = x->pixels[ret];
ptr += cpp;
}
ptr += mod_strcspn(ptr, ",") + 1;
}
p->key_frame = 1;
p->pict_type = AV_PICTURE_TYPE_I;
*got_frame = 1;
return avpkt->size;
}
Commit Message: avcodec/xpmdec: Fix multiple pointer/memory issues
Most of these were found through code review in response to
fixing 1466/clusterfuzz-testcase-minimized-5961584419536896
There is thus no testcase for most of this.
The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-119
|
static int xpm_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
XPMDecContext *x = avctx->priv_data;
AVFrame *p=data;
const uint8_t *end, *ptr;
int ncolors, cpp, ret, i, j;
int64_t size;
uint32_t *dst;
avctx->pix_fmt = AV_PIX_FMT_BGRA;
av_fast_padded_malloc(&x->buf, &x->buf_size, avpkt->size);
if (!x->buf)
return AVERROR(ENOMEM);
memcpy(x->buf, avpkt->data, avpkt->size);
x->buf[avpkt->size] = 0;
ptr = x->buf;
end = x->buf + avpkt->size;
while (end - ptr > 9 && memcmp(ptr, "/* XPM */", 9))
ptr++;
if (end - ptr <= 9) {
av_log(avctx, AV_LOG_ERROR, "missing signature\n");
return AVERROR_INVALIDDATA;
}
ptr += mod_strcspn(ptr, "\"");
if (sscanf(ptr, "\"%u %u %u %u\",",
&avctx->width, &avctx->height, &ncolors, &cpp) != 4) {
av_log(avctx, AV_LOG_ERROR, "missing image parameters\n");
return AVERROR_INVALIDDATA;
}
if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0)
return ret;
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
if (cpp <= 0 || cpp >= 5) {
av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of chars per pixel: %d\n", cpp);
return AVERROR_INVALIDDATA;
}
size = 1;
for (i = 0; i < cpp; i++)
size *= 95;
if (ncolors <= 0 || ncolors > size) {
av_log(avctx, AV_LOG_ERROR, "invalid number of colors: %d\n", ncolors);
return AVERROR_INVALIDDATA;
}
size *= 4;
av_fast_padded_malloc(&x->pixels, &x->pixels_size, size);
if (!x->pixels)
return AVERROR(ENOMEM);
ptr += mod_strcspn(ptr, ",") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
for (i = 0; i < ncolors; i++) {
const uint8_t *index;
int len;
ptr += mod_strcspn(ptr, "\"") + 1;
if (end - ptr < cpp)
return AVERROR_INVALIDDATA;
index = ptr;
ptr += cpp;
ptr = strstr(ptr, "c ");
if (ptr) {
ptr += 2;
} else {
return AVERROR_INVALIDDATA;
}
len = strcspn(ptr, "\" ");
if ((ret = ascii2index(index, cpp)) < 0)
return ret;
x->pixels[ret] = color_string_to_rgba(ptr, len);
ptr += mod_strcspn(ptr, ",") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
}
for (i = 0; i < avctx->height; i++) {
dst = (uint32_t *)(p->data[0] + i * p->linesize[0]);
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
ptr += mod_strcspn(ptr, "\"") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
for (j = 0; j < avctx->width; j++) {
if (end - ptr < cpp)
return AVERROR_INVALIDDATA;
if ((ret = ascii2index(ptr, cpp)) < 0)
return ret;
*dst++ = x->pixels[ret];
ptr += cpp;
}
ptr += mod_strcspn(ptr, ",") + 1;
}
p->key_frame = 1;
p->pict_type = AV_PICTURE_TYPE_I;
*got_frame = 1;
return avpkt->size;
}
| 168,078
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DataReductionProxyConfig::FetchWarmupProbeURL() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!enabled_by_user_) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kProxyNotEnabledByUser);
return;
}
if (!params::FetchWarmupProbeURLEnabled()) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kWarmupURLFetchingDisabled);
return;
}
if (connection_type_ == network::mojom::ConnectionType::CONNECTION_NONE) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kConnectionTypeNone);
return;
}
base::Optional<DataReductionProxyServer> warmup_proxy =
GetProxyConnectionToProbe();
if (!warmup_proxy)
return;
warmup_url_fetch_in_flight_secure_proxy_ = warmup_proxy->IsSecureProxy();
warmup_url_fetch_in_flight_core_proxy_ = warmup_proxy->IsCoreProxy();
size_t previous_attempt_counts = GetWarmupURLFetchAttemptCounts();
network_properties_manager_->OnWarmupFetchInitiated(
warmup_url_fetch_in_flight_secure_proxy_,
warmup_url_fetch_in_flight_core_proxy_);
RecordWarmupURLFetchAttemptEvent(WarmupURLFetchAttemptEvent::kFetchInitiated);
warmup_url_fetcher_->FetchWarmupURL(previous_attempt_counts,
warmup_proxy.value());
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <tbansal@chromium.org>
Reviewed-by: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416
|
void DataReductionProxyConfig::FetchWarmupProbeURL() {
DCHECK(thread_checker_.CalledOnValidThread());
if (params::IsIncludedInHoldbackFieldTrial())
return;
if (!enabled_by_user_) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kProxyNotEnabledByUser);
return;
}
if (!params::FetchWarmupProbeURLEnabled()) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kWarmupURLFetchingDisabled);
return;
}
if (connection_type_ == network::mojom::ConnectionType::CONNECTION_NONE) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kConnectionTypeNone);
return;
}
base::Optional<DataReductionProxyServer> warmup_proxy =
GetProxyConnectionToProbe();
if (!warmup_proxy)
return;
warmup_url_fetch_in_flight_secure_proxy_ = warmup_proxy->IsSecureProxy();
warmup_url_fetch_in_flight_core_proxy_ = warmup_proxy->IsCoreProxy();
size_t previous_attempt_counts = GetWarmupURLFetchAttemptCounts();
network_properties_manager_->OnWarmupFetchInitiated(
warmup_url_fetch_in_flight_secure_proxy_,
warmup_url_fetch_in_flight_core_proxy_);
RecordWarmupURLFetchAttemptEvent(WarmupURLFetchAttemptEvent::kFetchInitiated);
warmup_url_fetcher_->FetchWarmupURL(previous_attempt_counts,
warmup_proxy.value());
}
| 172,415
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[8] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, 8);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, sizeof iv);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
| 169,053
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.