prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: unsigned long long Track::GetUid() const
{
return m_info.uid;
}
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
Target: 1
Example 2:
Code: static int efx_probe_eventq(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
unsigned long entries;
netif_dbg(channel->efx, probe, channel->efx->net_dev,
"chan %d create event queue\n", channel->channel);
/* Build an event queue with room for one event per tx and rx buffer,
* plus some extra for link state events and MCDI completions. */
entries = roundup_pow_of_two(efx->rxq_entries + efx->txq_entries + 128);
EFX_BUG_ON_PARANOID(entries > EFX_MAX_EVQ_SIZE);
channel->eventq_mask = max(entries, EFX_MIN_EVQ_SIZE) - 1;
return efx_nic_probe_eventq(channel);
}
Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size
[ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ]
Currently an skb requiring TSO may not fit within a minimum-size TX
queue. The TX queue selected for the skb may stall and trigger the TX
watchdog repeatedly (since the problem skb will be retried after the
TX reset). This issue is designated as CVE-2012-3412.
Set the maximum number of TSO segments for our devices to 100. This
should make no difference to behaviour unless the actual MSS is less
than about 700. Increase the minimum TX queue size accordingly to
allow for 2 worst-case skbs, so that there will definitely be space
to add an skb after we wake a queue.
To avoid invalidating existing configurations, change
efx_ethtool_set_ringparam() to fix up values that are too small rather
than returning -EINVAL.
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gx_outputfile_is_separate_pages(const char *fname, gs_memory_t *memory)
{
const char *fmt;
gs_parsed_file_name_t parsed;
int code = gx_parse_output_file_name(&parsed, &fmt, fname,
strlen(fname), memory);
return (code >= 0 && fmt != 0);
}
Commit Message:
CWE ID: CWE-78
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *isk = inet_sk(sk);
int family = sk->sk_family;
struct sockaddr_in *sin;
struct sockaddr_in6 *sin6;
struct sk_buff *skb;
int copied, err;
pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
err = -EOPNOTSUPP;
if (flags & MSG_OOB)
goto out;
if (addr_len) {
if (family == AF_INET)
*addr_len = sizeof(*sin);
else if (family == AF_INET6 && addr_len)
*addr_len = sizeof(*sin6);
}
if (flags & MSG_ERRQUEUE) {
if (family == AF_INET) {
return ip_recv_error(sk, msg, len);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
return pingv6_ops.ipv6_recv_error(sk, msg, len);
#endif
}
}
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* Don't bother checking the checksum */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_timestamp(msg, sk, skb);
/* Copy the address and add cmsg data. */
if (family == AF_INET) {
sin = (struct sockaddr_in *) msg->msg_name;
sin->sin_family = AF_INET;
sin->sin_port = 0 /* skb->h.uh->source */;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
if (isk->cmsg_flags)
ip_cmsg_recv(msg, skb);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6hdr *ip6 = ipv6_hdr(skb);
sin6 = (struct sockaddr_in6 *) msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ip6->saddr;
sin6->sin6_flowinfo = 0;
if (np->sndflow)
sin6->sin6_flowinfo = ip6_flowinfo(ip6);
sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
if (inet6_sk(sk)->rxopt.all)
pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);
#endif
} else {
BUG();
}
err = copied;
done:
skb_free_datagram(sk, skb);
out:
pr_debug("ping_recvmsg -> %d\n", err);
return err;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: FrameFetchContext::FrameFetchContext(DocumentLoader* loader, Document* document)
: document_loader_(loader),
document_(document),
save_data_enabled_(GetNetworkStateNotifier().SaveDataEnabled() &&
!GetSettings()->GetDataSaverHoldbackWebApi()) {
if (document_) {
fetch_client_settings_object_ =
new FetchClientSettingsObjectImpl(*document_);
}
DCHECK(GetFrame());
}
Commit Message: Do not forward resource timing to parent frame after back-forward navigation
LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to
send timing info to parent except for the first navigation. This flag is
cleared when the first timing is sent to parent, however this does not happen
if iframe's first navigation was by back-forward navigation. For such
iframes, we shouldn't send timings to parent at all.
Bug: 876822
Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5
Reviewed-on: https://chromium-review.googlesource.com/1186215
Reviewed-by: Kinuko Yasuda <[email protected]>
Commit-Queue: Kunihiko Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#585736}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void TearDown() {
content::GetContentClient()->set_browser(old_browser_client_);
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void HttpAuthFilterWhitelist::SetWhitelist(
const std::string& server_whitelist) {
rules_.ParseFromString(server_whitelist);
}
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void SVGElement::SetNeedsStyleRecalcForInstances(
StyleChangeType change_type,
const StyleChangeReasonForTracing& reason) {
const HeapHashSet<WeakMember<SVGElement>>& set = InstancesForElement();
if (set.IsEmpty())
return;
for (SVGElement* instance : set)
instance->SetNeedsStyleRecalc(change_type, reason);
}
Commit Message: Fix SVG crash for v0 distribution into foreignObject.
We require a parent element to be an SVG element for non-svg-root
elements in order to create a LayoutObject for them. However, we checked
the light tree parent element, not the flat tree one which is the parent
for the layout tree construction. Note that this is just an issue in
Shadow DOM v0 since v1 does not allow shadow roots on SVG elements.
Bug: 915469
Change-Id: Id81843abad08814fae747b5bc81c09666583f130
Reviewed-on: https://chromium-review.googlesource.com/c/1382494
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#617487}
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGL2RenderingContextBase::UnregisterGetBufferSubDataAsyncCallback(
WebGLGetBufferSubDataAsyncCallback* callback) {
get_buffer_sub_data_async_callbacks_.erase(callback);
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
struct segment *seg;
/* Check that the playlist is still needed before opening a new
* segment. */
if (v->ctx && v->ctx->nb_streams) {
v->needed = 0;
for (i = 0; i < v->n_main_streams; i++) {
if (v->main_streams[i]->discard < AVDISCARD_ALL) {
v->needed = 1;
break;
}
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
/* If this is a live stream and the reload interval has elapsed since
* the last playlist reload, reload the playlists now. */
reload_interval = default_reload_interval(v);
reload:
if (!v->finished &&
av_gettime_relative() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
/* If we need to reload the playlist again below (if
* there's still no more segments), switch to a reload
* interval of half the target duration. */
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime_relative() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
/* Enough time has elapsed since the last reload */
goto reload;
}
seg = current_segment(v);
/* load/update Media Initialization Section, if any */
ret = update_init_section(v, seg);
if (ret)
return ret;
ret = open_input(c, v, seg);
if (ret < 0) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
v->cur_seq_no += 1;
goto reload;
}
just_opened = 1;
}
if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
/* Push init section out first before first actual segment */
int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
memcpy(buf, v->init_sec_buf, copy_size);
v->init_sec_buf_read_offset += copy_size;
return copy_size;
}
ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
/* Intercept ID3 tags here, elementary audio streams are required
* to convey timestamps using them in the beginning of each segment. */
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ff_format_io_close(v->parent, &v->input);
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
}
Commit Message: avformat/hls: Fix DoS due to infinite loop
Fixes: loop.m3u
The default max iteration count of 1000 is arbitrary and ideas for a better solution are welcome
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Previous version reviewed-by: Steven Liu <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-835
Target: 1
Example 2:
Code: __xml_log_element(int log_level, const char *file, const char *function, int line,
const char *prefix, xmlNode * data, int depth, int options)
{
int max = 0;
int offset = 0;
const char *name = NULL;
const char *hidden = NULL;
xmlNode *child = NULL;
xmlAttrPtr pIter = NULL;
if(data == NULL) {
return;
}
name = crm_element_name(data);
if(is_set(options, xml_log_option_open)) {
char *buffer = NULL;
insert_prefix(options, &buffer, &offset, &max, depth);
if(data->type == XML_COMMENT_NODE) {
buffer_print(buffer, max, offset, "<!--");
buffer_print(buffer, max, offset, "%s", data->content);
buffer_print(buffer, max, offset, "-->");
} else {
buffer_print(buffer, max, offset, "<%s", name);
}
hidden = crm_element_value(data, "hidden");
for (pIter = crm_first_attr(data); pIter != NULL; pIter = pIter->next) {
xml_private_t *p = pIter->_private;
const char *p_name = (const char *)pIter->name;
const char *p_value = crm_attr_value(pIter);
char *p_copy = NULL;
if(is_set(p->flags, xpf_deleted)) {
continue;
} else if ((is_set(options, xml_log_option_diff_plus)
|| is_set(options, xml_log_option_diff_minus))
&& strcmp(XML_DIFF_MARKER, p_name) == 0) {
continue;
} else if (hidden != NULL && p_name[0] != 0 && strstr(hidden, p_name) != NULL) {
p_copy = strdup("*****");
} else {
p_copy = crm_xml_escape(p_value);
}
buffer_print(buffer, max, offset, " %s=\"%s\"", p_name, p_copy);
free(p_copy);
}
if(xml_has_children(data) == FALSE) {
buffer_print(buffer, max, offset, "/>");
} else if(is_set(options, xml_log_option_children)) {
buffer_print(buffer, max, offset, ">");
} else {
buffer_print(buffer, max, offset, "/>");
}
do_crm_log_alias(log_level, file, function, line, "%s %s", prefix, buffer);
free(buffer);
}
if(data->type == XML_COMMENT_NODE) {
return;
} else if(xml_has_children(data) == FALSE) {
return;
} else if(is_set(options, xml_log_option_children)) {
offset = 0;
max = 0;
for (child = __xml_first_child(data); child != NULL; child = __xml_next(child)) {
__xml_log_element(log_level, file, function, line, prefix, child, depth + 1, options|xml_log_option_open|xml_log_option_close);
}
}
if(is_set(options, xml_log_option_close)) {
char *buffer = NULL;
insert_prefix(options, &buffer, &offset, &max, depth);
buffer_print(buffer, max, offset, "</%s>", name);
do_crm_log_alias(log_level, file, function, line, "%s %s", prefix, buffer);
free(buffer);
}
}
Commit Message: Fix: acl: Do not delay evaluation of added nodes in some situations
It is not appropriate when the node has no children as it is not a
placeholder
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: EncodedJSValue JSC_HOST_CALL JSTestObjConstructor::constructJSTestObj(ExecState* exec)
{
JSTestObjConstructor* castedThis = jsCast<JSTestObjConstructor*>(exec->callee());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> testCallback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject());
RefPtr<TestObj> object = TestObj::create(testCallback);
return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get())));
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void TextTrackCue::setEndTime(double value) {
if (end_time_ == value || value < 0)
return;
CueWillChange();
end_time_ = value;
CueDidChange(kCueMutationAffectsOrder);
}
Commit Message: Support negative timestamps of TextTrackCue
Ensure proper behaviour for negative timestamps of TextTrackCue.
1. Cues with negative startTime should become active from 0s.
2. Cues with negative startTime and endTime should never be active.
Bug: 314032
Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d
Reviewed-on: https://chromium-review.googlesource.com/863270
Commit-Queue: srirama chandra sekhar <[email protected]>
Reviewed-by: Fredrik Söderquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529012}
CWE ID:
Target: 1
Example 2:
Code: bool WebGLRenderingContextBase::ExtensionTracker::MatchesNameWithPrefixes(
const String& name) const {
const char* const* prefix_set = Prefixes();
for (; *prefix_set; ++prefix_set) {
String prefixed_name = String(*prefix_set) + ExtensionName();
if (DeprecatedEqualIgnoringCase(prefixed_name, name)) {
return true;
}
}
return false;
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int lstats_show_proc(struct seq_file *m, void *v)
{
int i;
struct inode *inode = m->private;
struct task_struct *task = get_proc_task(inode);
if (!task)
return -ESRCH;
seq_puts(m, "Latency Top version : v0.1\n");
for (i = 0; i < 32; i++) {
struct latency_record *lr = &task->latency_record[i];
if (lr->backtrace[0]) {
int q;
seq_printf(m, "%i %li %li",
lr->count, lr->time, lr->max);
for (q = 0; q < LT_BACKTRACEDEPTH; q++) {
unsigned long bt = lr->backtrace[q];
if (!bt)
break;
if (bt == ULONG_MAX)
break;
seq_printf(m, " %ps", (void *)bt);
}
seq_putc(m, '\n');
}
}
put_task_struct(task);
return 0;
}
Commit Message: proc: restrict access to /proc/PID/io
/proc/PID/io may be used for gathering private information. E.g. for
openssh and vsftpd daemons wchars/rchars may be used to learn the
precise password length. Restrict it to processes being able to ptrace
the target process.
ptrace_may_access() is needed to prevent keeping open file descriptor of
"io" file, executing setuid binary and gathering io information of the
setuid'ed process.
Signed-off-by: Vasiliy Kulikov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
length;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth == 0) || (sun_info.depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->storage_class=PseudoClass;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
}
switch (sun_info.maptype)
{
case RMT_NONE:
{
if (sun_info.depth < 24)
{
/*
Create linear color ramp.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
break;
}
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=
sun_info.length || !sun_info.length)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) &&
((number_pixels*((sun_info.depth+7)/8)) > sun_info.length))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
sun_pixels=sun_data;
bytes_per_line=0;
if (sun_info.type == RT_ENCODED)
{
size_t
height;
/*
Read run-length encoded raster pixels.
*/
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line>>=4;
sun_pixels=(unsigned char *) AcquireQuantumMemory(height,
bytes_per_line*sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*
height);
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
}
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
if (bytes_per_line == 0)
bytes_per_line=image->columns;
length=image->rows*(image->columns+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
length=image->rows*(bytes_per_line+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=26848
CWE ID: CWE-119
Target: 1
Example 2:
Code: void LayoutBlockFlow::moveAllChildrenIncludingFloatsTo(LayoutBlock* toBlock, bool fullRemoveInsert)
{
LayoutBlockFlow* toBlockFlow = toLayoutBlockFlow(toBlock);
moveAllChildrenTo(toBlockFlow, fullRemoveInsert);
if (m_floatingObjects) {
if (!toBlockFlow->m_floatingObjects)
toBlockFlow->createFloatingObjects();
const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = fromFloatingObjectSet.end();
for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
const FloatingObject& floatingObject = *it->get();
if (toBlockFlow->containsFloat(floatingObject.layoutObject()))
continue;
toBlockFlow->m_floatingObjects->add(floatingObject.unsafeClone());
}
}
}
Commit Message: Consistently check if a block can handle pagination strut propagation.
https://codereview.chromium.org/1360753002 got it right for inline child
layout, but did nothing for block child layout.
BUG=329421
[email protected],[email protected]
Review URL: https://codereview.chromium.org/1387553002
Cr-Commit-Position: refs/heads/master@{#352429}
CWE ID: CWE-22
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static char *dex_class_name(RBinDexObj *bin, RBinDexClass *c) {
return dex_class_name_byid (bin, c->class_id);
}
Commit Message: fix #6872
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
PNG_CONST char *name)
{
/* Do this first so that the modifier fields are cleared even if an error
* happens allocating the png_struct. No allocation is done here so no
* cleanup is required.
*/
pm->state = modifier_start;
pm->bit_depth = 0;
pm->colour_type = 255;
pm->pending_len = 0;
pm->pending_chunk = 0;
pm->flush = 0;
pm->buffer_count = 0;
pm->buffer_position = 0;
return set_store_for_read(&pm->this, ppi, id, name);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: bool CanRequestURL(const GURL& url) {
DCHECK(!url.SchemeIsBlob() && !url.SchemeIsFileSystem())
<< "inner_url extraction should be done already.";
auto scheme_judgment = scheme_map_.find(url.scheme());
if (scheme_judgment != scheme_map_.end())
return true;
if (CanRequestOrigin(url::Origin::Create(url)))
return true;
return CanCommitURL(url);
}
Commit Message: Lock down blob/filesystem URL creation with a stronger CPSP::CanCommitURL()
ChildProcessSecurityPolicy::CanCommitURL() is a security check that's
supposed to tell whether a given renderer process is allowed to commit
a given URL. It is currently used to validate (1) blob and filesystem
URL creation, and (2) Origin headers. Currently, it has scheme-based
checks that disallow things like web renderers creating
blob/filesystem URLs in chrome-extension: origins, but it cannot stop
one web origin from creating those URLs for another origin.
This CL locks down its use for (1) to also consult
CanAccessDataForOrigin(). With site isolation, this will check origin
locks and ensure that foo.com cannot create blob/filesystem URLs for
other origins.
For now, this CL does not provide the same enforcements for (2),
Origin header validation, which has additional constraints that need
to be solved first (see https://crbug.com/515309).
Bug: 886976, 888001
Change-Id: I743ef05469e4000b2c0bee840022162600cc237f
Reviewed-on: https://chromium-review.googlesource.com/1235343
Commit-Queue: Alex Moshchuk <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#594914}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool NavigatorImpl::NavigateToPendingEntry(
FrameTreeNode* frame_tree_node,
const FrameNavigationEntry& frame_entry,
ReloadType reload_type,
bool is_same_document_history_load) {
return NavigateToEntry(frame_tree_node, frame_entry,
*controller_->GetPendingEntry(), reload_type,
is_same_document_history_load, false, true, nullptr);
}
Commit Message: Correctly reset FP in RFHI whenever origin changes
Bug: 713364
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
Reviewed-on: https://chromium-review.googlesource.com/482380
Commit-Queue: Ian Clelland <[email protected]>
Reviewed-by: Charles Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#466778}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int parse_arguments(int *argc_p, const char ***argv_p)
{
static poptContext pc;
char *ref = lp_refuse_options(module_id);
const char *arg, **argv = *argv_p;
int argc = *argc_p;
int opt;
if (ref && *ref)
set_refuse_options(ref);
set_refuse_options("log-file*");
#ifdef ICONV_OPTION
if (!*lp_charset(module_id))
set_refuse_options("iconv");
#endif
}
Commit Message:
CWE ID:
Target: 1
Example 2:
Code: static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
{
kvm_init_shadow_mmu(vcpu, &vcpu->arch.mmu);
vcpu->arch.mmu.set_cr3 = nested_svm_set_tdp_cr3;
vcpu->arch.mmu.get_cr3 = nested_svm_get_tdp_cr3;
vcpu->arch.mmu.get_pdptr = nested_svm_get_tdp_pdptr;
vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
vcpu->arch.mmu.shadow_root_level = get_npt_level();
vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
}
Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR
Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is
written to certain MSRs. The behavior is "almost" identical for AMD and Intel
(ignoring MSRs that are not implemented in either architecture since they would
anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
non-canonical address is written on Intel but not on AMD (which ignores the top
32-bits).
Accordingly, this patch injects a #GP on the MSRs which behave identically on
Intel and AMD. To eliminate the differences between the architecutres, the
value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to
canonical value before writing instead of injecting a #GP.
Some references from Intel and AMD manuals:
According to Intel SDM description of WRMSR instruction #GP is expected on
WRMSR "If the source register contains a non-canonical address and ECX
specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE,
IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP."
According to AMD manual instruction manual:
LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the
LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical
form, a general-protection exception (#GP) occurs."
IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the
base field must be in canonical form or a #GP fault will occur."
IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must
be in canonical form."
This patch fixes CVE-2014-3610.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static EAS_RESULT Parse_wave (SDLS_SYNTHESIZER_DATA *pDLSData, EAS_I32 pos, EAS_U16 waveIndex)
{
EAS_RESULT result;
EAS_U32 temp;
EAS_I32 size;
EAS_I32 endChunk;
EAS_I32 chunkPos;
EAS_I32 wsmpPos = 0;
EAS_I32 fmtPos = 0;
EAS_I32 dataPos = 0;
EAS_I32 dataSize = 0;
S_WSMP_DATA *p;
void *pSample;
S_WSMP_DATA wsmp;
/* seek to start of chunk */
chunkPos = pos + 12;
if ((result = EAS_HWFileSeek(pDLSData->hwInstData, pDLSData->fileHandle, pos)) != EAS_SUCCESS)
return result;
/* get the chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* make sure it is a wave chunk */
if (temp != CHUNK_WAVE)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Offset in ptbl does not point to wave chunk\n"); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* read to end of chunk */
pos = chunkPos;
endChunk = pos + size;
while (pos < endChunk)
{
chunkPos = pos;
/* get the chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* parse useful chunks */
switch (temp)
{
case CHUNK_WSMP:
wsmpPos = chunkPos + 8;
break;
case CHUNK_FMT:
fmtPos = chunkPos + 8;
break;
case CHUNK_DATA:
dataPos = chunkPos + 8;
dataSize = size;
break;
default:
break;
}
}
if (dataSize > MAX_DLS_WAVE_SIZE)
{
return EAS_ERROR_SOUND_LIBRARY;
}
/* for first pass, use temporary variable */
if (pDLSData->pDLS == NULL)
p = &wsmp;
else
p = &pDLSData->wsmpData[waveIndex];
/* set the defaults */
p->fineTune = 0;
p->unityNote = 60;
p->gain = 0;
p->loopStart = 0;
p->loopLength = 0;
/* must have a fmt chunk */
if (!fmtPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no fmt chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a data chunk */
if (!dataPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no data chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* parse the wsmp chunk */
if (wsmpPos)
{
if ((result = Parse_wsmp(pDLSData, wsmpPos, p)) != EAS_SUCCESS)
return result;
}
/* parse the fmt chunk */
if ((result = Parse_fmt(pDLSData, fmtPos, p)) != EAS_SUCCESS)
return result;
/* calculate the size of the wavetable needed. We need only half
* the memory for 16-bit samples when in 8-bit mode, and we need
* double the memory for 8-bit samples in 16-bit mode. For
* unlooped samples, we may use ADPCM. If so, we need only 1/4
* the memory.
*
* We also need to add one for looped samples to allow for
* the first sample to be copied to the end of the loop.
*/
/* use ADPCM encode for unlooped 16-bit samples if ADPCM is enabled */
/*lint -e{506} -e{774} groundwork for future version to support 8 & 16 bit */
if (bitDepth == 8)
{
if (p->bitsPerSample == 8)
size = dataSize;
else
/*lint -e{704} use shift for performance */
size = dataSize >> 1;
if (p->loopLength)
size++;
}
else
{
if (p->bitsPerSample == 16)
size = dataSize;
else
/*lint -e{703} use shift for performance */
size = dataSize << 1;
if (p->loopLength)
size += 2;
}
/* for first pass, add size to wave pool size and return */
if (pDLSData->pDLS == NULL)
{
pDLSData->wavePoolSize += (EAS_U32) size;
return EAS_SUCCESS;
}
/* allocate memory and read in the sample data */
pSample = pDLSData->pDLS->pDLSSamples + pDLSData->wavePoolOffset;
pDLSData->pDLS->pDLSSampleOffsets[waveIndex] = pDLSData->wavePoolOffset;
pDLSData->pDLS->pDLSSampleLen[waveIndex] = (EAS_U32) size;
pDLSData->wavePoolOffset += (EAS_U32) size;
if (pDLSData->wavePoolOffset > pDLSData->wavePoolSize)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Wave pool exceeded allocation\n"); */ }
return EAS_ERROR_SOUND_LIBRARY;
}
if ((result = Parse_data(pDLSData, dataPos, dataSize, p, pSample)) != EAS_SUCCESS)
return result;
return EAS_SUCCESS;
}
Commit Message: DLS parser: fix wave pool size check.
Bug: 21132860.
Change-Id: I8ae872ea2cc2e8fec5fa0b7815f0b6b31ce744ff
(cherry picked from commit 2d7f8e1be2241e48458f5d3cab5e90be2b07c699)
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long VideoTrack::Parse(
Segment* pSegment,
const Info& info,
long long element_start,
long long element_size,
VideoTrack*& pResult)
{
if (pResult)
return -1;
if (info.type != Track::kVideo)
return -1;
long long width = 0;
long long height = 0;
double rate = 0.0;
IMkvReader* const pReader = pSegment->m_pReader;
const Settings& s = info.settings;
assert(s.start >= 0);
assert(s.size >= 0);
long long pos = s.start;
assert(pos >= 0);
const long long stop = pos + s.size;
while (pos < stop)
{
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x30) //pixel width
{
width = UnserializeUInt(pReader, pos, size);
if (width <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x3A) //pixel height
{
height = UnserializeUInt(pReader, pos, size);
if (height <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0383E3) //frame rate
{
const long status = UnserializeFloat(
pReader,
pos,
size,
rate);
if (status < 0)
return status;
if (rate <= 0)
return E_FILE_FORMAT_INVALID;
}
pos += size; //consume payload
assert(pos <= stop);
}
assert(pos == stop);
VideoTrack* const pTrack = new (std::nothrow) VideoTrack(pSegment,
element_start,
element_size);
if (pTrack == NULL)
return -1; //generic error
const int status = info.Copy(pTrack->m_info);
if (status) // error
{
delete pTrack;
return status;
}
pTrack->m_width = width;
pTrack->m_height = height;
pTrack->m_rate = rate;
pResult = pTrack;
return 0; //success
}
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
Target: 1
Example 2:
Code: bool RunAllPending(content::WebContents* web_contents) {
if (!content::ExecuteScript(web_contents, "1 == 1;"))
return false;
base::RunLoop().RunUntilIdle();
return true;
}
Commit Message: Extensions: Prevent content script injection in the New tab Page.
r487664 disallowed content script injection in the New Tab Page. However, the
check in RendererPermissionsPolicyDelegate::IsRestrictedUrl for the same, might
not work due to the following reasons:
- There might be a race between checking if the extension can inject the
script and setting the new tab url in the renderer (SearchBouncer).
- The New Tab page url in the SearchBouncer might be set incorrectly due to
incorrect handling of multiple profiles by InstantService.
Fix this by checking if the current renderer process is an Instant (NTP)
renderer. This should work since the NTP renderer process should not be shared
with other sites.
BUG=844428, 662610
Change-Id: I45f6b27fb2680d3b8df6e1da223452ffee09b0d8
Reviewed-on: https://chromium-review.googlesource.com/1068607
Reviewed-by: Devlin <[email protected]>
Commit-Queue: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563031}
CWE ID: CWE-285
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Image *ReadTILEImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image,
*tile_image;
ImageInfo
*read_info;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
*read_info->magick='\0';
tile_image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (tile_image == (Image *) NULL)
return((Image *) NULL);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if (*image_info->filename == '\0')
ThrowReaderException(OptionError,"MustSpecifyAnImageName");
image->colorspace=tile_image->colorspace;
image->matte=tile_image->matte;
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(image);
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
if (LocaleCompare(tile_image->magick,"PATTERN") == 0)
{
tile_image->tile_offset.x=0;
tile_image->tile_offset.y=0;
}
(void) TextureImage(image,tile_image);
tile_image=DestroyImage(tile_image);
if (image->colorspace == GRAYColorspace)
image->type=GrayscaleType;
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: v8::Handle<v8::Value> V8DataView::getUint8Callback(const v8::Arguments& args)
{
INC_STATS("DOM.DataView.getUint8");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
DataView* imp = V8DataView::toNative(args.Holder());
ExceptionCode ec = 0;
EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0]));
uint8_t result = imp->getUint8(byteOffset, ec);
if (UNLIKELY(ec)) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
return v8::Integer::New(result);
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 1
Example 2:
Code: static jas_seqent_t pgx_wordtoint(uint_fast32_t v, int prec, bool sgnd)
{
jas_seqent_t ret;
v &= (1 << prec) - 1;
ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v;
return ret;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int sctp_register_pf(struct sctp_pf *pf, sa_family_t family)
{
switch (family) {
case PF_INET:
if (sctp_pf_inet_specific)
return 0;
sctp_pf_inet_specific = pf;
break;
case PF_INET6:
if (sctp_pf_inet6_specific)
return 0;
sctp_pf_inet6_specific = pf;
break;
default:
return 0;
}
return 1;
}
Commit Message: sctp: fix race on protocol/netns initialization
Consider sctp module is unloaded and is being requested because an user
is creating a sctp socket.
During initialization, sctp will add the new protocol type and then
initialize pernet subsys:
status = sctp_v4_protosw_init();
if (status)
goto err_protosw_init;
status = sctp_v6_protosw_init();
if (status)
goto err_v6_protosw_init;
status = register_pernet_subsys(&sctp_net_ops);
The problem is that after those calls to sctp_v{4,6}_protosw_init(), it
is possible for userspace to create SCTP sockets like if the module is
already fully loaded. If that happens, one of the possible effects is
that we will have readers for net->sctp.local_addr_list list earlier
than expected and sctp_net_init() does not take precautions while
dealing with that list, leading to a potential panic but not limited to
that, as sctp_sock_init() will copy a bunch of blank/partially
initialized values from net->sctp.
The race happens like this:
CPU 0 | CPU 1
socket() |
__sock_create | socket()
inet_create | __sock_create
list_for_each_entry_rcu( |
answer, &inetsw[sock->type], |
list) { | inet_create
/* no hits */ |
if (unlikely(err)) { |
... |
request_module() |
/* socket creation is blocked |
* the module is fully loaded |
*/ |
sctp_init |
sctp_v4_protosw_init |
inet_register_protosw |
list_add_rcu(&p->list, |
last_perm); |
| list_for_each_entry_rcu(
| answer, &inetsw[sock->type],
sctp_v6_protosw_init | list) {
| /* hit, so assumes protocol
| * is already loaded
| */
| /* socket creation continues
| * before netns is initialized
| */
register_pernet_subsys |
Simply inverting the initialization order between
register_pernet_subsys() and sctp_v4_protosw_init() is not possible
because register_pernet_subsys() will create a control sctp socket, so
the protocol must be already visible by then. Deferring the socket
creation to a work-queue is not good specially because we loose the
ability to handle its errors.
So, as suggested by Vlad, the fix is to split netns initialization in
two moments: defaults and control socket, so that the defaults are
already loaded by when we register the protocol, while control socket
initialization is kept at the same moment it is today.
Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace")
Signed-off-by: Vlad Yasevich <[email protected]>
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
Target: 1
Example 2:
Code: void hns_rcbv2_int_ctrl_hw(struct hnae_queue *q, u32 flag, u32 mask)
{
u32 int_mask_en = !!mask;
if (flag & RCB_INT_FLAG_TX)
dsaf_write_dev(q, RCB_RING_INTMSK_TXWL_REG, int_mask_en);
if (flag & RCB_INT_FLAG_RX)
dsaf_write_dev(q, RCB_RING_INTMSK_RXWL_REG, int_mask_en);
}
Commit Message: net: hns: fix ethtool_get_strings overflow in hns driver
hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated
is not enough for ethtool_get_strings(), which will cause random memory
corruption.
When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the
the following can be observed without this patch:
[ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80
[ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070.
[ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70)
[ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk
[ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k
[ 43.115218] Next obj: start=ffff801fb0b69098, len=80
[ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b.
[ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38)
[ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_
[ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai
Signed-off-by: Timmy Li <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: magic_setparam(struct magic_set *ms, int param, const void *val)
{
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
ms->indir_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_NAME_MAX:
ms->name_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
ms->elf_phnum_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
ms->elf_shnum_max = *(const size_t *)val;
return 0;
default:
errno = EINVAL;
return -1;
}
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OmniboxPopupViewGtk::~OmniboxPopupViewGtk() {
model_.reset();
g_object_unref(layout_);
gtk_widget_destroy(window_);
for (ImageMap::iterator it = images_.begin(); it != images_.end(); ++it)
delete it->second;
}
Commit Message: GTK: Stop listening to gtk signals in the omnibox before destroying the model.
BUG=123530
TEST=none
Review URL: http://codereview.chromium.org/10103012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132498 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void hns_tx_timeout_reset(struct hns_nic_priv *priv)
{
/* Do the reset outside of interrupt context */
if (!test_bit(NIC_STATE_DOWN, &priv->state)) {
set_bit(NIC_STATE2_RESET_REQUESTED, &priv->state);
netdev_warn(priv->netdev,
"initiating reset due to tx timeout(%llu,0x%lx)\n",
priv->tx_timeout_count, priv->state);
priv->tx_timeout_count++;
hns_nic_task_schedule(priv);
}
}
Commit Message: net: hns: Fix a skb used after free bug
skb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK,
which cause hns_nic_net_xmit to use a freed skb.
BUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940...
[17659.112635] alloc_debug_processing+0x18c/0x1a0
[17659.117208] __slab_alloc+0x52c/0x560
[17659.120909] kmem_cache_alloc_node+0xac/0x2c0
[17659.125309] __alloc_skb+0x6c/0x260
[17659.128837] tcp_send_ack+0x8c/0x280
[17659.132449] __tcp_ack_snd_check+0x9c/0xf0
[17659.136587] tcp_rcv_established+0x5a4/0xa70
[17659.140899] tcp_v4_do_rcv+0x27c/0x620
[17659.144687] tcp_prequeue_process+0x108/0x170
[17659.149085] tcp_recvmsg+0x940/0x1020
[17659.152787] inet_recvmsg+0x124/0x180
[17659.156488] sock_recvmsg+0x64/0x80
[17659.160012] SyS_recvfrom+0xd8/0x180
[17659.163626] __sys_trace_return+0x0/0x4
[17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13
[17659.174000] free_debug_processing+0x1d4/0x2c0
[17659.178486] __slab_free+0x240/0x390
[17659.182100] kmem_cache_free+0x24c/0x270
[17659.186062] kfree_skbmem+0xa0/0xb0
[17659.189587] __kfree_skb+0x28/0x40
[17659.193025] napi_gro_receive+0x168/0x1c0
[17659.197074] hns_nic_rx_up_pro+0x58/0x90
[17659.201038] hns_nic_rx_poll_one+0x518/0xbc0
[17659.205352] hns_nic_common_poll+0x94/0x140
[17659.209576] net_rx_action+0x458/0x5e0
[17659.213363] __do_softirq+0x1b8/0x480
[17659.217062] run_ksoftirqd+0x64/0x80
[17659.220679] smpboot_thread_fn+0x224/0x310
[17659.224821] kthread+0x150/0x170
[17659.228084] ret_from_fork+0x10/0x40
BUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0...
[17751.080490] __slab_alloc+0x52c/0x560
[17751.084188] kmem_cache_alloc+0x244/0x280
[17751.088238] __build_skb+0x40/0x150
[17751.091764] build_skb+0x28/0x100
[17751.095115] __alloc_rx_skb+0x94/0x150
[17751.098900] __napi_alloc_skb+0x34/0x90
[17751.102776] hns_nic_rx_poll_one+0x180/0xbc0
[17751.107097] hns_nic_common_poll+0x94/0x140
[17751.111333] net_rx_action+0x458/0x5e0
[17751.115123] __do_softirq+0x1b8/0x480
[17751.118823] run_ksoftirqd+0x64/0x80
[17751.122437] smpboot_thread_fn+0x224/0x310
[17751.126575] kthread+0x150/0x170
[17751.129838] ret_from_fork+0x10/0x40
[17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43
[17751.139951] free_debug_processing+0x1d4/0x2c0
[17751.144436] __slab_free+0x240/0x390
[17751.148051] kmem_cache_free+0x24c/0x270
[17751.152014] kfree_skbmem+0xa0/0xb0
[17751.155543] __kfree_skb+0x28/0x40
[17751.159022] napi_gro_receive+0x168/0x1c0
[17751.163074] hns_nic_rx_up_pro+0x58/0x90
[17751.167041] hns_nic_rx_poll_one+0x518/0xbc0
[17751.171358] hns_nic_common_poll+0x94/0x140
[17751.175585] net_rx_action+0x458/0x5e0
[17751.179373] __do_softirq+0x1b8/0x480
[17751.183076] run_ksoftirqd+0x64/0x80
[17751.186691] smpboot_thread_fn+0x224/0x310
[17751.190826] kthread+0x150/0x170
[17751.194093] ret_from_fork+0x10/0x40
Fixes: 13ac695e7ea1 ("net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem")
Signed-off-by: Yunsheng Lin <[email protected]>
Signed-off-by: lipeng <[email protected]>
Reported-by: Jun He <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static uint32_t FilterKey(Handle<SeededNumberDictionary> dictionary,
int entry, Object* raw_key, PropertyFilter filter) {
DCHECK(!dictionary->IsDeleted(entry));
DCHECK(raw_key->IsNumber());
DCHECK_LE(raw_key->Number(), kMaxUInt32);
PropertyDetails details = dictionary->DetailsAt(entry);
PropertyAttributes attr = details.attributes();
if ((attr & filter) != 0) return kMaxUInt32;
return static_cast<uint32_t>(raw_key->Number());
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: hstore_from_arrays(PG_FUNCTION_ARGS)
{
int32 buflen;
HStore *out;
Pairs *pairs;
Datum *key_datums;
bool *key_nulls;
int key_count;
Datum *value_datums;
bool *value_nulls;
int value_count;
ArrayType *key_array;
ArrayType *value_array;
int i;
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
key_array = PG_GETARG_ARRAYTYPE_P(0);
Assert(ARR_ELEMTYPE(key_array) == TEXTOID);
/*
* must check >1 rather than != 1 because empty arrays have 0 dimensions,
* not 1
*/
if (ARR_NDIM(key_array) > 1)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
deconstruct_array(key_array,
TEXTOID, -1, false, 'i',
&key_datums, &key_nulls, &key_count);
/* value_array might be NULL */
if (PG_ARGISNULL(1))
{
value_array = NULL;
value_count = key_count;
value_datums = NULL;
value_nulls = NULL;
}
else
{
value_array = PG_GETARG_ARRAYTYPE_P(1);
Assert(ARR_ELEMTYPE(value_array) == TEXTOID);
if (ARR_NDIM(value_array) > 1)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
if ((ARR_NDIM(key_array) > 0 || ARR_NDIM(value_array) > 0) &&
(ARR_NDIM(key_array) != ARR_NDIM(value_array) ||
ARR_DIMS(key_array)[0] != ARR_DIMS(value_array)[0] ||
ARR_LBOUND(key_array)[0] != ARR_LBOUND(value_array)[0]))
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("arrays must have same bounds")));
deconstruct_array(value_array,
TEXTOID, -1, false, 'i',
&value_datums, &value_nulls, &value_count);
Assert(key_count == value_count);
}
pairs = palloc(key_count * sizeof(Pairs));
for (i = 0; i < key_count; ++i)
{
if (key_nulls[i])
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null value not allowed for hstore key")));
if (!value_nulls || value_nulls[i])
{
pairs[i].key = VARDATA_ANY(key_datums[i]);
pairs[i].val = NULL;
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i]));
pairs[i].vallen = 4;
pairs[i].isnull = true;
pairs[i].needfree = false;
}
else
{
pairs[i].key = VARDATA_ANY(key_datums[i]);
pairs[i].val = VARDATA_ANY(value_datums[i]);
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i]));
pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(value_datums[i]));
pairs[i].isnull = false;
pairs[i].needfree = false;
}
}
key_count = hstoreUniquePairs(pairs, key_count, &buflen);
out = hstorePairs(pairs, key_count, buflen);
PG_RETURN_POINTER(out);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189
Target: 1
Example 2:
Code: void SkiaOutputSurfaceImpl::OnGpuVSync(base::TimeTicks timebase,
base::TimeDelta interval) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (gpu_vsync_callback_)
gpu_vsync_callback_.Run(timebase, interval);
}
Commit Message: SkiaRenderer: Support changing color space
SkiaOutputSurfaceImpl did not handle the color space changing after it
was created previously. The SkSurfaceCharacterization color space was
only set during the first time Reshape() ran when the charactization is
returned from the GPU thread. If the color space was changed later the
SkSurface and SkDDL color spaces no longer matched and draw failed.
Bug: 1009452
Change-Id: Ib6d2083efc7e7eb6f94782342e92a809b69d6fdc
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1841811
Reviewed-by: Peng Huang <[email protected]>
Commit-Queue: kylechar <[email protected]>
Cr-Commit-Position: refs/heads/master@{#702946}
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void blkdev_show(struct seq_file *seqf, off_t offset)
{
struct blk_major_name *dp;
if (offset < BLKDEV_MAJOR_HASH_SIZE) {
mutex_lock(&block_class_lock);
for (dp = major_names[offset]; dp; dp = dp->next)
seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
mutex_unlock(&block_class_lock);
}
}
Commit Message: block: fix use-after-free in seq file
I got a KASAN report of use-after-free:
==================================================================
BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508
Read of size 8 by task trinity-c1/315
=============================================================================
BUG kmalloc-32 (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315
___slab_alloc+0x4f1/0x520
__slab_alloc.isra.58+0x56/0x80
kmem_cache_alloc_trace+0x260/0x2a0
disk_seqf_start+0x66/0x110
traverse+0x176/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315
__slab_free+0x17a/0x2c0
kfree+0x20a/0x220
disk_seqf_stop+0x42/0x50
traverse+0x3b5/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014
ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480
ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480
ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970
Call Trace:
[<ffffffff81d6ce81>] dump_stack+0x65/0x84
[<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0
[<ffffffff814704ff>] object_err+0x2f/0x40
[<ffffffff814754d1>] kasan_report_error+0x221/0x520
[<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40
[<ffffffff83888161>] klist_iter_exit+0x61/0x70
[<ffffffff82404389>] class_dev_iter_exit+0x9/0x10
[<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50
[<ffffffff8151f812>] seq_read+0x4b2/0x11a0
[<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180
[<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210
[<ffffffff814b4c45>] do_readv_writev+0x565/0x660
[<ffffffff814b8a17>] vfs_readv+0x67/0xa0
[<ffffffff814b8de6>] do_preadv+0x126/0x170
[<ffffffff814b92ec>] SyS_preadv+0xc/0x10
This problem can occur in the following situation:
open()
- pread()
- .seq_start()
- iter = kmalloc() // succeeds
- seqf->private = iter
- .seq_stop()
- kfree(seqf->private)
- pread()
- .seq_start()
- iter = kmalloc() // fails
- .seq_stop()
- class_dev_iter_exit(seqf->private) // boom! old pointer
As the comment in disk_seqf_stop() says, stop is called even if start
failed, so we need to reinitialise the private pointer to NULL when seq
iteration stops.
An alternative would be to set the private pointer to NULL when the
kmalloc() in disk_seqf_start() fails.
Cc: [email protected]
Signed-off-by: Vegard Nossum <[email protected]>
Acked-by: Tejun Heo <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: report_error (const char *format, ...)
#else
report_error (format, va_alist)
const char *format;
va_dcl
#endif
{
va_list args;
error_prolog (1);
SH_VA_START (args, format);
vfprintf (stderr, format, args);
fprintf (stderr, "\n");
va_end (args);
if (exit_immediately_on_error)
exit_shell (1);
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
{
int rc = 0;
struct nls_table *nls_codepage;
struct cifs_ses *ses;
struct TCP_Server_Info *server;
/*
* SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
* check for tcp and smb session status done differently
* for those three - in the calling routine.
*/
if (tcon == NULL)
return rc;
if (smb2_command == SMB2_TREE_CONNECT)
return rc;
if (tcon->tidStatus == CifsExiting) {
/*
* only tree disconnect, open, and write,
* (and ulogoff which does not have tcon)
* are allowed as we start force umount.
*/
if ((smb2_command != SMB2_WRITE) &&
(smb2_command != SMB2_CREATE) &&
(smb2_command != SMB2_TREE_DISCONNECT)) {
cifs_dbg(FYI, "can not send cmd %d while umounting\n",
smb2_command);
return -ENODEV;
}
}
if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
(!tcon->ses->server))
return -EIO;
ses = tcon->ses;
server = ses->server;
/*
* Give demultiplex thread up to 10 seconds to reconnect, should be
* greater than cifs socket timeout which is 7 seconds
*/
while (server->tcpStatus == CifsNeedReconnect) {
/*
* Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
* here since they are implicitly done when session drops.
*/
switch (smb2_command) {
/*
* BB Should we keep oplock break and add flush to exceptions?
*/
case SMB2_TREE_DISCONNECT:
case SMB2_CANCEL:
case SMB2_CLOSE:
case SMB2_OPLOCK_BREAK:
return -EAGAIN;
}
wait_event_interruptible_timeout(server->response_q,
(server->tcpStatus != CifsNeedReconnect), 10 * HZ);
/* are we still trying to reconnect? */
if (server->tcpStatus != CifsNeedReconnect)
break;
/*
* on "soft" mounts we wait once. Hard mounts keep
* retrying until process is killed or server comes
* back on-line
*/
if (!tcon->retry) {
cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
return -EHOSTDOWN;
}
}
if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
return rc;
nls_codepage = load_nls_default();
/*
* need to prevent multiple threads trying to simultaneously reconnect
* the same SMB session
*/
mutex_lock(&tcon->ses->session_mutex);
rc = cifs_negotiate_protocol(0, tcon->ses);
if (!rc && tcon->ses->need_reconnect)
rc = cifs_setup_session(0, tcon->ses, nls_codepage);
if (rc || !tcon->need_reconnect) {
mutex_unlock(&tcon->ses->session_mutex);
goto out;
}
cifs_mark_open_files_invalid(tcon);
if (tcon->use_persistent)
tcon->need_reopen_files = true;
rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
mutex_unlock(&tcon->ses->session_mutex);
cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
if (rc)
goto out;
if (smb2_command != SMB2_INTERNAL_CMD)
queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
atomic_inc(&tconInfoReconnectCount);
out:
/*
* Check if handle based operation so we know whether we can continue
* or not without returning to caller to reset file handle.
*/
/*
* BB Is flush done by server on drop of tcp session? Should we special
* case it and skip above?
*/
switch (smb2_command) {
case SMB2_FLUSH:
case SMB2_READ:
case SMB2_WRITE:
case SMB2_LOCK:
case SMB2_IOCTL:
case SMB2_QUERY_DIRECTORY:
case SMB2_CHANGE_NOTIFY:
case SMB2_QUERY_INFO:
case SMB2_SET_INFO:
rc = -EAGAIN;
}
unload_nls(nls_codepage);
return rc;
}
Commit Message: CIFS: Enable encryption during session setup phase
In order to allow encryption on SMB connection we need to exchange
a session key and generate encryption and decryption keys.
Signed-off-by: Pavel Shilovsky <[email protected]>
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& es)
{
if (!root) {
es.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
UNUSED_PARAM(expandEntityReferences);
return NodeIterator::create(root, whatToShow, filter);
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
[email protected], abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int64 GetReceivedListPrefValue(size_t index) {
return ListPrefInt64Value(*received_update_, index);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void crypto_rng_show(struct seq_file *m, struct crypto_alg *alg)
{
seq_printf(m, "type : rng\n");
seq_printf(m, "seedsize : %u\n", alg->cra_rng.seedsize);
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool BrowserViewRenderer::CompositeHw() {
CancelFallbackTick();
ReturnResourceFromParent();
UpdateMemoryPolicy();
ParentCompositorDrawConstraints parent_draw_constraints =
shared_renderer_state_.GetParentDrawConstraintsOnUI();
gfx::Size surface_size(size_);
gfx::Rect viewport(surface_size);
gfx::Rect clip = viewport;
gfx::Transform transform_for_tile_priority =
parent_draw_constraints.transform;
gfx::Rect viewport_rect_for_tile_priority;
if (!offscreen_pre_raster_ && !parent_draw_constraints.is_layer) {
viewport_rect_for_tile_priority = last_on_draw_global_visible_rect_;
}
scoped_ptr<cc::CompositorFrame> frame =
compositor_->DemandDrawHw(surface_size,
gfx::Transform(),
viewport,
clip,
viewport_rect_for_tile_priority,
transform_for_tile_priority);
if (!frame.get()) {
TRACE_EVENT_INSTANT0("android_webview", "NoNewFrame",
TRACE_EVENT_SCOPE_THREAD);
return shared_renderer_state_.HasFrameOnUI();
}
scoped_ptr<ChildFrame> child_frame = make_scoped_ptr(
new ChildFrame(frame.Pass(), viewport_rect_for_tile_priority.IsEmpty(),
transform_for_tile_priority, offscreen_pre_raster_,
parent_draw_constraints.is_layer));
ReturnUnusedResource(shared_renderer_state_.PassUncommittedFrameOnUI());
shared_renderer_state_.SetCompositorFrameOnUI(child_frame.Pass());
return true;
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void ib_uverbs_release_dev(struct device *device)
{
struct ib_uverbs_device *dev =
container_of(device, struct ib_uverbs_device, dev);
uverbs_destroy_api(dev->uapi);
cleanup_srcu_struct(&dev->disassociate_srcu);
kfree(dev);
}
Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping
The core dumping code has always run without holding the mmap_sem for
writing, despite that is the only way to ensure that the entire vma
layout will not change from under it. Only using some signal
serialization on the processes belonging to the mm is not nearly enough.
This was pointed out earlier. For example in Hugh's post from Jul 2017:
https://lkml.kernel.org/r/[email protected]
"Not strictly relevant here, but a related note: I was very surprised
to discover, only quite recently, how handle_mm_fault() may be called
without down_read(mmap_sem) - when core dumping. That seems a
misguided optimization to me, which would also be nice to correct"
In particular because the growsdown and growsup can move the
vm_start/vm_end the various loops the core dump does around the vma will
not be consistent if page faults can happen concurrently.
Pretty much all users calling mmget_not_zero()/get_task_mm() and then
taking the mmap_sem had the potential to introduce unexpected side
effects in the core dumping code.
Adding mmap_sem for writing around the ->core_dump invocation is a
viable long term fix, but it requires removing all copy user and page
faults and to replace them with get_dump_page() for all binary formats
which is not suitable as a short term fix.
For the time being this solution manually covers the places that can
confuse the core dump either by altering the vma layout or the vma flags
while it runs. Once ->core_dump runs under mmap_sem for writing the
function mmget_still_valid() can be dropped.
Allowing mmap_sem protected sections to run in parallel with the
coredump provides some minor parallelism advantage to the swapoff code
(which seems to be safe enough by never mangling any vma field and can
keep doing swapins in parallel to the core dumping) and to some other
corner case.
In order to facilitate the backporting I added "Fixes: 86039bd3b4e6"
however the side effect of this same race condition in /proc/pid/mem
should be reproducible since before 2.6.12-rc2 so I couldn't add any
other "Fixes:" because there's no hash beyond the git genesis commit.
Because find_extend_vma() is the only location outside of the process
context that could modify the "mm" structures under mmap_sem for
reading, by adding the mmget_still_valid() check to it, all other cases
that take the mmap_sem for reading don't need the new check after
mmget_not_zero()/get_task_mm(). The expand_stack() in page fault
context also doesn't need the new check, because all tasks under core
dumping are frozen.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization")
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Jann Horn <[email protected]>
Suggested-by: Oleg Nesterov <[email protected]>
Acked-by: Peter Xu <[email protected]>
Reviewed-by: Mike Rapoport <[email protected]>
Reviewed-by: Oleg Nesterov <[email protected]>
Reviewed-by: Jann Horn <[email protected]>
Acked-by: Jason Gunthorpe <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool WtsSessionProcessDelegate::Core::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
CommandLine command_line(CommandLine::NO_PROGRAM);
if (launch_elevated_) {
if (!job_.IsValid()) {
return false;
}
FilePath daemon_binary;
if (!GetInstalledBinaryPath(kDaemonBinaryName, &daemon_binary))
return false;
command_line.SetProgram(daemon_binary);
command_line.AppendSwitchPath(kElevateSwitchName, binary_path_);
CHECK(ResetEvent(process_exit_event_));
} else {
command_line.SetProgram(binary_path_);
}
scoped_ptr<IPC::ChannelProxy> channel;
std::string channel_name = GenerateIpcChannelName(this);
if (!CreateIpcChannel(channel_name, channel_security_, io_task_runner_,
delegate, &channel))
return false;
command_line.AppendSwitchNative(kDaemonPipeSwitchName,
UTF8ToWide(channel_name));
command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(),
kCopiedSwitchNames,
arraysize(kCopiedSwitchNames));
ScopedHandle worker_process;
ScopedHandle worker_thread;
if (!LaunchProcessWithToken(command_line.GetProgram(),
command_line.GetCommandLineString(),
session_token_,
false,
CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB,
&worker_process,
&worker_thread)) {
return false;
}
HANDLE local_process_exit_event;
if (launch_elevated_) {
if (!AssignProcessToJobObject(job_, worker_process)) {
LOG_GETLASTERROR(ERROR)
<< "Failed to assign the worker to the job object";
TerminateProcess(worker_process, CONTROL_C_EXIT);
return false;
}
local_process_exit_event = process_exit_event_;
} else {
worker_process_ = worker_process.Pass();
local_process_exit_event = worker_process_;
}
if (!ResumeThread(worker_thread)) {
LOG_GETLASTERROR(ERROR) << "Failed to resume the worker thread";
KillProcess(CONTROL_C_EXIT);
return false;
}
ScopedHandle process_exit_event;
if (!DuplicateHandle(GetCurrentProcess(),
local_process_exit_event,
GetCurrentProcess(),
process_exit_event.Receive(),
SYNCHRONIZE,
FALSE,
0)) {
LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle";
KillProcess(CONTROL_C_EXIT);
return false;
}
channel_ = channel.Pass();
*process_exit_event_out = process_exit_event.Pass();
return true;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FFmpegVideoDecodeEngine::Initialize(
MessageLoop* message_loop,
VideoDecodeEngine::EventHandler* event_handler,
VideoDecodeContext* context,
const VideoDecoderConfig& config) {
static const int kDecodeThreads = 2;
static const int kMaxDecodeThreads = 16;
codec_context_ = avcodec_alloc_context();
codec_context_->pix_fmt = PIX_FMT_YUV420P;
codec_context_->codec_type = AVMEDIA_TYPE_VIDEO;
codec_context_->codec_id = VideoCodecToCodecID(config.codec());
codec_context_->coded_width = config.width();
codec_context_->coded_height = config.height();
frame_rate_numerator_ = config.frame_rate_numerator();
frame_rate_denominator_ = config.frame_rate_denominator();
if (config.extra_data() != NULL) {
codec_context_->extradata_size = config.extra_data_size();
codec_context_->extradata =
reinterpret_cast<uint8_t*>(av_malloc(config.extra_data_size()));
memcpy(codec_context_->extradata, config.extra_data(),
config.extra_data_size());
}
codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
codec_context_->error_recognition = FF_ER_CAREFUL;
AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ?
1 : kDecodeThreads;
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
if ((!threads.empty() &&
!base::StringToInt(threads, &decode_threads)) ||
decode_threads < 0 || decode_threads > kMaxDecodeThreads) {
decode_threads = kDecodeThreads;
}
av_frame_.reset(avcodec_alloc_frame());
VideoCodecInfo info;
info.success = false;
info.provides_buffers = true;
info.stream_info.surface_type = VideoFrame::TYPE_SYSTEM_MEMORY;
info.stream_info.surface_format = GetSurfaceFormat();
info.stream_info.surface_width = config.surface_width();
info.stream_info.surface_height = config.surface_height();
bool buffer_allocated = true;
frame_queue_available_.clear();
for (size_t i = 0; i < Limits::kMaxVideoFrames; ++i) {
scoped_refptr<VideoFrame> video_frame;
VideoFrame::CreateFrame(VideoFrame::YV12,
config.width(),
config.height(),
kNoTimestamp,
kNoTimestamp,
&video_frame);
if (!video_frame.get()) {
buffer_allocated = false;
break;
}
frame_queue_available_.push_back(video_frame);
}
if (codec &&
avcodec_thread_init(codec_context_, decode_threads) >= 0 &&
avcodec_open(codec_context_, codec) >= 0 &&
av_frame_.get() &&
buffer_allocated) {
info.success = true;
}
event_handler_ = event_handler;
event_handler_->OnInitializeComplete(info);
}
Commit Message: Don't forget the ffmpeg input buffer padding when allocating a codec's
extradata buffer.
BUG=82438
Review URL: http://codereview.chromium.org/7137002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: const char* XMLRPC_GetValueID(XMLRPC_VALUE value) {
return (const char*)((value && value->id.len) ? value->id.str : 0);
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void copyIPv6IfDifferent(void * dest, const void * src)
{
if(dest != src) {
memcpy(dest, src, sizeof(struct in6_addr));
}
}
Commit Message: pcpserver.c: copyIPv6IfDifferent() check for NULL src argument
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SelectionEditor::NodeChildrenWillBeRemoved(ContainerNode& container) {
if (selection_.IsNone())
return;
const Position old_base = selection_.base_;
const Position old_extent = selection_.extent_;
const Position& new_base =
ComputePositionForChildrenRemoval(old_base, container);
const Position& new_extent =
ComputePositionForChildrenRemoval(old_extent, container);
if (new_base == old_base && new_extent == old_extent)
return;
selection_ = SelectionInDOMTree::Builder()
.SetBaseAndExtent(new_base, new_extent)
.SetIsHandleVisible(selection_.IsHandleVisible())
.Build();
MarkCacheDirty();
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <[email protected]>
Reviewed-by: Xiaocheng Hu <[email protected]>
Reviewed-by: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119
Target: 1
Example 2:
Code: status_t OMX::setParameter(
node_id node, OMX_INDEXTYPE index,
const void *params, size_t size) {
ALOGV("setParameter(%u %#x %p %zd)", node, index, params, size);
return findInstance(node)->setParameter(
index, params, size);
}
Commit Message: Add VPX output buffer size check
and handle dead observers more gracefully
Bug: 27597103
Change-Id: Id7acb25d5ef69b197da15ec200a9e4f9e7b03518
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: rdpUpdate* update_new(rdpRdp* rdp)
{
const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL };
rdpUpdate* update;
OFFSCREEN_DELETE_LIST* deleteList;
update = (rdpUpdate*) calloc(1, sizeof(rdpUpdate));
if (!update)
return NULL;
update->log = WLog_Get("com.freerdp.core.update");
update->pointer = (rdpPointerUpdate*) calloc(1, sizeof(rdpPointerUpdate));
if (!update->pointer)
goto fail;
update->primary = (rdpPrimaryUpdate*) calloc(1, sizeof(rdpPrimaryUpdate));
if (!update->primary)
goto fail;
update->secondary = (rdpSecondaryUpdate*) calloc(1, sizeof(rdpSecondaryUpdate));
if (!update->secondary)
goto fail;
update->altsec = (rdpAltSecUpdate*) calloc(1, sizeof(rdpAltSecUpdate));
if (!update->altsec)
goto fail;
update->window = (rdpWindowUpdate*) calloc(1, sizeof(rdpWindowUpdate));
if (!update->window)
goto fail;
deleteList = &(update->altsec->create_offscreen_bitmap.deleteList);
deleteList->sIndices = 64;
deleteList->indices = calloc(deleteList->sIndices, 2);
if (!deleteList->indices)
goto fail;
deleteList->cIndices = 0;
update->SuppressOutput = update_send_suppress_output;
update->initialState = TRUE;
update->queue = MessageQueue_New(&cb);
if (!update->queue)
goto fail;
return update;
fail:
update_free(update);
return NULL;
}
Commit Message: Fixed CVE-2018-8786
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Encoder::Flush() {
const vpx_codec_err_t res = vpx_codec_encode(&encoder_, NULL, 0, 0, 0,
deadline_);
ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError();
}
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
Target: 1
Example 2:
Code: gdImagePtr gdImageCreateFromWBMPCtx (gdIOCtx * infile)
{
/* FILE *wbmp_file; */
Wbmp *wbmp;
gdImagePtr im = NULL;
int black, white;
int col, row, pos;
if (readwbmp (&gd_getin, infile, &wbmp)) {
return NULL;
}
if (!(im = gdImageCreate (wbmp->width, wbmp->height))) {
freewbmp (wbmp);
return NULL;
}
/* create the background color */
white = gdImageColorAllocate(im, 255, 255, 255);
/* create foreground color */
black = gdImageColorAllocate(im, 0, 0, 0);
/* fill in image (in a wbmp 1 = white/ 0 = black) */
pos = 0;
for (row = 0; row < wbmp->height; row++) {
for (col = 0; col < wbmp->width; col++) {
if (wbmp->bitmap[pos++] == WBMP_WHITE) {
gdImageSetPixel(im, col, row, white);
} else {
gdImageSetPixel(im, col, row, black);
}
}
}
freewbmp(wbmp);
return im;
}
Commit Message: Sync with upstream
Even though libgd/libgd#492 is not a relevant bug fix for PHP, since
the binding doesn't use the `gdImage*Ptr()` functions at all, we're
porting the fix to stay in sync here.
CWE ID: CWE-415
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ZSTD_CCtx* ZSTD_createCCtx(void)
{
return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
}
Commit Message: fixed T36302429
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: tgs_make_reply(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ_BODY *b,
krb5_const_principal tgt_name,
const EncTicketPart *tgt,
const krb5_keyblock *replykey,
int rk_is_subkey,
const EncryptionKey *serverkey,
const krb5_keyblock *sessionkey,
krb5_kvno kvno,
AuthorizationData *auth_data,
hdb_entry_ex *server,
krb5_principal server_principal,
const char *server_name,
hdb_entry_ex *client,
krb5_principal client_principal,
hdb_entry_ex *krbtgt,
krb5_enctype krbtgt_etype,
krb5_principals spp,
const krb5_data *rspac,
const METHOD_DATA *enc_pa_data,
const char **e_text,
krb5_data *reply)
{
KDC_REP rep;
EncKDCRepPart ek;
EncTicketPart et;
KDCOptions f = b->kdc_options;
krb5_error_code ret;
int is_weak = 0;
memset(&rep, 0, sizeof(rep));
memset(&et, 0, sizeof(et));
memset(&ek, 0, sizeof(ek));
rep.pvno = 5;
rep.msg_type = krb_tgs_rep;
et.authtime = tgt->authtime;
_kdc_fix_time(&b->till);
et.endtime = min(tgt->endtime, *b->till);
ALLOC(et.starttime);
*et.starttime = kdc_time;
ret = check_tgs_flags(context, config, b, tgt, &et);
if(ret)
goto out;
/* We should check the transited encoding if:
1) the request doesn't ask not to be checked
2) globally enforcing a check
3) principal requires checking
4) we allow non-check per-principal, but principal isn't marked as allowing this
5) we don't globally allow this
*/
#define GLOBAL_FORCE_TRANSITED_CHECK \
(config->trpolicy == TRPOLICY_ALWAYS_CHECK)
#define GLOBAL_ALLOW_PER_PRINCIPAL \
(config->trpolicy == TRPOLICY_ALLOW_PER_PRINCIPAL)
#define GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK \
(config->trpolicy == TRPOLICY_ALWAYS_HONOUR_REQUEST)
/* these will consult the database in future release */
#define PRINCIPAL_FORCE_TRANSITED_CHECK(P) 0
#define PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(P) 0
ret = fix_transited_encoding(context, config,
!f.disable_transited_check ||
GLOBAL_FORCE_TRANSITED_CHECK ||
PRINCIPAL_FORCE_TRANSITED_CHECK(server) ||
!((GLOBAL_ALLOW_PER_PRINCIPAL &&
PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(server)) ||
GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK),
&tgt->transited, &et,
krb5_principal_get_realm(context, client_principal),
krb5_principal_get_realm(context, server->entry.principal),
krb5_principal_get_realm(context, krbtgt->entry.principal));
if(ret)
goto out;
copy_Realm(&server_principal->realm, &rep.ticket.realm);
_krb5_principal2principalname(&rep.ticket.sname, server_principal);
copy_Realm(&tgt_name->realm, &rep.crealm);
/*
if (f.request_anonymous)
_kdc_make_anonymous_principalname (&rep.cname);
else */
copy_PrincipalName(&tgt_name->name, &rep.cname);
rep.ticket.tkt_vno = 5;
ek.caddr = et.caddr;
{
time_t life;
life = et.endtime - *et.starttime;
if(client && client->entry.max_life)
life = min(life, *client->entry.max_life);
if(server->entry.max_life)
life = min(life, *server->entry.max_life);
et.endtime = *et.starttime + life;
}
if(f.renewable_ok && tgt->flags.renewable &&
et.renew_till == NULL && et.endtime < *b->till &&
tgt->renew_till != NULL)
{
et.flags.renewable = 1;
ALLOC(et.renew_till);
*et.renew_till = *b->till;
}
if(et.renew_till){
time_t renew;
renew = *et.renew_till - *et.starttime;
if(client && client->entry.max_renew)
renew = min(renew, *client->entry.max_renew);
if(server->entry.max_renew)
renew = min(renew, *server->entry.max_renew);
*et.renew_till = *et.starttime + renew;
}
if(et.renew_till){
*et.renew_till = min(*et.renew_till, *tgt->renew_till);
*et.starttime = min(*et.starttime, *et.renew_till);
et.endtime = min(et.endtime, *et.renew_till);
}
*et.starttime = min(*et.starttime, et.endtime);
if(*et.starttime == et.endtime){
ret = KRB5KDC_ERR_NEVER_VALID;
goto out;
}
if(et.renew_till && et.endtime == *et.renew_till){
free(et.renew_till);
et.renew_till = NULL;
et.flags.renewable = 0;
}
et.flags.pre_authent = tgt->flags.pre_authent;
et.flags.hw_authent = tgt->flags.hw_authent;
et.flags.anonymous = tgt->flags.anonymous;
et.flags.ok_as_delegate = server->entry.flags.ok_as_delegate;
if(rspac->length) {
/*
* No not need to filter out the any PAC from the
* auth_data since it's signed by the KDC.
*/
ret = _kdc_tkt_add_if_relevant_ad(context, &et,
KRB5_AUTHDATA_WIN2K_PAC, rspac);
if (ret)
goto out;
}
if (auth_data) {
unsigned int i = 0;
/* XXX check authdata */
if (et.authorization_data == NULL) {
et.authorization_data = calloc(1, sizeof(*et.authorization_data));
if (et.authorization_data == NULL) {
ret = ENOMEM;
krb5_set_error_message(context, ret, "malloc: out of memory");
goto out;
}
}
for(i = 0; i < auth_data->len ; i++) {
ret = add_AuthorizationData(et.authorization_data, &auth_data->val[i]);
if (ret) {
krb5_set_error_message(context, ret, "malloc: out of memory");
goto out;
}
}
/* Filter out type KRB5SignedPath */
ret = find_KRB5SignedPath(context, et.authorization_data, NULL);
if (ret == 0) {
if (et.authorization_data->len == 1) {
free_AuthorizationData(et.authorization_data);
free(et.authorization_data);
et.authorization_data = NULL;
} else {
AuthorizationData *ad = et.authorization_data;
free_AuthorizationDataElement(&ad->val[ad->len - 1]);
ad->len--;
}
}
}
ret = krb5_copy_keyblock_contents(context, sessionkey, &et.key);
if (ret)
goto out;
et.crealm = tgt_name->realm;
et.cname = tgt_name->name;
ek.key = et.key;
/* MIT must have at least one last_req */
ek.last_req.val = calloc(1, sizeof(*ek.last_req.val));
if (ek.last_req.val == NULL) {
ret = ENOMEM;
goto out;
}
ek.last_req.len = 1; /* set after alloc to avoid null deref on cleanup */
ek.nonce = b->nonce;
ek.flags = et.flags;
ek.authtime = et.authtime;
ek.starttime = et.starttime;
ek.endtime = et.endtime;
ek.renew_till = et.renew_till;
ek.srealm = rep.ticket.realm;
ek.sname = rep.ticket.sname;
_kdc_log_timestamp(context, config, "TGS-REQ", et.authtime, et.starttime,
et.endtime, et.renew_till);
/* Don't sign cross realm tickets, they can't be checked anyway */
{
char *r = get_krbtgt_realm(&ek.sname);
if (r == NULL || strcmp(r, ek.srealm) == 0) {
ret = _kdc_add_KRB5SignedPath(context,
config,
krbtgt,
krbtgt_etype,
client_principal,
NULL,
spp,
&et);
if (ret)
goto out;
}
}
if (enc_pa_data->len) {
rep.padata = calloc(1, sizeof(*rep.padata));
if (rep.padata == NULL) {
ret = ENOMEM;
goto out;
}
ret = copy_METHOD_DATA(enc_pa_data, rep.padata);
if (ret)
goto out;
}
if (krb5_enctype_valid(context, serverkey->keytype) != 0
&& _kdc_is_weak_exception(server->entry.principal, serverkey->keytype))
{
krb5_enctype_enable(context, serverkey->keytype);
is_weak = 1;
}
/* It is somewhat unclear where the etype in the following
encryption should come from. What we have is a session
key in the passed tgt, and a list of preferred etypes
*for the new ticket*. Should we pick the best possible
etype, given the keytype in the tgt, or should we look
at the etype list here as well? What if the tgt
session key is DES3 and we want a ticket with a (say)
CAST session key. Should the DES3 etype be added to the
etype list, even if we don't want a session key with
DES3? */
ret = _kdc_encode_reply(context, config, NULL, 0,
&rep, &et, &ek, serverkey->keytype,
kvno,
serverkey, 0, replykey, rk_is_subkey,
e_text, reply);
if (is_weak)
krb5_enctype_disable(context, serverkey->keytype);
out:
free_TGS_REP(&rep);
free_TransitedEncoding(&et.transited);
if(et.starttime)
free(et.starttime);
if(et.renew_till)
free(et.renew_till);
if(et.authorization_data) {
free_AuthorizationData(et.authorization_data);
free(et.authorization_data);
}
free_LastReq(&ek.last_req);
memset(et.key.keyvalue.data, 0, et.key.keyvalue.length);
free_EncryptionKey(&et.key);
return ret;
}
Commit Message: Fix transit path validation CVE-2017-6594
Commit f469fc6 (2010-10-02) inadvertently caused the previous hop realm
to not be added to the transit path of issued tickets. This may, in
some cases, enable bypass of capath policy in Heimdal versions 1.5
through 7.2.
Note, this may break sites that rely on the bug. With the bug some
incomplete [capaths] worked, that should not have. These may now break
authentication in some cross-realm configurations.
CWE ID: CWE-295
Target: 1
Example 2:
Code: ofputil_decode_meter_config(struct ofpbuf *msg,
struct ofputil_meter_config *mc,
struct ofpbuf *bands)
{
const struct ofp13_meter_config *omc;
enum ofperr err;
/* Pull OpenFlow headers for the first call. */
if (!msg->header) {
ofpraw_pull_assert(msg);
}
if (!msg->size) {
return EOF;
}
omc = ofpbuf_try_pull(msg, sizeof *omc);
if (!omc) {
VLOG_WARN_RL(&bad_ofmsg_rl,
"OFPMP_METER_CONFIG reply has %"PRIu32" leftover bytes at end",
msg->size);
return OFPERR_OFPBRC_BAD_LEN;
}
ofpbuf_clear(bands);
err = ofputil_pull_bands(msg, ntohs(omc->length) - sizeof *omc,
&mc->n_bands, bands);
if (err) {
return err;
}
mc->meter_id = ntohl(omc->meter_id);
mc->flags = ntohs(omc->flags);
mc->bands = bands->data;
return 0;
}
Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command.
When decoding a group mod, the current code validates the group type and
command after the whole group mod has been decoded. The OF1.5 decoder,
however, tries to use the type and command earlier, when it might still be
invalid. This caused an assertion failure (via OVS_NOT_REACHED). This
commit fixes the problem.
ovs-vswitchd does not enable support for OpenFlow 1.5 by default.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249
Signed-off-by: Ben Pfaff <[email protected]>
Reviewed-by: Yifeng Sun <[email protected]>
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int snd_pcm_hw_constraint_mask(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
u_int32_t mask)
{
struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
struct snd_mask *maskp = constrs_mask(constrs, var);
*maskp->bits &= mask;
memset(maskp->bits + 1, 0, (SNDRV_MASK_MAX-32) / 8); /* clear rest */
if (*maskp->bits == 0)
return -EINVAL;
return 0;
}
Commit Message: ALSA: pcm : Call kill_fasync() in stream lock
Currently kill_fasync() is called outside the stream lock in
snd_pcm_period_elapsed(). This is potentially racy, since the stream
may get released even during the irq handler is running. Although
snd_pcm_release_substream() calls snd_pcm_drop(), this doesn't
guarantee that the irq handler finishes, thus the kill_fasync() call
outside the stream spin lock may be invoked after the substream is
detached, as recently reported by KASAN.
As a quick workaround, move kill_fasync() call inside the stream
lock. The fasync is rarely used interface, so this shouldn't have a
big impact from the performance POV.
Ideally, we should implement some sync mechanism for the proper finish
of stream and irq handler. But this oneliner should suffice for most
cases, so far.
Reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void Unregister(const GURL& url) {
EXPECT_TRUE(
content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
net::URLRequestFilter::GetInstance()->RemoveUrlHandler(url);
}
Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service.
The functionality worked, as part of converting DICE, however the test code didn't work since it
depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to
better match production, which removes the dependency on net/.
Also:
-make GetFilePathWithReplacements replace strings in the mock headers if they're present
-add a global to google_util to ignore ports; that way other tests can be converted without having
to modify each callsite to google_util
Bug: 881976
Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058
Reviewed-on: https://chromium-review.googlesource.com/c/1328142
Commit-Queue: John Abd-El-Malek <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652}
CWE ID:
Target: 1
Example 2:
Code: void ProfileChooserView::PostActionPerformed(
ProfileMetrics::ProfileDesktopMenu action_performed) {
ProfileMetrics::LogProfileDesktopMenu(action_performed, gaia_service_type_);
gaia_service_type_ = signin::GAIA_SERVICE_TYPE_NONE;
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static std::string error_data() {
return std::string("ohhh nooooo mr. bill!");
}
Commit Message: Tests were marked as Flaky.
BUG=151811,151810
[email protected],[email protected]
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/10968052
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158204 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: sc_parse_ef_gdo_content(const unsigned char *gdo, size_t gdo_len,
unsigned char *iccsn, size_t *iccsn_len,
unsigned char *chn, size_t *chn_len)
{
int r = SC_SUCCESS, iccsn_found = 0, chn_found = 0;
const unsigned char *p = gdo;
size_t left = gdo_len;
while (left >= 2) {
unsigned int cla, tag;
size_t tag_len;
r = sc_asn1_read_tag(&p, left, &cla, &tag, &tag_len);
if (r != SC_SUCCESS) {
if (r == SC_ERROR_ASN1_END_OF_CONTENTS) {
/* not enough data */
r = SC_SUCCESS;
}
break;
}
if (p == NULL) {
/* done parsing */
break;
}
if (cla == SC_ASN1_TAG_APPLICATION) {
switch (tag) {
case 0x1A:
iccsn_found = 1;
if (iccsn && iccsn_len) {
memcpy(iccsn, p, MIN(tag_len, *iccsn_len));
*iccsn_len = MIN(tag_len, *iccsn_len);
}
break;
case 0x1F20:
chn_found = 1;
if (chn && chn_len) {
memcpy(chn, p, MIN(tag_len, *chn_len));
*chn_len = MIN(tag_len, *chn_len);
}
break;
}
}
p += tag_len;
left -= (p - gdo);
}
if (!iccsn_found && iccsn_len)
*iccsn_len = 0;
if (!chn_found && chn_len)
*chn_len = 0;
return r;
}
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
Target: 1
Example 2:
Code: get_linux_hostspec(const char *solaris_hostspec, char **plinux_hostspec)
{
/*
* For now we just support CIDR masks (e.g. @192.168.0.0/16) and host
* wildcards (e.g. *.example.org).
*/
if (solaris_hostspec[0] == '@') {
/*
* Solaris host specifier, e.g. @192.168.0.0/16; we just need
* to skip the @ in this case
*/
*plinux_hostspec = strdup(solaris_hostspec + 1);
} else {
*plinux_hostspec = strdup(solaris_hostspec);
}
if (*plinux_hostspec == NULL) {
return (SA_NO_MEMORY);
}
return (SA_OK);
}
Commit Message: Move nfs.c:foreach_nfs_shareopt() to libshare.c:foreach_shareopt()
so that it can be (re)used in other parts of libshare.
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline int ftrace_init_dyn_debugfs(struct dentry *d_tracer) { return 0; }
Commit Message: tracing: Fix possible NULL pointer dereferences
Currently set_ftrace_pid and set_graph_function files use seq_lseek
for their fops. However seq_open() is called only for FMODE_READ in
the fops->open() so that if an user tries to seek one of those file
when she open it for writing, it sees NULL seq_file and then panic.
It can be easily reproduced with following command:
$ cd /sys/kernel/debug/tracing
$ echo 1234 | sudo tee -a set_ftrace_pid
In this example, GNU coreutils' tee opens the file with fopen(, "a")
and then the fopen() internally calls lseek().
Link: http://lkml.kernel.org/r/[email protected]
Cc: Frederic Weisbecker <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Namhyung Kim <[email protected]>
Cc: [email protected]
Signed-off-by: Namhyung Kim <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void qrio_cpuwd_flag(bool flag)
{
u8 reason1;
void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE;
reason1 = in_8(qrio_base + REASON1_OFF);
if (flag)
reason1 |= REASON1_CPUWD;
else
reason1 &= ~REASON1_CPUWD;
out_8(qrio_base + REASON1_OFF, reason1);
}
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
Target: 1
Example 2:
Code: is_valid_response(struct rad_handle *h, int srv,
const struct sockaddr_in *from)
{
MD5_CTX ctx;
unsigned char md5[16];
const struct rad_server *srvp;
int len;
srvp = &h->servers[srv];
/* Check the source address */
if (from->sin_family != srvp->addr.sin_family ||
from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
from->sin_port != srvp->addr.sin_port)
return 0;
/* Check the message length */
if (h->resp_len < POS_ATTRS)
return 0;
len = h->response[POS_LENGTH] << 8 | h->response[POS_LENGTH+1];
if (len > h->resp_len)
return 0;
/* Check the response authenticator */
MD5Init(&ctx);
MD5Update(&ctx, &h->response[POS_CODE], POS_AUTH - POS_CODE);
MD5Update(&ctx, &h->request[POS_AUTH], LEN_AUTH);
MD5Update(&ctx, &h->response[POS_ATTRS], len - POS_ATTRS);
MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
MD5Final(md5, &ctx);
if (memcmp(&h->response[POS_AUTH], md5, sizeof md5) != 0)
return 0;
return 1;
}
Commit Message: Fix a security issue in radius_get_vendor_attr().
The underlying rad_get_vendor_attr() function assumed that it would always be
given valid VSA data. Indeed, the buffer length wasn't even passed in; the
assumption was that the length field within the VSA structure would be valid.
This could result in denial of service by providing a length that would be
beyond the memory limit, or potential arbitrary memory access by providing a
length greater than the actual data given.
rad_get_vendor_attr() has been changed to require the raw data length be
provided, and this is then used to check that the VSA is valid.
Conflicts:
radlib_vs.h
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ptrace_triggered(struct perf_event *bp, int nmi,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct perf_event_attr attr;
/*
* Disable the breakpoint request here since ptrace has defined a
* one-shot behaviour for breakpoint exceptions.
*/
attr = bp->attr;
attr.disabled = true;
modify_user_hw_breakpoint(bp, &attr);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword)
{ const AIFF_CAF_CHANNEL_MAP * map_info ;
unsigned channel_bitmap, channel_decriptions, bytesread ;
int layout_tag ;
bytesread = psf_binheader_readf (psf, "444", &layout_tag, &channel_bitmap, &channel_decriptions) ;
if ((map_info = aiff_caf_of_channel_layout_tag (layout_tag)) == NULL)
return 0 ;
psf_log_printf (psf, " Tag : %x\n", layout_tag) ;
if (map_info)
psf_log_printf (psf, " Layout : %s\n", map_info->name) ;
if (bytesread < dword)
psf_binheader_readf (psf, "j", dword - bytesread) ;
if (map_info->channel_map != NULL)
{ size_t chanmap_size = psf->sf.channels * sizeof (psf->channel_map [0]) ;
free (psf->channel_map) ;
if ((psf->channel_map = malloc (chanmap_size)) == NULL)
return SFE_MALLOC_FAILED ;
memcpy (psf->channel_map, map_info->channel_map, chanmap_size) ;
} ;
return 0 ;
} /* aiff_read_chanmap */
Commit Message: src/aiff.c: Fix a buffer read overflow
Secunia Advisory SA76717.
Found by: Laurent Delosieres, Secunia Research at Flexera Software
CWE ID: CWE-119
Target: 1
Example 2:
Code: static u32 countLookasideSlots(LookasideSlot *p){
u32 cnt = 0;
while( p ){
p = p->pNext;
cnt++;
}
return cnt;
}
Commit Message: sqlite: backport bugfixes for dbfuzz2
Bug: 952406
Change-Id: Icbec429742048d6674828726c96d8e265c41b595
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1568152
Reviewed-by: Chris Mumford <[email protected]>
Commit-Queue: Darwin Huang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#651030}
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void update_context(struct ImapData *idata, int oldmsgcount)
{
struct Header *h = NULL;
struct Context *ctx = idata->ctx;
if (!idata->uid_hash)
idata->uid_hash = mutt_hash_int_create(MAX(6 * ctx->msgcount / 5, 30), 0);
for (int msgno = oldmsgcount; msgno < ctx->msgcount; msgno++)
{
h = ctx->hdrs[msgno];
mutt_hash_int_insert(idata->uid_hash, HEADER_DATA(h)->uid, h);
}
}
Commit Message: Don't overflow stack buffer in msg_parse_fetch
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
{
int pad = 0, ret, i, neg;
unsigned char *p, *n, pb = 0;
if (a == NULL)
return (0);
neg = a->type & V_ASN1_NEG;
if (a->length == 0)
ret = 1;
else {
ret = a->length;
i = a->data[0];
if (!neg && (i > 127)) {
pad = 1;
pb = 0;
pad = 1;
pb = 0xFF;
} else if (i == 128) {
/*
* Special case: if any other bytes non zero we pad:
* otherwise we don't.
*/
for (i = 1; i < a->length; i++)
if (a->data[i]) {
pad = 1;
pb = 0xFF;
break;
}
}
}
ret += pad;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline void prepare_value(unsigned flags, zval *zv TSRMLS_DC)
{
if (flags & PHP_HTTP_PARAMS_URLENCODED) {
prepare_urlencoded(zv TSRMLS_CC);
}
if (flags & PHP_HTTP_PARAMS_ESCAPED) {
prepare_escaped(zv TSRMLS_CC);
}
}
Commit Message: fix bug #73055
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LayerWebKitThread::removeFromSuperlayer()
{
if (m_superlayer)
m_superlayer->removeSublayerOrOverlay(this);
}
Commit Message: [BlackBerry] GraphicsLayer: rename notifySyncRequired to notifyFlushRequired
https://bugs.webkit.org/show_bug.cgi?id=111997
Patch by Alberto Garcia <[email protected]> on 2013-03-11
Reviewed by Rob Buis.
This changed in r130439 but the old name was introduced again by
mistake in r144465.
* platform/graphics/blackberry/GraphicsLayerBlackBerry.h:
(WebCore::GraphicsLayerBlackBerry::notifyFlushRequired):
* platform/graphics/blackberry/LayerWebKitThread.cpp:
(WebCore::LayerWebKitThread::setNeedsCommit):
git-svn-id: svn://svn.chromium.org/blink/trunk@145363 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long address, pte_t *page_table, pmd_t *pmd,
unsigned int flags)
{
struct mem_cgroup *memcg;
struct page *page;
spinlock_t *ptl;
pte_t entry;
pte_unmap(page_table);
/* Check if we need to add a guard page to the stack */
if (check_stack_guard_page(vma, address) < 0)
return VM_FAULT_SIGSEGV;
/* Use the zero-page for reads */
if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm)) {
entry = pte_mkspecial(pfn_pte(my_zero_pfn(address),
vma->vm_page_prot));
page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
if (!pte_none(*page_table))
goto unlock;
goto setpte;
}
/* Allocate our own private page. */
if (unlikely(anon_vma_prepare(vma)))
goto oom;
page = alloc_zeroed_user_highpage_movable(vma, address);
if (!page)
goto oom;
if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg))
goto oom_free_page;
/*
* The memory barrier inside __SetPageUptodate makes sure that
* preceeding stores to the page contents become visible before
* the set_pte_at() write.
*/
__SetPageUptodate(page);
entry = mk_pte(page, vma->vm_page_prot);
if (vma->vm_flags & VM_WRITE)
entry = pte_mkwrite(pte_mkdirty(entry));
page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
if (!pte_none(*page_table))
goto release;
inc_mm_counter_fast(mm, MM_ANONPAGES);
page_add_new_anon_rmap(page, vma, address);
mem_cgroup_commit_charge(page, memcg, false);
lru_cache_add_active_or_unevictable(page, vma);
setpte:
set_pte_at(mm, address, page_table, entry);
/* No need to invalidate - it was non-present before */
update_mmu_cache(vma, address, page_table);
unlock:
pte_unmap_unlock(page_table, ptl);
return 0;
release:
mem_cgroup_cancel_charge(page, memcg);
page_cache_release(page);
goto unlock;
oom_free_page:
page_cache_release(page);
oom:
return VM_FAULT_OOM;
}
Commit Message: mm: avoid setting up anonymous pages into file mapping
Reading page fault handler code I've noticed that under right
circumstances kernel would map anonymous pages into file mappings: if
the VMA doesn't have vm_ops->fault() and the VMA wasn't fully populated
on ->mmap(), kernel would handle page fault to not populated pte with
do_anonymous_page().
Let's change page fault handler to use do_anonymous_page() only on
anonymous VMA (->vm_ops == NULL) and make sure that the VMA is not
shared.
For file mappings without vm_ops->fault() or shred VMA without vm_ops,
page fault on pte_none() entry would lead to SIGBUS.
Signed-off-by: Kirill A. Shutemov <[email protected]>
Acked-by: Oleg Nesterov <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: void IsWindowAndCloseButtonInScreen(aura::Window* window,
WindowSelectorItem* window_item) {
aura::Window* root_window = window_item->root_window();
EXPECT_TRUE(window_item->Contains(window));
EXPECT_TRUE(root_window->GetBoundsInScreen().Contains(
GetTransformedTargetBounds(window)));
EXPECT_TRUE(
root_window->GetBoundsInScreen().Contains(GetTransformedTargetBounds(
GetCloseButton(window_item)->GetNativeView())));
}
Commit Message: cros: Enable some tests in //ash/wm in ash_unittests --mash
For the ones that fail, disable them via filter file instead of in the
code, per our disablement policy.
Bug: 698085, 695556, 698878, 698888, 698093, 698894
Test: ash_unittests --mash
Change-Id: Ic145ab6a95508968d6884d14fac2a3ca08888d26
Reviewed-on: https://chromium-review.googlesource.com/752423
Commit-Queue: James Cook <[email protected]>
Reviewed-by: Steven Bennetts <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513836}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int inode_has_encryption_context(struct inode *inode)
{
if (!inode->i_sb->s_cop->get_context)
return 0;
return (inode->i_sb->s_cop->get_context(inode, NULL, 0L) > 0);
}
Commit Message: fscrypto: add authorization check for setting encryption policy
On an ext4 or f2fs filesystem with file encryption supported, a user
could set an encryption policy on any empty directory(*) to which they
had readonly access. This is obviously problematic, since such a
directory might be owned by another user and the new encryption policy
would prevent that other user from creating files in their own directory
(for example).
Fix this by requiring inode_owner_or_capable() permission to set an
encryption policy. This means that either the caller must own the file,
or the caller must have the capability CAP_FOWNER.
(*) Or also on any regular file, for f2fs v4.6 and later and ext4
v4.8-rc1 and later; a separate bug fix is coming for that.
Signed-off-by: Eric Biggers <[email protected]>
Cc: [email protected] # 4.1+; check fs/{ext4,f2fs}
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: size_t compile_tree(struct filter_op **fop)
{
int i = 1;
struct filter_op *array = NULL;
struct unfold_elm *ue;
BUG_IF(tree_root == NULL);
fprintf(stdout, " Unfolding the meta-tree ");
fflush(stdout);
/* start the recursion on the tree */
unfold_blk(&tree_root);
fprintf(stdout, " done.\n\n");
/* substitute the virtual labels with real offsets */
labels_to_offsets();
/* convert the tailq into an array */
TAILQ_FOREACH(ue, &unfolded_tree, next) {
/* label == 0 means a real instruction */
if (ue->label == 0) {
SAFE_REALLOC(array, i * sizeof(struct filter_op));
memcpy(&array[i - 1], &ue->fop, sizeof(struct filter_op));
i++;
}
}
/* always append the exit function to a script */
SAFE_REALLOC(array, i * sizeof(struct filter_op));
array[i - 1].opcode = FOP_EXIT;
/* return the pointer to the array */
*fop = array;
return (i);
}
Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782)
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int inet_gro_complete(struct sk_buff *skb, int nhoff)
{
__be16 newlen = htons(skb->len - nhoff);
struct iphdr *iph = (struct iphdr *)(skb->data + nhoff);
const struct net_offload *ops;
int proto = iph->protocol;
int err = -ENOSYS;
if (skb->encapsulation)
skb_set_inner_network_header(skb, nhoff);
csum_replace2(&iph->check, iph->tot_len, newlen);
iph->tot_len = newlen;
rcu_read_lock();
ops = rcu_dereference(inet_offloads[proto]);
if (WARN_ON(!ops || !ops->callbacks.gro_complete))
goto out_unlock;
/* Only need to add sizeof(*iph) to get to the next hdr below
* because any hdr with option will have been flushed in
* inet_gro_receive().
*/
err = ops->callbacks.gro_complete(skb, nhoff + sizeof(*iph));
out_unlock:
rcu_read_unlock();
return err;
}
Commit Message: net: add validation for the socket syscall protocol argument
郭永刚 reported that one could simply crash the kernel as root by
using a simple program:
int socket_fd;
struct sockaddr_in addr;
addr.sin_port = 0;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = 10;
socket_fd = socket(10,3,0x40000000);
connect(socket_fd , &addr,16);
AF_INET, AF_INET6 sockets actually only support 8-bit protocol
identifiers. inet_sock's skc_protocol field thus is sized accordingly,
thus larger protocol identifiers simply cut off the higher bits and
store a zero in the protocol fields.
This could lead to e.g. NULL function pointer because as a result of
the cut off inet_num is zero and we call down to inet_autobind, which
is NULL for raw sockets.
kernel: Call Trace:
kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70
kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80
kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110
kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80
kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200
kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10
kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89
I found no particular commit which introduced this problem.
CVE: CVE-2015-8543
Cc: Cong Wang <[email protected]>
Reported-by: 郭永刚 <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int nfs4_init_ds_session(struct nfs_client *clp, unsigned long lease_time)
{
struct nfs4_session *session = clp->cl_session;
int ret;
spin_lock(&clp->cl_lock);
if (test_and_clear_bit(NFS4_SESSION_INITING, &session->session_state)) {
/*
* Do not set NFS_CS_CHECK_LEASE_TIME instead set the
* DS lease to be equal to the MDS lease.
*/
clp->cl_lease_time = lease_time;
clp->cl_last_renewal = jiffies;
}
spin_unlock(&clp->cl_lock);
ret = nfs41_check_session_ready(clp);
if (ret)
return ret;
/* Test for the DS role */
if (!is_ds_client(clp))
return -ENODEV;
return 0;
}
Commit Message: NFSv4: Check for buffer length in __nfs4_get_acl_uncached
Commit 1f1ea6c "NFSv4: Fix buffer overflow checking in
__nfs4_get_acl_uncached" accidently dropped the checking for too small
result buffer length.
If someone uses getxattr on "system.nfs4_acl" on an NFSv4 mount
supporting ACLs, the ACL has not been cached and the buffer suplied is
too short, we still copy the complete ACL, resulting in kernel and user
space memory corruption.
Signed-off-by: Sven Wegener <[email protected]>
Cc: [email protected]
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 nInterpolatedSample;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* get last two samples generated */
/*lint -e{704} <avoid divide for performance>*/
tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18;
/*lint -e{704} <avoid divide for performance>*/
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
/* generate a buffer of noise */
while (numSamples--) {
nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac));
nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac);
*pOutputBuffer++ = (EAS_PCM) nInterpolatedSample;
/* update PRNG */
pWTVoice->phaseFrac += (EAS_U32) phaseInc;
if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) {
tmp0 = tmp1;
pWTVoice->phaseAccum = pWTVoice->loopEnd;
pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1);
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac);
}
}
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
Target: 1
Example 2:
Code: _dbus_close_socket (int fd,
DBusError *error)
{
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
again:
if (closesocket (fd) == SOCKET_ERROR)
{
DBUS_SOCKET_SET_ERRNO ();
if (errno == EINTR)
goto again;
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not close socket: socket=%d, , %s",
fd, _dbus_strerror_from_errno ());
return FALSE;
}
_dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
return TRUE;
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gpk_parse_fileinfo(sc_card_t *card,
const u8 *buf, size_t buflen,
sc_file_t *file)
{
const u8 *sp, *end, *next;
int i, rc;
memset(file, 0, sizeof(*file));
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE);
end = buf + buflen;
for (sp = buf; sp + 2 < end; sp = next) {
next = sp + 2 + sp[1];
if (next > end)
break;
if (sp[0] == 0x84) {
/* ignore if name is longer than what it should be */
if (sp[1] > sizeof(file->name))
continue;
memset(file->name, 0, sizeof(file->name));
memcpy(file->name, sp+2, sp[1]);
} else
if (sp[0] == 0x85) {
unsigned int ac[3], n;
file->id = (sp[4] << 8) | sp[5];
file->size = (sp[8] << 8) | sp[9];
file->record_length = sp[7];
/* Map ACLs. Note the third AC byte is
* valid of EFs only */
for (n = 0; n < 3; n++)
ac[n] = (sp[10+2*n] << 8) | sp[11+2*n];
/* Examine file type */
switch (sp[6] & 7) {
case 0x01: case 0x02: case 0x03: case 0x04:
case 0x05: case 0x06: case 0x07:
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = sp[6] & 7;
ac_to_acl(ac[0], file, SC_AC_OP_UPDATE);
ac_to_acl(ac[1], file, SC_AC_OP_WRITE);
ac_to_acl(ac[2], file, SC_AC_OP_READ);
break;
case 0x00: /* 0x38 is DF */
file->type = SC_FILE_TYPE_DF;
/* Icky: the GPK uses different ACLs
* for creating data files and
* 'sensitive' i.e. key files */
ac_to_acl(ac[0], file, SC_AC_OP_LOCK);
ac_to_acl(ac[1], file, SC_AC_OP_CREATE);
sc_file_add_acl_entry(file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_DELETE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
break;
}
} else
if (sp[0] == 0x6f) {
/* oops - this is a directory with an IADF.
* This happens with the personalized GemSafe cards
* for instance. */
file->type = SC_FILE_TYPE_DF;
rc = gpk_parse_fci(card, sp + 2, sp[1], file);
if (rc < 0)
return rc;
}
}
if (file->record_length)
file->record_count = file->size / file->record_length;
file->magic = SC_FILE_MAGIC;
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AcceleratedStaticBitmapImage::CopyToTexture(
gpu::gles2::GLES2Interface* dest_gl,
GLenum dest_target,
GLuint dest_texture_id,
bool unpack_premultiply_alpha,
bool unpack_flip_y,
const IntPoint& dest_point,
const IntRect& source_sub_rectangle) {
CheckThread();
if (!IsValid())
return false;
DCHECK(texture_holder_->IsCrossThread() ||
dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL());
EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST);
dest_gl->WaitSyncTokenCHROMIUM(
texture_holder_->GetSyncToken().GetConstData());
GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM(
texture_holder_->GetMailbox().name);
dest_gl->CopySubTextureCHROMIUM(
source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(),
dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(),
source_sub_rectangle.Width(), source_sub_rectangle.Height(),
unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE,
unpack_premultiply_alpha ? GL_FALSE : GL_TRUE);
dest_gl->DeleteTextures(1, &source_texture_id);
gpu::SyncToken sync_token;
dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData());
texture_holder_->UpdateSyncToken(sync_token);
return true;
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
Target: 1
Example 2:
Code: uint64_t streamDelConsumer(streamCG *cg, sds name) {
streamConsumer *consumer = streamLookupConsumer(cg,name,0);
if (consumer == NULL) return 0;
uint64_t retval = raxSize(consumer->pel);
/* Iterate all the consumer pending messages, deleting every corresponding
* entry from the global entry. */
raxIterator ri;
raxStart(&ri,consumer->pel);
raxSeek(&ri,"^",NULL,0);
while(raxNext(&ri)) {
streamNACK *nack = ri.data;
raxRemove(cg->pel,ri.key,ri.key_len,NULL);
streamFreeNACK(nack);
}
raxStop(&ri);
/* Deallocate the consumer. */
raxRemove(cg->consumers,(unsigned char*)name,sdslen(name),NULL);
streamFreeConsumer(consumer);
return retval;
}
Commit Message: Abort in XGROUP if the key is not a stream
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gpgsm_cancel (void *engine)
{
engine_gpgsm_t gpgsm = engine;
if (!gpgsm)
return gpg_error (GPG_ERR_INV_VALUE);
if (gpgsm->status_cb.fd != -1)
_gpgme_io_close (gpgsm->status_cb.fd);
if (gpgsm->input_cb.fd != -1)
_gpgme_io_close (gpgsm->input_cb.fd);
if (gpgsm->output_cb.fd != -1)
_gpgme_io_close (gpgsm->output_cb.fd);
if (gpgsm->message_cb.fd != -1)
_gpgme_io_close (gpgsm->message_cb.fd);
if (gpgsm->assuan_ctx)
{
assuan_release (gpgsm->assuan_ctx);
gpgsm->assuan_ctx = NULL;
}
return 0;
}
Commit Message:
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FolderHeaderView::SetFolderItem(AppListFolderItem* folder_item) {
if (folder_item_)
folder_item_->RemoveObserver(this);
folder_item_ = folder_item;
if (!folder_item_)
return;
folder_item_->AddObserver(this);
folder_name_view_->SetEnabled(folder_item->folder_type() !=
AppListFolderItem::FOLDER_TYPE_OEM);
Update();
}
Commit Message: Enforce the maximum length of the folder name in UI.
BUG=355797
[email protected]
Review URL: https://codereview.chromium.org/203863005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260156 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: virtual ~MockRenderProcess() {}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GpuProcessHost::DidFailInitialize() {
UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", false);
status_ = FAILURE;
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
gpu_data_manager->FallBackToNextGpuMode();
RunRequestGPUInfoCallbacks(gpu_data_manager->GetGPUInfo());
}
Commit Message: Fix GPU process fallback logic.
1. In GpuProcessHost::OnProcessCrashed() record the process crash first.
This means the GPU mode fallback will happen before a new GPU process
is started.
2. Don't call FallBackToNextGpuMode() if GPU process initialization
fails for an unsandboxed GPU process. The unsandboxed GPU is only
used for collect information and it's failure doesn't indicate a need
to change GPU modes.
Bug: 869419
Change-Id: I8bd0a03268f0ea8809f3df8458d4e6a92db9391f
Reviewed-on: https://chromium-review.googlesource.com/1157164
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: kylechar <[email protected]>
Cr-Commit-Position: refs/heads/master@{#579625}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: pimv1_join_prune_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int ngroups, njoin, nprune;
int njp;
/* If it's a single group and a single source, use 1-line output. */
if (ND_TTEST2(bp[0], 30) && bp[11] == 1 &&
((njoin = EXTRACT_16BITS(&bp[20])) + EXTRACT_16BITS(&bp[22])) == 1) {
int hold;
ND_PRINT((ndo, " RPF %s ", ipaddr_string(ndo, bp)));
hold = EXTRACT_16BITS(&bp[6]);
if (hold != 180) {
ND_PRINT((ndo, "Hold "));
unsigned_relts_print(ndo, hold);
}
ND_PRINT((ndo, "%s (%s/%d, %s", njoin ? "Join" : "Prune",
ipaddr_string(ndo, &bp[26]), bp[25] & 0x3f,
ipaddr_string(ndo, &bp[12])));
if (EXTRACT_32BITS(&bp[16]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[16])));
ND_PRINT((ndo, ") %s%s %s",
(bp[24] & 0x01) ? "Sparse" : "Dense",
(bp[25] & 0x80) ? " WC" : "",
(bp[25] & 0x40) ? "RP" : "SPT"));
return;
}
ND_TCHECK2(bp[0], sizeof(struct in_addr));
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, " Upstream Nbr: %s", ipaddr_string(ndo, bp)));
ND_TCHECK2(bp[6], 2);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, " Hold time: "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[6]));
if (ndo->ndo_vflag < 2)
return;
bp += 8;
len -= 8;
ND_TCHECK2(bp[0], 4);
ngroups = bp[3];
bp += 4;
len -= 4;
while (ngroups--) {
/*
* XXX - does the address have length "addrlen" and the
* mask length "maddrlen"?
*/
ND_TCHECK2(bp[0], sizeof(struct in_addr));
ND_PRINT((ndo, "\n\tGroup: %s", ipaddr_string(ndo, bp)));
ND_TCHECK2(bp[4], sizeof(struct in_addr));
if (EXTRACT_32BITS(&bp[4]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[4])));
ND_TCHECK2(bp[8], 4);
njoin = EXTRACT_16BITS(&bp[8]);
nprune = EXTRACT_16BITS(&bp[10]);
ND_PRINT((ndo, " joined: %d pruned: %d", njoin, nprune));
bp += 12;
len -= 12;
for (njp = 0; njp < (njoin + nprune); njp++) {
const char *type;
if (njp < njoin)
type = "Join ";
else
type = "Prune";
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "\n\t%s %s%s%s%s/%d", type,
(bp[0] & 0x01) ? "Sparse " : "Dense ",
(bp[1] & 0x80) ? "WC " : "",
(bp[1] & 0x40) ? "RP " : "SPT ",
ipaddr_string(ndo, &bp[2]), bp[1] & 0x3f));
bp += 6;
len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125
Target: 1
Example 2:
Code: TitleCard(const base::string16& message, views::ButtonListener* listener,
views::ImageButton** back_button) {
back_button_ = CreateBackButton(listener);
*back_button = back_button_;
title_label_ =
new views::Label(message, views::style::CONTEXT_DIALOG_TITLE);
title_label_->SetHorizontalAlignment(gfx::ALIGN_CENTER);
AddChildView(back_button_);
AddChildView(title_label_);
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int MStoBeaufort(const float ms)
{
if (ms < 0.3f)
return 0;
if (ms < 1.5f)
return 1;
if (ms < 3.3f)
return 2;
if (ms < 5.5f)
return 3;
if (ms < 8.0f)
return 4;
if (ms < 10.8f)
return 5;
if (ms < 13.9f)
return 6;
if (ms < 17.2f)
return 7;
if (ms < 20.7f)
return 8;
if (ms < 24.5f)
return 9;
if (ms < 28.4f)
return 10;
if (ms < 32.6f)
return 11;
return 12;
}
Commit Message: Do not allow enters/returns in arguments (thanks to Fabio Carretto)
CWE ID: CWE-93
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int v9fs_device_realize_common(V9fsState *s, Error **errp)
{
V9fsVirtioState *v = container_of(s, V9fsVirtioState, state);
int i, len;
struct stat stat;
FsDriverEntry *fse;
V9fsPath path;
int rc = 1;
/* initialize pdu allocator */
QLIST_INIT(&s->free_list);
QLIST_INIT(&s->active_list);
for (i = 0; i < (MAX_REQ - 1); i++) {
QLIST_INSERT_HEAD(&s->free_list, &v->pdus[i], next);
v->pdus[i].s = s;
v->pdus[i].idx = i;
}
v9fs_path_init(&path);
fse = get_fsdev_fsentry(s->fsconf.fsdev_id);
if (!fse) {
/* We don't have a fsdev identified by fsdev_id */
error_setg(errp, "9pfs device couldn't find fsdev with the "
"id = %s",
s->fsconf.fsdev_id ? s->fsconf.fsdev_id : "NULL");
goto out;
}
if (!s->fsconf.tag) {
/* we haven't specified a mount_tag */
error_setg(errp, "fsdev with id %s needs mount_tag arguments",
s->fsconf.fsdev_id);
goto out;
}
s->ctx.export_flags = fse->export_flags;
s->ctx.fs_root = g_strdup(fse->path);
s->ctx.exops.get_st_gen = NULL;
len = strlen(s->fsconf.tag);
if (len > MAX_TAG_LEN - 1) {
error_setg(errp, "mount tag '%s' (%d bytes) is longer than "
"maximum (%d bytes)", s->fsconf.tag, len, MAX_TAG_LEN - 1);
goto out;
}
s->tag = g_strdup(s->fsconf.tag);
s->ctx.uid = -1;
s->ops = fse->ops;
s->fid_list = NULL;
qemu_co_rwlock_init(&s->rename_lock);
if (s->ops->init(&s->ctx) < 0) {
error_setg(errp, "9pfs Failed to initialize fs-driver with id:%s"
" and export path:%s", s->fsconf.fsdev_id, s->ctx.fs_root);
goto out;
}
/*
* Check details of export path, We need to use fs driver
* call back to do that. Since we are in the init path, we don't
* use co-routines here.
*/
if (s->ops->name_to_path(&s->ctx, NULL, "/", &path) < 0) {
error_setg(errp,
"error in converting name to path %s", strerror(errno));
goto out;
}
if (s->ops->lstat(&s->ctx, &path, &stat)) {
error_setg(errp, "share path %s does not exist", fse->path);
goto out;
} else if (!S_ISDIR(stat.st_mode)) {
error_setg(errp, "share path %s is not a directory", fse->path);
goto out;
}
v9fs_path_free(&path);
rc = 0;
out:
if (rc) {
g_free(s->ctx.fs_root);
g_free(s->tag);
v9fs_path_free(&path);
}
return rc;
}
Commit Message:
CWE ID: CWE-400
Target: 1
Example 2:
Code: static int crypto_ccm_create_common(struct crypto_template *tmpl,
struct rtattr **tb,
const char *full_name,
const char *ctr_name,
const char *mac_name)
{
struct crypto_attr_type *algt;
struct aead_instance *inst;
struct skcipher_alg *ctr;
struct crypto_alg *mac_alg;
struct hash_alg_common *mac;
struct ccm_instance_ctx *ictx;
int err;
algt = crypto_get_attr_type(tb);
if (IS_ERR(algt))
return PTR_ERR(algt);
if ((algt->type ^ CRYPTO_ALG_TYPE_AEAD) & algt->mask)
return -EINVAL;
mac_alg = crypto_find_alg(mac_name, &crypto_ahash_type,
CRYPTO_ALG_TYPE_HASH,
CRYPTO_ALG_TYPE_AHASH_MASK |
CRYPTO_ALG_ASYNC);
if (IS_ERR(mac_alg))
return PTR_ERR(mac_alg);
mac = __crypto_hash_alg_common(mac_alg);
err = -EINVAL;
if (mac->digestsize != 16)
goto out_put_mac;
inst = kzalloc(sizeof(*inst) + sizeof(*ictx), GFP_KERNEL);
err = -ENOMEM;
if (!inst)
goto out_put_mac;
ictx = aead_instance_ctx(inst);
err = crypto_init_ahash_spawn(&ictx->mac, mac,
aead_crypto_instance(inst));
if (err)
goto err_free_inst;
crypto_set_skcipher_spawn(&ictx->ctr, aead_crypto_instance(inst));
err = crypto_grab_skcipher(&ictx->ctr, ctr_name, 0,
crypto_requires_sync(algt->type,
algt->mask));
if (err)
goto err_drop_mac;
ctr = crypto_spawn_skcipher_alg(&ictx->ctr);
/* Not a stream cipher? */
err = -EINVAL;
if (ctr->base.cra_blocksize != 1)
goto err_drop_ctr;
/* We want the real thing! */
if (crypto_skcipher_alg_ivsize(ctr) != 16)
goto err_drop_ctr;
err = -ENAMETOOLONG;
if (snprintf(inst->alg.base.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"ccm_base(%s,%s)", ctr->base.cra_driver_name,
mac->base.cra_driver_name) >= CRYPTO_MAX_ALG_NAME)
goto err_drop_ctr;
memcpy(inst->alg.base.cra_name, full_name, CRYPTO_MAX_ALG_NAME);
inst->alg.base.cra_flags = ctr->base.cra_flags & CRYPTO_ALG_ASYNC;
inst->alg.base.cra_priority = (mac->base.cra_priority +
ctr->base.cra_priority) / 2;
inst->alg.base.cra_blocksize = 1;
inst->alg.base.cra_alignmask = mac->base.cra_alignmask |
ctr->base.cra_alignmask;
inst->alg.ivsize = 16;
inst->alg.chunksize = crypto_skcipher_alg_chunksize(ctr);
inst->alg.maxauthsize = 16;
inst->alg.base.cra_ctxsize = sizeof(struct crypto_ccm_ctx);
inst->alg.init = crypto_ccm_init_tfm;
inst->alg.exit = crypto_ccm_exit_tfm;
inst->alg.setkey = crypto_ccm_setkey;
inst->alg.setauthsize = crypto_ccm_setauthsize;
inst->alg.encrypt = crypto_ccm_encrypt;
inst->alg.decrypt = crypto_ccm_decrypt;
inst->free = crypto_ccm_free;
err = aead_register_instance(tmpl, inst);
if (err)
goto err_drop_ctr;
out_put_mac:
crypto_mod_put(mac_alg);
return err;
err_drop_ctr:
crypto_drop_skcipher(&ictx->ctr);
err_drop_mac:
crypto_drop_ahash(&ictx->mac);
err_free_inst:
kfree(inst);
goto out_put_mac;
}
Commit Message: crypto: ccm - move cbcmac input off the stack
Commit f15f05b0a5de ("crypto: ccm - switch to separate cbcmac driver")
refactored the CCM driver to allow separate implementations of the
underlying MAC to be provided by a platform. However, in doing so, it
moved some data from the linear region to the stack, which violates the
SG constraints when the stack is virtually mapped.
So move idata/odata back to the request ctx struct, of which we can
reasonably expect that it has been allocated using kmalloc() et al.
Reported-by: Johannes Berg <[email protected]>
Fixes: f15f05b0a5de ("crypto: ccm - switch to separate cbcmac driver")
Signed-off-by: Ard Biesheuvel <[email protected]>
Tested-by: Johannes Berg <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int dn_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
struct dn_scp *scp = DN_SK(sk);
struct sk_buff_head *queue = &sk->sk_receive_queue;
size_t target = size > 1 ? 1 : 0;
size_t copied = 0;
int rv = 0;
struct sk_buff *skb, *n;
struct dn_skb_cb *cb = NULL;
unsigned char eor = 0;
long timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
lock_sock(sk);
if (sock_flag(sk, SOCK_ZAPPED)) {
rv = -EADDRNOTAVAIL;
goto out;
}
if (sk->sk_shutdown & RCV_SHUTDOWN) {
rv = 0;
goto out;
}
rv = dn_check_state(sk, NULL, 0, &timeo, flags);
if (rv)
goto out;
if (flags & ~(MSG_CMSG_COMPAT|MSG_PEEK|MSG_OOB|MSG_WAITALL|MSG_DONTWAIT|MSG_NOSIGNAL)) {
rv = -EOPNOTSUPP;
goto out;
}
if (flags & MSG_OOB)
queue = &scp->other_receive_queue;
if (flags & MSG_WAITALL)
target = size;
/*
* See if there is data ready to read, sleep if there isn't
*/
for(;;) {
DEFINE_WAIT(wait);
if (sk->sk_err)
goto out;
if (!skb_queue_empty(&scp->other_receive_queue)) {
if (!(flags & MSG_OOB)) {
msg->msg_flags |= MSG_OOB;
if (!scp->other_report) {
scp->other_report = 1;
goto out;
}
}
}
if (scp->state != DN_RUN)
goto out;
if (signal_pending(current)) {
rv = sock_intr_errno(timeo);
goto out;
}
if (dn_data_ready(sk, queue, flags, target))
break;
if (flags & MSG_DONTWAIT) {
rv = -EWOULDBLOCK;
goto out;
}
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
sk_wait_event(sk, &timeo, dn_data_ready(sk, queue, flags, target));
sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
finish_wait(sk_sleep(sk), &wait);
}
skb_queue_walk_safe(queue, skb, n) {
unsigned int chunk = skb->len;
cb = DN_SKB_CB(skb);
if ((chunk + copied) > size)
chunk = size - copied;
if (memcpy_to_msg(msg, skb->data, chunk)) {
rv = -EFAULT;
break;
}
copied += chunk;
if (!(flags & MSG_PEEK))
skb_pull(skb, chunk);
eor = cb->nsp_flags & 0x40;
if (skb->len == 0) {
skb_unlink(skb, queue);
kfree_skb(skb);
/*
* N.B. Don't refer to skb or cb after this point
* in loop.
*/
if ((scp->flowloc_sw == DN_DONTSEND) && !dn_congested(sk)) {
scp->flowloc_sw = DN_SEND;
dn_nsp_send_link(sk, DN_SEND, 0);
}
}
if (eor) {
if (sk->sk_type == SOCK_SEQPACKET)
break;
if (!(flags & MSG_WAITALL))
break;
}
if (flags & MSG_OOB)
break;
if (copied >= target)
break;
}
rv = copied;
if (eor && (sk->sk_type == SOCK_SEQPACKET))
msg->msg_flags |= MSG_EOR;
out:
if (rv == 0)
rv = (flags & MSG_PEEK) ? -sk->sk_err : sock_error(sk);
if ((rv >= 0) && msg->msg_name) {
__sockaddr_check_size(sizeof(struct sockaddr_dn));
memcpy(msg->msg_name, &scp->peer, sizeof(struct sockaddr_dn));
msg->msg_namelen = sizeof(struct sockaddr_dn);
}
release_sock(sk);
return rv;
}
Commit Message: net: add validation for the socket syscall protocol argument
郭永刚 reported that one could simply crash the kernel as root by
using a simple program:
int socket_fd;
struct sockaddr_in addr;
addr.sin_port = 0;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = 10;
socket_fd = socket(10,3,0x40000000);
connect(socket_fd , &addr,16);
AF_INET, AF_INET6 sockets actually only support 8-bit protocol
identifiers. inet_sock's skc_protocol field thus is sized accordingly,
thus larger protocol identifiers simply cut off the higher bits and
store a zero in the protocol fields.
This could lead to e.g. NULL function pointer because as a result of
the cut off inet_num is zero and we call down to inet_autobind, which
is NULL for raw sockets.
kernel: Call Trace:
kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70
kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80
kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110
kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80
kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200
kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10
kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89
I found no particular commit which introduced this problem.
CVE: CVE-2015-8543
Cc: Cong Wang <[email protected]>
Reported-by: 郭永刚 <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int powermate_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev (intf);
struct usb_host_interface *interface;
struct usb_endpoint_descriptor *endpoint;
struct powermate_device *pm;
struct input_dev *input_dev;
int pipe, maxp;
int error = -ENOMEM;
interface = intf->cur_altsetting;
endpoint = &interface->endpoint[0].desc;
if (!usb_endpoint_is_int_in(endpoint))
return -EIO;
usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x0a, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, interface->desc.bInterfaceNumber, NULL, 0,
USB_CTRL_SET_TIMEOUT);
pm = kzalloc(sizeof(struct powermate_device), GFP_KERNEL);
input_dev = input_allocate_device();
if (!pm || !input_dev)
goto fail1;
if (powermate_alloc_buffers(udev, pm))
goto fail2;
pm->irq = usb_alloc_urb(0, GFP_KERNEL);
if (!pm->irq)
goto fail2;
pm->config = usb_alloc_urb(0, GFP_KERNEL);
if (!pm->config)
goto fail3;
pm->udev = udev;
pm->intf = intf;
pm->input = input_dev;
usb_make_path(udev, pm->phys, sizeof(pm->phys));
strlcat(pm->phys, "/input0", sizeof(pm->phys));
spin_lock_init(&pm->lock);
switch (le16_to_cpu(udev->descriptor.idProduct)) {
case POWERMATE_PRODUCT_NEW:
input_dev->name = pm_name_powermate;
break;
case POWERMATE_PRODUCT_OLD:
input_dev->name = pm_name_soundknob;
break;
default:
input_dev->name = pm_name_soundknob;
printk(KERN_WARNING "powermate: unknown product id %04x\n",
le16_to_cpu(udev->descriptor.idProduct));
}
input_dev->phys = pm->phys;
usb_to_input_id(udev, &input_dev->id);
input_dev->dev.parent = &intf->dev;
input_set_drvdata(input_dev, pm);
input_dev->event = powermate_input_event;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL) |
BIT_MASK(EV_MSC);
input_dev->keybit[BIT_WORD(BTN_0)] = BIT_MASK(BTN_0);
input_dev->relbit[BIT_WORD(REL_DIAL)] = BIT_MASK(REL_DIAL);
input_dev->mscbit[BIT_WORD(MSC_PULSELED)] = BIT_MASK(MSC_PULSELED);
/* get a handle to the interrupt data pipe */
pipe = usb_rcvintpipe(udev, endpoint->bEndpointAddress);
maxp = usb_maxpacket(udev, pipe, usb_pipeout(pipe));
if (maxp < POWERMATE_PAYLOAD_SIZE_MIN || maxp > POWERMATE_PAYLOAD_SIZE_MAX) {
printk(KERN_WARNING "powermate: Expected payload of %d--%d bytes, found %d bytes!\n",
POWERMATE_PAYLOAD_SIZE_MIN, POWERMATE_PAYLOAD_SIZE_MAX, maxp);
maxp = POWERMATE_PAYLOAD_SIZE_MAX;
}
usb_fill_int_urb(pm->irq, udev, pipe, pm->data,
maxp, powermate_irq,
pm, endpoint->bInterval);
pm->irq->transfer_dma = pm->data_dma;
pm->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* register our interrupt URB with the USB system */
if (usb_submit_urb(pm->irq, GFP_KERNEL)) {
error = -EIO;
goto fail4;
}
error = input_register_device(pm->input);
if (error)
goto fail5;
/* force an update of everything */
pm->requires_update = UPDATE_PULSE_ASLEEP | UPDATE_PULSE_AWAKE | UPDATE_PULSE_MODE | UPDATE_STATIC_BRIGHTNESS;
powermate_pulse_led(pm, 0x80, 255, 0, 1, 0); // set default pulse parameters
usb_set_intfdata(intf, pm);
return 0;
fail5: usb_kill_urb(pm->irq);
fail4: usb_free_urb(pm->config);
fail3: usb_free_urb(pm->irq);
fail2: powermate_free_buffers(udev, pm);
fail1: input_free_device(input_dev);
kfree(pm);
return error;
}
Commit Message: Input: powermate - fix oops with malicious USB descriptors
The powermate driver expects at least one valid USB endpoint in its
probe function. If given malicious descriptors that specify 0 for
the number of endpoints, it will crash. Validate the number of
endpoints on the interface before using them.
The full report for this issue can be found here:
http://seclists.org/bugtraq/2016/Mar/85
Reported-by: Ralf Spenneberg <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Josh Boyer <[email protected]>
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: sctp_disposition_t sctp_sf_cookie_echoed_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_abort(net, ep, asoc, type, arg, commands);
}
Commit Message: sctp: Use correct sideffect command in duplicate cookie handling
When SCTP is done processing a duplicate cookie chunk, it tries
to delete a newly created association. For that, it has to set
the right association for the side-effect processing to work.
However, when it uses the SCTP_CMD_NEW_ASOC command, that performs
more work then really needed (like hashing the associationa and
assigning it an id) and there is no point to do that only to
delete the association as a next step. In fact, it also creates
an impossible condition where an association may be found by
the getsockopt() call, and that association is empty. This
causes a crash in some sctp getsockopts.
The solution is rather simple. We simply use SCTP_CMD_SET_ASOC
command that doesn't have all the overhead and does exactly
what we need.
Reported-by: Karl Heiss <[email protected]>
Tested-by: Karl Heiss <[email protected]>
CC: Neil Horman <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Acked-by: Neil Horman <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: sp<IMemory> SoundTriggerHwService::prepareServiceStateEvent_l(sound_trigger_service_state_t state)
{
sp<IMemory> eventMemory;
size_t size = sizeof(sound_trigger_service_state_t);
eventMemory = mMemoryDealer->allocate(size);
if (eventMemory == 0 || eventMemory->pointer() == NULL) {
eventMemory.clear();
return eventMemory;
}
*((sound_trigger_service_state_t *)eventMemory->pointer()) = state;
return eventMemory;
}
Commit Message: soundtrigger: add size check on sound model and recogntion data
Bug: 30148546
Change-Id: I082f535a853c96571887eeea37c6d41ecee7d8c0
(cherry picked from commit bb00d8f139ff51336ab3c810d35685003949bcf8)
(cherry picked from commit ef0c91518446e65533ca8bab6726a845f27c73fd)
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CairoOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg)
{
unsigned char *buffer;
unsigned int *dest;
cairo_surface_t *image;
cairo_pattern_t *pattern;
int x, y;
ImageStream *imgStr;
Guchar *pix;
int i;
cairo_matrix_t matrix;
int is_identity_transform;
buffer = (unsigned char *)gmalloc (width * height * 4);
/* TODO: Do we want to cache these? */
imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgStr->reset();
/* ICCBased color space doesn't do any color correction
* so check its underlying color space as well */
is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB ||
(colorMap->getColorSpace()->getMode() == csICCBased &&
((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB);
if (maskColors) {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
for (x = 0; x < width; x++) {
for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
if (pix[i] < maskColors[2*i] * 255||
pix[i] > maskColors[2*i+1] * 255) {
*dest = *dest | 0xff000000;
break;
}
}
pix += colorMap->getNumPixelComps();
dest++;
}
}
image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_ARGB32,
width, height, width * 4);
}
else {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
}
image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24,
width, height, width * 4);
}
if (image == NULL) {
delete imgStr;
return;
}
pattern = cairo_pattern_create_for_surface (image);
if (pattern == NULL) {
delete imgStr;
return;
}
LOG (printf ("drawImageMask %dx%d\n", width, height));
cairo_matrix_init_translate (&matrix, 0, height);
cairo_matrix_scale (&matrix, width, -height);
cairo_pattern_set_matrix (pattern, &matrix);
cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR);
cairo_set_source (cairo, pattern);
cairo_paint (cairo);
if (cairo_shape) {
#if 0
cairo_rectangle (cairo_shape, 0., 0., width, height);
cairo_fill (cairo_shape);
#else
cairo_save (cairo_shape);
/* this should draw a rectangle the size of the image
* we use this instead of rect,fill because of the lack
* of EXTEND_PAD */
/* NOTE: this will multiply the edges of the image twice */
cairo_set_source (cairo_shape, pattern);
cairo_paint(cairo_shape);
cairo_restore (cairo_shape);
#endif
}
cairo_pattern_destroy (pattern);
cairo_surface_destroy (image);
free (buffer);
delete imgStr;
}
Commit Message:
CWE ID: CWE-189
Target: 1
Example 2:
Code: int yr_object_function_create(
const char* identifier,
const char* arguments_fmt,
const char* return_fmt,
YR_MODULE_FUNC code,
YR_OBJECT* parent,
YR_OBJECT** function)
{
YR_OBJECT* return_obj;
YR_OBJECT* o = NULL;
YR_OBJECT_FUNCTION* f = NULL;
int8_t return_type;
int i;
switch (*return_fmt)
{
case 'i':
return_type = OBJECT_TYPE_INTEGER;
break;
case 's':
return_type = OBJECT_TYPE_STRING;
break;
case 'f':
return_type = OBJECT_TYPE_FLOAT;
break;
default:
return ERROR_INVALID_FORMAT;
}
if (parent != NULL)
{
assert(parent->type == OBJECT_TYPE_STRUCTURE);
f = (YR_OBJECT_FUNCTION*) yr_object_lookup_field(parent, identifier);
if (f != NULL && return_type != f->return_obj->type)
return ERROR_WRONG_RETURN_TYPE;
}
if (f == NULL) // Function doesn't exist yet
{
FAIL_ON_ERROR(
yr_object_create(
OBJECT_TYPE_FUNCTION,
identifier,
parent,
&o));
FAIL_ON_ERROR_WITH_CLEANUP(
yr_object_create(
return_type,
"result",
o,
&return_obj),
yr_object_destroy(o));
f = (YR_OBJECT_FUNCTION*) o;
}
for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++)
{
if (f->prototypes[i].arguments_fmt == NULL)
{
f->prototypes[i].arguments_fmt = arguments_fmt;
f->prototypes[i].code = code;
break;
}
}
if (function != NULL)
*function = (YR_OBJECT*) f;
return ERROR_SUCCESS;
}
Commit Message: Fix issue #658
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SYSCALL_DEFINE5(add_key, const char __user *, _type,
const char __user *, _description,
const void __user *, _payload,
size_t, plen,
key_serial_t, ringid)
{
key_ref_t keyring_ref, key_ref;
char type[32], *description;
void *payload;
long ret;
ret = -EINVAL;
if (plen > 1024 * 1024 - 1)
goto error;
/* draw all the data into kernel space */
ret = key_get_type_from_user(type, _type, sizeof(type));
if (ret < 0)
goto error;
description = NULL;
if (_description) {
description = strndup_user(_description, KEY_MAX_DESC_SIZE);
if (IS_ERR(description)) {
ret = PTR_ERR(description);
goto error;
}
if (!*description) {
kfree(description);
description = NULL;
} else if ((description[0] == '.') &&
(strncmp(type, "keyring", 7) == 0)) {
ret = -EPERM;
goto error2;
}
}
/* pull the payload in if one was supplied */
payload = NULL;
if (_payload) {
ret = -ENOMEM;
payload = kvmalloc(plen, GFP_KERNEL);
if (!payload)
goto error2;
ret = -EFAULT;
if (copy_from_user(payload, _payload, plen) != 0)
goto error3;
}
/* find the target keyring (which must be writable) */
keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
if (IS_ERR(keyring_ref)) {
ret = PTR_ERR(keyring_ref);
goto error3;
}
/* create or update the requested key and add it to the target
* keyring */
key_ref = key_create_or_update(keyring_ref, type, description,
payload, plen, KEY_PERM_UNDEF,
KEY_ALLOC_IN_QUOTA);
if (!IS_ERR(key_ref)) {
ret = key_ref_to_ptr(key_ref)->serial;
key_ref_put(key_ref);
}
else {
ret = PTR_ERR(key_ref);
}
key_ref_put(keyring_ref);
error3:
kvfree(payload);
error2:
kfree(description);
error:
return ret;
}
Commit Message: KEYS: fix dereferencing NULL payload with nonzero length
sys_add_key() and the KEYCTL_UPDATE operation of sys_keyctl() allowed a
NULL payload with nonzero length to be passed to the key type's
->preparse(), ->instantiate(), and/or ->update() methods. Various key
types including asymmetric, cifs.idmap, cifs.spnego, and pkcs7_test did
not handle this case, allowing an unprivileged user to trivially cause a
NULL pointer dereference (kernel oops) if one of these key types was
present. Fix it by doing the copy_from_user() when 'plen' is nonzero
rather than when '_payload' is non-NULL, causing the syscall to fail
with EFAULT as expected when an invalid buffer is specified.
Cc: [email protected] # 2.6.10+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int em_syscall(struct x86_emulate_ctxt *ctxt)
{
struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
/* syscall is not available in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86)
return emulate_ud(ctxt);
ops->get_msr(ctxt, MSR_EFER, &efer);
setup_syscalls_segments(ctxt, &cs, &ss);
ops->get_msr(ctxt, MSR_STAR, &msr_data);
msr_data >>= 32;
cs_sel = (u16)(msr_data & 0xfffc);
ss_sel = (u16)(msr_data + 8);
if (efer & EFER_LMA) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ctxt->regs[VCPU_REGS_RCX] = ctxt->_eip;
if (efer & EFER_LMA) {
#ifdef CONFIG_X86_64
ctxt->regs[VCPU_REGS_R11] = ctxt->eflags & ~EFLG_RF;
ops->get_msr(ctxt,
ctxt->mode == X86EMUL_MODE_PROT64 ?
MSR_LSTAR : MSR_CSTAR, &msr_data);
ctxt->_eip = msr_data;
ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data);
ctxt->eflags &= ~(msr_data | EFLG_RF);
#endif
} else {
/* legacy mode */
ops->get_msr(ctxt, MSR_STAR, &msr_data);
ctxt->_eip = (u32)msr_data;
ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF);
}
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: fix missing checks in syscall emulation
On hosts without this patch, 32bit guests will crash (and 64bit guests
may behave in a wrong way) for example by simply executing following
nasm-demo-application:
[bits 32]
global _start
SECTION .text
_start: syscall
(I tested it with winxp and linux - both always crashed)
Disassembly of section .text:
00000000 <_start>:
0: 0f 05 syscall
The reason seems a missing "invalid opcode"-trap (int6) for the
syscall opcode "0f05", which is not available on Intel CPUs
within non-longmodes, as also on some AMD CPUs within legacy-mode.
(depending on CPU vendor, MSR_EFER and cpuid)
Because previous mentioned OSs may not engage corresponding
syscall target-registers (STAR, LSTAR, CSTAR), they remain
NULL and (non trapping) syscalls are leading to multiple
faults and finally crashs.
Depending on the architecture (AMD or Intel) pretended by
guests, various checks according to vendor's documentation
are implemented to overcome the current issue and behave
like the CPUs physical counterparts.
[mtosatti: cleanup/beautify code]
Signed-off-by: Stephan Baerwolf <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void bioset_free(struct bio_set *bs)
{
if (bs->rescue_workqueue)
destroy_workqueue(bs->rescue_workqueue);
if (bs->bio_pool)
mempool_destroy(bs->bio_pool);
if (bs->bvec_pool)
mempool_destroy(bs->bvec_pool);
bioset_integrity_free(bs);
bio_put_slab(bs);
kfree(bs);
}
Commit Message: fix unbalanced page refcounting in bio_map_user_iov
bio_map_user_iov and bio_unmap_user do unbalanced pages refcounting if
IO vector has small consecutive buffers belonging to the same page.
bio_add_pc_page merges them into one, but the page reference is never
dropped.
Cc: [email protected]
Signed-off-by: Vitaly Mayatskikh <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-772
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostImpl::CopyFromBackingStore(
const gfx::Rect& src_subrect,
const gfx::Size& accelerated_dst_size,
const ReadbackRequestCallback& callback,
const SkColorType preferred_color_type) {
if (view_) {
TRACE_EVENT0("browser",
"RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
view_->CopyFromCompositingSurface(accelerated_copy_rect,
accelerated_dst_size, callback,
preferred_color_type);
return;
}
callback.Run(SkBitmap(), content::READBACK_FAILED);
}
Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI
BUG=590284
Review URL: https://codereview.chromium.org/1747183002
Cr-Commit-Position: refs/heads/master@{#378844}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool FrameSelection::SetSelectionDeprecated(
const SelectionInDOMTree& passed_selection,
const SetSelectionData& options) {
DCHECK(IsAvailable());
passed_selection.AssertValidFor(GetDocument());
SelectionInDOMTree::Builder builder(passed_selection);
if (ShouldAlwaysUseDirectionalSelection(frame_))
builder.SetIsDirectional(true);
SelectionInDOMTree new_selection = builder.Build();
if (granularity_strategy_ && !options.DoNotClearStrategy())
granularity_strategy_->Clear();
granularity_ = options.Granularity();
if (options.ShouldCloseTyping())
TypingCommand::CloseTyping(frame_);
if (options.ShouldClearTypingStyle())
frame_->GetEditor().ClearTypingStyle();
const SelectionInDOMTree old_selection_in_dom_tree =
selection_editor_->GetSelectionInDOMTree();
if (old_selection_in_dom_tree == new_selection)
return false;
selection_editor_->SetSelection(new_selection);
ScheduleVisualUpdateForPaintInvalidationIfNeeded();
const Document& current_document = GetDocument();
frame_->GetEditor().RespondToChangedSelection(
old_selection_in_dom_tree.ComputeStartPosition(),
options.ShouldCloseTyping() ? TypingContinuation::kEnd
: TypingContinuation::kContinue);
DCHECK_EQ(current_document, GetDocument());
return true;
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <[email protected]>
Reviewed-by: Xiaocheng Hu <[email protected]>
Reviewed-by: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119
Target: 1
Example 2:
Code: _kdc_find_padata(const KDC_REQ *req, int *start, int type)
{
if (req->padata == NULL)
return NULL;
while((size_t)*start < req->padata->len){
(*start)++;
if(req->padata->val[*start - 1].padata_type == (unsigned)type)
return &req->padata->val[*start - 1];
}
return NULL;
}
Commit Message: Security: Avoid NULL structure pointer member dereference
This can happen in the error path when processing malformed AS
requests with a NULL client name. Bug originally introduced on
Fri Feb 13 09:26:01 2015 +0100 in commit:
a873e21d7c06f22943a90a41dc733ae76799390d
kdc: base _kdc_fast_mk_error() on krb5_mk_error_ext()
Original patch by Jeffrey Altman <[email protected]>
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static LZWInfo *AcquireLZWInfo(Image *image,const size_t data_size)
{
LZWInfo
*lzw_info;
register ssize_t
i;
size_t
one;
lzw_info=(LZWInfo *) AcquireMagickMemory(sizeof(*lzw_info));
if (lzw_info == (LZWInfo *) NULL)
return((LZWInfo *) NULL);
(void) ResetMagickMemory(lzw_info,0,sizeof(*lzw_info));
lzw_info->image=image;
lzw_info->data_size=data_size;
one=1;
lzw_info->maximum_data_value=(one << data_size)-1;
lzw_info->clear_code=lzw_info->maximum_data_value+1;
lzw_info->end_code=lzw_info->maximum_data_value+2;
lzw_info->table[0]=(size_t *) AcquireQuantumMemory(MaximumLZWCode,
sizeof(*lzw_info->table));
lzw_info->table[1]=(size_t *) AcquireQuantumMemory(MaximumLZWCode,
sizeof(*lzw_info->table));
if ((lzw_info->table[0] == (size_t *) NULL) ||
(lzw_info->table[1] == (size_t *) NULL))
{
lzw_info=RelinquishLZWInfo(lzw_info);
return((LZWInfo *) NULL);
}
for (i=0; i <= (ssize_t) lzw_info->maximum_data_value; i++)
{
lzw_info->table[0][i]=0;
lzw_info->table[1][i]=(size_t) i;
}
ResetLZWInfo(lzw_info);
lzw_info->code_info.buffer[0]='\0';
lzw_info->code_info.buffer[1]='\0';
lzw_info->code_info.count=2;
lzw_info->code_info.bit=8*lzw_info->code_info.count;
lzw_info->code_info.eof=MagickFalse;
lzw_info->genesis=MagickTrue;
lzw_info->stack=(LZWStack *) AcquireMagickMemory(sizeof(*lzw_info->stack));
if (lzw_info->stack == (LZWStack *) NULL)
{
lzw_info=RelinquishLZWInfo(lzw_info);
return((LZWInfo *) NULL);
}
lzw_info->stack->codes=(size_t *) AcquireQuantumMemory(2UL*
MaximumLZWCode,sizeof(*lzw_info->stack->codes));
if (lzw_info->stack->codes == (size_t *) NULL)
{
lzw_info=RelinquishLZWInfo(lzw_info);
return((LZWInfo *) NULL);
}
lzw_info->stack->index=lzw_info->stack->codes;
lzw_info->stack->top=lzw_info->stack->codes+2*MaximumLZWCode;
return(lzw_info);
}
Commit Message:
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int imap_subscribe(char *path, bool subscribe)
{
struct ImapData *idata = NULL;
char buf[LONG_STRING];
char mbox[LONG_STRING];
char errstr[STRING];
struct Buffer err, token;
struct ImapMbox mx;
if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox)
{
mutt_error(_("Bad mailbox name"));
return -1;
}
idata = imap_conn_find(&(mx.account), 0);
if (!idata)
goto fail;
imap_fix_path(idata, mx.mbox, buf, sizeof(buf));
if (!*buf)
mutt_str_strfcpy(buf, "INBOX", sizeof(buf));
if (ImapCheckSubscribed)
{
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
snprintf(mbox, sizeof(mbox), "%smailboxes \"%s\"", subscribe ? "" : "un", path);
if (mutt_parse_rc_line(mbox, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
if (subscribe)
mutt_message(_("Subscribing to %s..."), buf);
else
mutt_message(_("Unsubscribing from %s..."), buf);
imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf);
snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
if (imap_exec(idata, buf, 0) < 0)
goto fail;
imap_unmunge_mbox_name(idata, mx.mbox);
if (subscribe)
mutt_message(_("Subscribed to %s"), mx.mbox);
else
mutt_message(_("Unsubscribed from %s"), mx.mbox);
FREE(&mx.mbox);
return 0;
fail:
FREE(&mx.mbox);
return -1;
}
Commit Message: Quote path in imap_subscribe
CWE ID: CWE-77
Target: 1
Example 2:
Code: void CommandBufferProxyImpl::OnClientError(gpu::error::Error error) {
CheckLock();
last_state_lock_.AssertAcquired();
last_state_.error = error;
last_state_.context_lost_reason = gpu::error::kUnknown;
DisconnectChannelInFreshCallStack();
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void nsc_encode_subsampling(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
BYTE* co_dst;
BYTE* cg_dst;
INT8* co_src0;
INT8* co_src1;
INT8* cg_src0;
INT8* cg_src1;
UINT32 tempWidth;
UINT32 tempHeight;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
for (y = 0; y < tempHeight >> 1; y++)
{
co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);
cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);
co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;
co_src1 = co_src0 + tempWidth;
cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;
cg_src1 = cg_src0 + tempWidth;
for (x = 0; x < tempWidth >> 1; x++)
{
*co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) +
(INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2);
*cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) +
(INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2);
co_src0 += 2;
co_src1 += 2;
cg_src0 += 2;
cg_src1 += 2;
}
}
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static vpx_codec_err_t decoder_peek_si_internal(const uint8_t *data,
unsigned int data_sz,
vpx_codec_stream_info_t *si,
int *is_intra_only,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state) {
int intra_only_flag = 0;
uint8_t clear_buffer[9];
if (data + data_sz <= data)
return VPX_CODEC_INVALID_PARAM;
si->is_kf = 0;
si->w = si->h = 0;
if (decrypt_cb) {
data_sz = VPXMIN(sizeof(clear_buffer), data_sz);
decrypt_cb(decrypt_state, data, clear_buffer, data_sz);
data = clear_buffer;
}
{
int show_frame;
int error_resilient;
struct vpx_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL };
const int frame_marker = vpx_rb_read_literal(&rb, 2);
const BITSTREAM_PROFILE profile = vp9_read_profile(&rb);
if (frame_marker != VP9_FRAME_MARKER)
return VPX_CODEC_UNSUP_BITSTREAM;
if (profile >= MAX_PROFILES)
return VPX_CODEC_UNSUP_BITSTREAM;
if ((profile >= 2 && data_sz <= 1) || data_sz < 1)
return VPX_CODEC_UNSUP_BITSTREAM;
if (vpx_rb_read_bit(&rb)) { // show an existing frame
vpx_rb_read_literal(&rb, 3); // Frame buffer to show.
return VPX_CODEC_OK;
}
if (data_sz <= 8)
return VPX_CODEC_UNSUP_BITSTREAM;
si->is_kf = !vpx_rb_read_bit(&rb);
show_frame = vpx_rb_read_bit(&rb);
error_resilient = vpx_rb_read_bit(&rb);
if (si->is_kf) {
if (!vp9_read_sync_code(&rb))
return VPX_CODEC_UNSUP_BITSTREAM;
if (!parse_bitdepth_colorspace_sampling(profile, &rb))
return VPX_CODEC_UNSUP_BITSTREAM;
vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
} else {
intra_only_flag = show_frame ? 0 : vpx_rb_read_bit(&rb);
rb.bit_offset += error_resilient ? 0 : 2; // reset_frame_context
if (intra_only_flag) {
if (!vp9_read_sync_code(&rb))
return VPX_CODEC_UNSUP_BITSTREAM;
if (profile > PROFILE_0) {
if (!parse_bitdepth_colorspace_sampling(profile, &rb))
return VPX_CODEC_UNSUP_BITSTREAM;
}
rb.bit_offset += REF_FRAMES; // refresh_frame_flags
vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
}
}
}
if (is_intra_only != NULL)
*is_intra_only = intra_only_flag;
return VPX_CODEC_OK;
}
Commit Message: DO NOT MERGE | libvpx: cherry-pick aa1c813 from upstream
Description from upstream:
vp9: Fix potential SEGV in decoder_peek_si_internal
decoder_peek_si_internal could potentially read more bytes than
what actually exists in the input buffer. We check for the buffer
size to be at least 8, but we try to read up to 10 bytes in the
worst case. A well crafted file could thus cause a segfault.
Likely change that introduced this bug was:
https://chromium-review.googlesource.com/#/c/70439 (git hash:
7c43fb6)
Bug: 30013856
Change-Id: If556414cb5b82472d5673e045bc185cc57bb9af3
(cherry picked from commit bd57d587c2eb743c61b049add18f9fd72bf78c33)
CWE ID: CWE-119
Target: 1
Example 2:
Code: http_write(const struct http *hp, int lvl, const char *pfx)
{
int l;
AZ(VSB_finish(hp->vsb));
vtc_dump(hp->vl, lvl, pfx, VSB_data(hp->vsb), VSB_len(hp->vsb));
l = write(hp->fd, VSB_data(hp->vsb), VSB_len(hp->vsb));
if (l != VSB_len(hp->vsb))
vtc_log(hp->vl, hp->fatal, "Write failed: (%d vs %d) %s",
l, VSB_len(hp->vsb), strerror(errno));
}
Commit Message: Do not consider a CR by itself as a valid line terminator
Varnish (prior to version 4.0) was not following the standard with
regard to line separator.
Spotted and analyzed by: Régis Leroy [regilero] [email protected]
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ChromeDownloadManagerDelegate::OnCheckDownloadAllowedComplete(
content::CheckDownloadAllowedCallback check_download_allowed_cb,
bool storage_permission_granted,
bool allow) {
if (!storage_permission_granted) {
} else if (allow) {
RecordDownloadSource(DOWNLOAD_INITIATED_BY_NAVIGATION);
} else {
RecordDownloadCount(CHROME_DOWNLOAD_COUNT_BLOCKED_BY_THROTTLING);
}
std::move(check_download_allowed_cb).Run(allow);
}
Commit Message: Downloads : Fixed an issue of opening incorrect download file
When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download.
Bug: 793620
Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8
Reviewed-on: https://chromium-review.googlesource.com/826477
Reviewed-by: David Trainor <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Commit-Queue: Shakti Sahu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#525810}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Response ServiceWorkerHandler::DispatchSyncEvent(
const std::string& origin,
const std::string& registration_id,
const std::string& tag,
bool last_chance) {
if (!enabled_)
return CreateDomainNotEnabledErrorResponse();
if (!process_)
return CreateContextErrorResponse();
int64_t id = 0;
if (!base::StringToInt64(registration_id, &id))
return CreateInvalidVersionIdErrorResponse();
StoragePartitionImpl* partition =
static_cast<StoragePartitionImpl*>(process_->GetStoragePartition());
BackgroundSyncContext* sync_context = partition->GetBackgroundSyncContext();
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&DispatchSyncEventOnIO, context_,
base::WrapRefCounted(sync_context),
GURL(origin), id, tag, last_chance));
return Response::OK();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Target: 1
Example 2:
Code: check_sender_has_retransmits(struct iperf_test *ipt)
{
if (ipt->sender && ipt->protocol->id == Ptcp && has_tcpinfo_retransmits())
ipt->sender_has_retransmits = 1;
else
ipt->sender_has_retransmits = 0;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: AdjustWaitForDelay (pointer waitTime, unsigned long newdelay)
{
static struct timeval delay_val;
struct timeval **wt = (struct timeval **) waitTime;
unsigned long olddelay;
if (*wt == NULL)
{
delay_val.tv_sec = newdelay / 1000;
delay_val.tv_usec = 1000 * (newdelay % 1000);
*wt = &delay_val;
}
else
{
olddelay = (*wt)->tv_sec * 1000 + (*wt)->tv_usec / 1000;
if (newdelay < olddelay)
{
(*wt)->tv_sec = newdelay / 1000;
(*wt)->tv_usec = 1000 * (newdelay % 1000);
}
}
}
Commit Message:
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void dns_resolver_describe(const struct key *key, struct seq_file *m)
{
seq_puts(m, key->description);
if (key_is_instantiated(key)) {
int err = PTR_ERR(key->payload.data[dns_key_error]);
if (err)
seq_printf(m, ": %d", err);
else
seq_printf(m, ": %u", key->datalen);
}
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int nl80211_set_cqm(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr *attrs[NL80211_ATTR_CQM_MAX + 1];
struct nlattr *cqm;
int err;
cqm = info->attrs[NL80211_ATTR_CQM];
if (!cqm) {
err = -EINVAL;
goto out;
}
err = nla_parse_nested(attrs, NL80211_ATTR_CQM_MAX, cqm,
nl80211_attr_cqm_policy);
if (err)
goto out;
if (attrs[NL80211_ATTR_CQM_RSSI_THOLD] &&
attrs[NL80211_ATTR_CQM_RSSI_HYST]) {
s32 threshold;
u32 hysteresis;
threshold = nla_get_u32(attrs[NL80211_ATTR_CQM_RSSI_THOLD]);
hysteresis = nla_get_u32(attrs[NL80211_ATTR_CQM_RSSI_HYST]);
err = nl80211_set_cqm_rssi(info, threshold, hysteresis);
} else
err = -EINVAL;
out:
return err;
}
Commit Message: nl80211: fix check for valid SSID size in scan operations
In both trigger_scan and sched_scan operations, we were checking for
the SSID length before assigning the value correctly. Since the
memory was just kzalloc'ed, the check was always failing and SSID with
over 32 characters were allowed to go through.
This was causing a buffer overflow when copying the actual SSID to the
proper place.
This bug has been there since 2.6.29-rc4.
Cc: [email protected]
Signed-off-by: Luciano Coelho <[email protected]>
Signed-off-by: John W. Linville <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ssize_t ib_ucm_send_mra(struct ib_ucm_file *file,
const char __user *inbuf,
int in_len, int out_len)
{
struct ib_ucm_context *ctx;
struct ib_ucm_mra cmd;
const void *data = NULL;
int result;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
result = ib_ucm_alloc_data(&data, cmd.data, cmd.len);
if (result)
return result;
ctx = ib_ucm_ctx_get(file, cmd.id);
if (!IS_ERR(ctx)) {
result = ib_send_cm_mra(ctx->cm_id, cmd.timeout, data, cmd.len);
ib_ucm_ctx_put(ctx);
} else
result = PTR_ERR(ctx);
kfree(data);
return result;
}
Commit Message: IB/security: Restrict use of the write() interface
The drivers/infiniband stack uses write() as a replacement for
bi-directional ioctl(). This is not safe. There are ways to
trigger write calls that result in the return structure that
is normally written to user space being shunted off to user
specified kernel memory instead.
For the immediate repair, detect and deny suspicious accesses to
the write API.
For long term, update the user space libraries and the kernel API
to something that doesn't present the same security vulnerabilities
(likely a structured ioctl() interface).
The impacted uAPI interfaces are generally only available if
hardware from drivers/infiniband is installed in the system.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
[ Expanded check to all known write() entry points ]
Cc: [email protected]
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings(
ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetExternalFileEntry",
base::Bind(&FileBrowserHandlerCustomBindings::GetExternalFileEntry,
base::Unretained(this)));
RouteFunction("GetEntryURL",
base::Bind(&FileBrowserHandlerCustomBindings::GetEntryURL,
base::Unretained(this)));
}
Commit Message: [Extensions] Add more bindings access checks
BUG=598165
Review URL: https://codereview.chromium.org/1854983002
Cr-Commit-Position: refs/heads/master@{#385282}
CWE ID:
Target: 1
Example 2:
Code: static void NodeAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "nodeAttribute");
Node* cpp_value = V8Node::ToImplWithTypeCheck(info.GetIsolate(), v8_value);
if (!cpp_value) {
exception_state.ThrowTypeError("The provided value is not of type 'Node'.");
return;
}
impl->setNodeAttribute(cpp_value);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
unsigned int b, unsigned int a, unsigned int in_digitized, double in,
unsigned int out, png_byte sample_depth, double err, double limit,
PNG_CONST char *name, double digitization_error)
{
/* Compare the scaled, digitzed, values of our local calculation (in+-err)
* with the digitized values libpng produced; 'sample_depth' is the actual
* digitization depth of the libpng output colors (the bit depth except for
* palette images where it is always 8.) The check on 'err' is to detect
* internal errors in pngvalid itself.
*/
unsigned int max = (1U<<sample_depth)-1;
double in_min = ceil((in-err)*max - digitization_error);
double in_max = floor((in+err)*max + digitization_error);
if (err > limit || !(out >= in_min && out <= in_max))
{
char message[256];
size_t pos;
pos = safecat(message, sizeof message, 0, name);
pos = safecat(message, sizeof message, pos, " output value error: rgba(");
pos = safecatn(message, sizeof message, pos, r);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, g);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, b);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, a);
pos = safecat(message, sizeof message, pos, "): ");
pos = safecatn(message, sizeof message, pos, out);
pos = safecat(message, sizeof message, pos, " expected: ");
pos = safecatn(message, sizeof message, pos, in_digitized);
pos = safecat(message, sizeof message, pos, " (");
pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
pos = safecat(message, sizeof message, pos, "..");
pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
pos = safecat(message, sizeof message, pos, ")");
png_error(pp, message);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int main(int argc, char *argv[]) {
struct mschm_decompressor *chmd;
struct mschmd_header *chm;
struct mschmd_file *file, **f;
unsigned int numf, i;
setbuf(stdout, NULL);
setbuf(stderr, NULL);
user_umask = umask(0); umask(user_umask);
MSPACK_SYS_SELFTEST(i);
if (i) return 0;
if ((chmd = mspack_create_chm_decompressor(NULL))) {
for (argv++; *argv; argv++) {
printf("%s\n", *argv);
if ((chm = chmd->open(chmd, *argv))) {
/* build an ordered list of files for maximum extraction speed */
for (numf=0, file=chm->files; file; file = file->next) numf++;
if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) {
for (i=0, file=chm->files; file; file = file->next) f[i++] = file;
qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc);
for (i = 0; i < numf; i++) {
char *outname = create_output_name((unsigned char *)f[i]->filename,NULL,0,1,0);
printf("Extracting %s\n", outname);
ensure_filepath(outname);
if (chmd->extract(chmd, f[i], outname)) {
printf("%s: extract error on \"%s\": %s\n",
*argv, f[i]->filename, ERROR(chmd));
}
free(outname);
}
free(f);
}
chmd->close(chmd, chm);
}
else {
printf("%s: can't open -- %s\n", *argv, ERROR(chmd));
}
}
mspack_destroy_chm_decompressor(chmd);
}
return 0;
}
Commit Message: add anti "../" and leading slash protection to chmextract
CWE ID: CWE-22
Target: 1
Example 2:
Code: lseg_construct(PG_FUNCTION_ARGS)
{
Point *pt1 = PG_GETARG_POINT_P(0);
Point *pt2 = PG_GETARG_POINT_P(1);
LSEG *result = (LSEG *) palloc(sizeof(LSEG));
result->p[0].x = pt1->x;
result->p[0].y = pt1->y;
result->p[1].x = pt2->x;
result->p[1].y = pt2->y;
#ifdef NOT_USED
result->m = point_sl(pt1, pt2);
#endif
PG_RETURN_LSEG_P(result);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int perf_default_core_config(const char *var __used, const char *value __used)
{
/* Add other config variables here and to Documentation/config.txt. */
return 0;
}
Commit Message: perf tools: do not look at ./config for configuration
In addition to /etc/perfconfig and $HOME/.perfconfig, perf looks for
configuration in the file ./config, imitating git which looks at
$GIT_DIR/config. If ./config is not a perf configuration file, it
fails, or worse, treats it as a configuration file and changes behavior
in some unexpected way.
"config" is not an unusual name for a file to be lying around and perf
does not have a private directory dedicated for its own use, so let's
just stop looking for configuration in the cwd. Callers needing
context-sensitive configuration can use the PERF_CONFIG environment
variable.
Requested-by: Christian Ohm <[email protected]>
Cc: [email protected]
Cc: Ben Hutchings <[email protected]>
Cc: Christian Ohm <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Paul Mackerras <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Jonathan Nieder <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void usage_exit() {
fprintf(stderr, "Usage: %s <width> <height> <infile> <outfile> <frame>\n",
exec_name);
exit(EXIT_FAILURE);
}
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
Target: 1
Example 2:
Code: static int setcos_getdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj)
{
int r;
struct sc_apdu apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x00;
apdu.ins = 0xCA; /* GET DATA */
apdu.p1 = data_obj->P1;
apdu.p2 = data_obj->P2;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = data_obj->Data;
apdu.le = 256;
apdu.resp = data_obj->Data;
apdu.resplen = data_obj->DataLen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "GET_DATA returned error");
if (apdu.resplen > data_obj->DataLen)
r = SC_ERROR_WRONG_LENGTH;
else
data_obj->DataLen = apdu.resplen;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->location());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes)
{
if (likely(i->nr_segs == 1)) {
i->iov_offset += bytes;
} else {
const struct iovec *iov = i->iov;
size_t base = i->iov_offset;
while (bytes) {
int copy = min(bytes, iov->iov_len - base);
bytes -= copy;
base += copy;
if (iov->iov_len == base) {
iov++;
base = 0;
}
}
i->iov = iov;
i->iov_offset = base;
}
}
Commit Message: fix writev regression: pan hanging unkillable and un-straceable
Frederik Himpe reported an unkillable and un-straceable pan process.
Zero length iovecs can go into an infinite loop in writev, because the
iovec iterator does not always advance over them.
The sequence required to trigger this is not trivial. I think it
requires that a zero-length iovec be followed by a non-zero-length iovec
which causes a pagefault in the atomic usercopy. This causes the writev
code to drop back into single-segment copy mode, which then tries to
copy the 0 bytes of the zero-length iovec; a zero length copy looks like
a failure though, so it loops.
Put a test into iov_iter_advance to catch zero-length iovecs. We could
just put the test in the fallback path, but I feel it is more robust to
skip over zero-length iovecs throughout the code (iovec iterator may be
used in filesystems too, so it should be robust).
Signed-off-by: Nick Piggin <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool IsPublicSuffixDomainMatch(const std::string& url1,
const std::string& url2) {
GURL gurl1(url1);
GURL gurl2(url2);
if (!gurl1.is_valid() || !gurl2.is_valid())
return false;
if (gurl1 == gurl2)
return true;
std::string domain1(GetRegistryControlledDomain(gurl1));
std::string domain2(GetRegistryControlledDomain(gurl2));
if (domain1.empty() || domain2.empty())
return false;
return gurl1.scheme() == gurl2.scheme() && domain1 == domain2 &&
gurl1.port() == gurl2.port();
}
Commit Message: [Android][TouchToFill] Use FindPasswordInfoForElement for triggering
Use for TouchToFill the same triggering logic that is used for regular
suggestions.
Bug: 1010233
Change-Id: I111d4eac4ce94dd94b86097b6b6c98e08875e11a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1834230
Commit-Queue: Boris Sazonov <[email protected]>
Reviewed-by: Vadym Doroshenko <[email protected]>
Cr-Commit-Position: refs/heads/master@{#702058}
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int tty_ldisc_open(struct tty_struct *tty, struct tty_ldisc *ld)
{
WARN_ON(test_and_set_bit(TTY_LDISC_OPEN, &tty->flags));
if (ld->ops->open) {
int ret;
/* BTM here locks versus a hangup event */
ret = ld->ops->open(tty);
if (ret)
clear_bit(TTY_LDISC_OPEN, &tty->flags);
tty_ldisc_debug(tty, "%p: opened\n", tty->ldisc);
return ret;
}
return 0;
}
Commit Message: tty: Prevent ldisc drivers from re-using stale tty fields
Line discipline drivers may mistakenly misuse ldisc-related fields
when initializing. For example, a failure to initialize tty->receive_room
in the N_GIGASET_M101 line discipline was recently found and fixed [1].
Now, the N_X25 line discipline has been discovered accessing the previous
line discipline's already-freed private data [2].
Harden the ldisc interface against misuse by initializing revelant
tty fields before instancing the new line discipline.
[1]
commit fd98e9419d8d622a4de91f76b306af6aa627aa9c
Author: Tilman Schmidt <[email protected]>
Date: Tue Jul 14 00:37:13 2015 +0200
isdn/gigaset: reset tty->receive_room when attaching ser_gigaset
[2] Report from Sasha Levin <[email protected]>
[ 634.336761] ==================================================================
[ 634.338226] BUG: KASAN: use-after-free in x25_asy_open_tty+0x13d/0x490 at addr ffff8800a743efd0
[ 634.339558] Read of size 4 by task syzkaller_execu/8981
[ 634.340359] =============================================================================
[ 634.341598] BUG kmalloc-512 (Not tainted): kasan: bad access detected
...
[ 634.405018] Call Trace:
[ 634.405277] dump_stack (lib/dump_stack.c:52)
[ 634.405775] print_trailer (mm/slub.c:655)
[ 634.406361] object_err (mm/slub.c:662)
[ 634.406824] kasan_report_error (mm/kasan/report.c:138 mm/kasan/report.c:236)
[ 634.409581] __asan_report_load4_noabort (mm/kasan/report.c:279)
[ 634.411355] x25_asy_open_tty (drivers/net/wan/x25_asy.c:559 (discriminator 1))
[ 634.413997] tty_ldisc_open.isra.2 (drivers/tty/tty_ldisc.c:447)
[ 634.414549] tty_set_ldisc (drivers/tty/tty_ldisc.c:567)
[ 634.415057] tty_ioctl (drivers/tty/tty_io.c:2646 drivers/tty/tty_io.c:2879)
[ 634.423524] do_vfs_ioctl (fs/ioctl.c:43 fs/ioctl.c:607)
[ 634.427491] SyS_ioctl (fs/ioctl.c:622 fs/ioctl.c:613)
[ 634.427945] entry_SYSCALL_64_fastpath (arch/x86/entry/entry_64.S:188)
Cc: Tilman Schmidt <[email protected]>
Cc: Sasha Levin <[email protected]>
Signed-off-by: Peter Hurley <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PageSerializer::addImageToResources(ImageResource* image, RenderObject* imageRenderer, const KURL& url)
{
if (!shouldAddURL(url))
return;
if (!image || !image->hasImage() || image->image() == Image::nullImage())
return;
RefPtr<SharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
if (!data)
data = image->image()->data();
addToResources(image, data, url);
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Document::storageBlockingStateDidChange()
{
if (Settings* settings = this->settings())
securityOrigin()->setStorageBlockingPolicy(settings->storageBlockingPolicy());
}
Commit Message: Unreviewed, rolling out r147402.
http://trac.webkit.org/changeset/147402
https://bugs.webkit.org/show_bug.cgi?id=112903
Source/WebCore:
* dom/Document.cpp:
(WebCore::Document::processHttpEquiv):
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::responseReceived):
LayoutTests:
* http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html:
* http/tests/security/XFrameOptions/x-frame-options-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool DataReductionProxySettings::IsDataReductionProxyEnabled() const {
if (base::FeatureList::IsEnabled(network::features::kNetworkService) &&
!params::IsEnabledWithNetworkService()) {
return false;
}
return IsDataSaverEnabledByUser();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int my_csr_reader( const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
REALTYPE** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
fprintf( stderr, "cannot open CSR file!\n" );
return -1;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
fprintf( stderr, "could not read file length!\n" );
return -1;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) {
/* allocate CSC datastructure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1));
*o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
fprintf( stderr, "could not allocate sp data!\n" );
return -1;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1));
memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count));
memset(*o_values, 0, sizeof(double)*(*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count));
/* init column idx */
for ( l_i = 0; l_i < (*o_row_count + 1); l_i++)
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
fprintf( stderr, "could not csr description!\n" );
return -1;
}
/* now we read the actual content */
} else {
unsigned int l_row, l_column;
REALTYPE l_value;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
fprintf( stderr, "could not read element!\n" );
return -1;
}
/* adjust numbers to zero termination */
l_row--;
l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
fprintf( stderr, "we were not able to read all elements!\n" );
return -1;
}
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
if ( l_row_idx_id != NULL ) {
free( l_row_idx_id );
}
return 0;
}
Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1).
CWE ID: CWE-119
Target: 1
Example 2:
Code: ZEND_API void zend_update_property_string(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */
{
zval *tmp;
ALLOC_ZVAL(tmp);
Z_UNSET_ISREF_P(tmp);
Z_SET_REFCOUNT_P(tmp, 0);
ZVAL_STRING(tmp, value, 1);
zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC);
}
/* }}} */
Commit Message:
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic,
unsigned long addr,
unsigned long length)
{
unsigned long result = 0;
switch (ioapic->ioregsel) {
case IOAPIC_REG_VERSION:
result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16)
| (IOAPIC_VERSION_ID & 0xff));
break;
case IOAPIC_REG_APIC_ID:
case IOAPIC_REG_ARB_ID:
result = ((ioapic->id & 0xf) << 24);
break;
default:
{
u32 redir_index = (ioapic->ioregsel - 0x10) >> 1;
u64 redir_content;
ASSERT(redir_index < IOAPIC_NUM_PINS);
redir_content = ioapic->redirtbl[redir_index].bits;
result = (ioapic->ioregsel & 0x1) ?
(redir_content >> 32) & 0xffffffff :
redir_content & 0xffffffff;
break;
}
}
return result;
}
Commit Message: KVM: Fix bounds checking in ioapic indirect register reads (CVE-2013-1798)
If the guest specifies a IOAPIC_REG_SELECT with an invalid value and follows
that with a read of the IOAPIC_REG_WINDOW KVM does not properly validate
that request. ioapic_read_indirect contains an
ASSERT(redir_index < IOAPIC_NUM_PINS), but the ASSERT has no effect in
non-debug builds. In recent kernels this allows a guest to cause a kernel
oops by reading invalid memory. In older kernels (pre-3.3) this allows a
guest to read from large ranges of host memory.
Tested: tested against apic unit tests.
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DOMHandler::DOMHandler()
: DevToolsDomainHandler(DOM::Metainfo::domainName),
host_(nullptr) {
}
Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles
Bug: 805557
Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f
Reviewed-on: https://chromium-review.googlesource.com/c/1334847
Reviewed-by: Pavel Feldman <[email protected]>
Commit-Queue: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607902}
CWE ID: CWE-254
Target: 1
Example 2:
Code: void RenderFrameHostImpl::OnShowCreatedWindow(int pending_widget_routing_id,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture) {
delegate_->ShowCreatedWindow(GetProcess()->GetID(), pending_widget_routing_id,
disposition, initial_rect, user_gesture);
}
Commit Message: Correctly reset FP in RFHI whenever origin changes
Bug: 713364
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
Reviewed-on: https://chromium-review.googlesource.com/482380
Commit-Queue: Ian Clelland <[email protected]>
Reviewed-by: Charles Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#466778}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void r_pkcs7_free_signeddata (RPKCS7SignedData* sd) {
if (sd) {
r_pkcs7_free_digestalgorithmidentifier (&sd->digestAlgorithms);
r_pkcs7_free_contentinfo (&sd->contentInfo);
r_pkcs7_free_extendedcertificatesandcertificates (&sd->certificates);
r_pkcs7_free_certificaterevocationlists (&sd->crls);
r_pkcs7_free_signerinfos (&sd->signerinfos);
}
}
Commit Message: Fix #7152 - Null deref in cms
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
WebContentsImpl* old_contents = GetFocusedWebContents();
if (old_contents == this)
return;
GetOutermostWebContents()->node_.SetFocusedWebContents(this);
if (!GuestMode::IsCrossProcessFrameGuest(this) && browser_plugin_guest_)
return;
if (old_contents)
old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
if (GetRenderManager()->GetProxyToOuterDelegate())
GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
if (ShowingInterstitialPage()) {
static_cast<RenderFrameHostImpl*>(
GetRenderManager()->interstitial_page()->GetMainFrame())
->GetRenderWidgetHost()
->SetPageFocus(true);
} else {
GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
}
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void LocalFrame::PrintNavigationErrorMessage(const Frame& target_frame,
const char* reason) {
String target_frame_description =
target_frame.IsLocalFrame()
? "with URL '" +
ToLocalFrame(target_frame).GetDocument()->Url().GetString() +
"'"
: "with origin '" +
target_frame.GetSecurityContext()
->GetSecurityOrigin()
->ToString() +
"'";
String message =
"Unsafe JavaScript attempt to initiate navigation for frame " +
target_frame_description + " from frame with URL '" +
GetDocument()->Url().GetString() + "'. " + reason + "\n";
DomWindow()->PrintErrorMessage(message);
}
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567663}
CWE ID: CWE-285
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ipip6_tunnel_get_prl(struct ip_tunnel *t,
struct ip_tunnel_prl __user *a)
{
struct ip_tunnel_prl kprl, *kp;
struct ip_tunnel_prl_entry *prl;
unsigned int cmax, c = 0, ca, len;
int ret = 0;
if (copy_from_user(&kprl, a, sizeof(kprl)))
return -EFAULT;
cmax = kprl.datalen / sizeof(kprl);
if (cmax > 1 && kprl.addr != htonl(INADDR_ANY))
cmax = 1;
/* For simple GET or for root users,
* we try harder to allocate.
*/
kp = (cmax <= 1 || capable(CAP_NET_ADMIN)) ?
kcalloc(cmax, sizeof(*kp), GFP_KERNEL) :
NULL;
rcu_read_lock();
ca = t->prl_count < cmax ? t->prl_count : cmax;
if (!kp) {
/* We don't try hard to allocate much memory for
* non-root users.
* For root users, retry allocating enough memory for
* the answer.
*/
kp = kcalloc(ca, sizeof(*kp), GFP_ATOMIC);
if (!kp) {
ret = -ENOMEM;
goto out;
}
}
c = 0;
for_each_prl_rcu(t->prl) {
if (c >= cmax)
break;
if (kprl.addr != htonl(INADDR_ANY) && prl->addr != kprl.addr)
continue;
kp[c].addr = prl->addr;
kp[c].flags = prl->flags;
c++;
if (kprl.addr != htonl(INADDR_ANY))
break;
}
out:
rcu_read_unlock();
len = sizeof(*kp) * c;
ret = 0;
if ((len && copy_to_user(a + 1, kp, len)) || put_user(len, &a->datalen))
ret = -EFAULT;
kfree(kp);
return ret;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ServiceWorkerHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_ = process_host;
if (!process_host) {
ClearForceUpdate();
context_ = nullptr;
return;
}
StoragePartition* partition = process_host->GetStoragePartition();
DCHECK(partition);
context_ = static_cast<ServiceWorkerContextWrapper*>(
partition->GetServiceWorkerContext());
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void DeprecateAsSameValueMeasureAsOverloadedMethod1Method(const v8::FunctionCallbackInfo<v8::Value>& info) {
TestObject* impl = V8TestObject::ToImpl(info.Holder());
impl->deprecateAsSameValueMeasureAsOverloadedMethod();
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MagickExport MagickSizeType ReadBlobMSBLongLong(Image *image)
{
register const unsigned char
*p;
register MagickSizeType
value;
ssize_t
count;
unsigned char
buffer[8];
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
*buffer='\0';
p=(const unsigned char *) ReadBlobStream(image,8,buffer,&count);
if (count != 8)
return(MagickULLConstant(0));
value=(MagickSizeType) (*p++) << 56;
value|=(MagickSizeType) (*p++) << 48;
value|=(MagickSizeType) (*p++) << 40;
value|=(MagickSizeType) (*p++) << 32;
value|=(MagickSizeType) (*p++) << 24;
value|=(MagickSizeType) (*p++) << 16;
value|=(MagickSizeType) (*p++) << 8;
value|=(MagickSizeType) (*p++);
return(value);
}
Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WORD32 ih264d_start_of_pic(dec_struct_t *ps_dec,
WORD32 i4_poc,
pocstruct_t *ps_temp_poc,
UWORD16 u2_frame_num,
dec_pic_params_t *ps_pps)
{
pocstruct_t *ps_prev_poc = &ps_dec->s_cur_pic_poc;
pocstruct_t *ps_cur_poc = ps_temp_poc;
pic_buffer_t *pic_buf;
ivd_video_decode_op_t * ps_dec_output =
(ivd_video_decode_op_t *)ps_dec->pv_dec_out;
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
dec_seq_params_t *ps_seq = ps_pps->ps_sps;
UWORD8 u1_bottom_field_flag = ps_cur_slice->u1_bottom_field_flag;
UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag;
/* high profile related declarations */
high_profile_tools_t s_high_profile;
WORD32 ret;
H264_MUTEX_LOCK(&ps_dec->process_disp_mutex);
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0];
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1];
ps_prev_poc->u1_bot_field = ps_dec->ps_cur_slice->u1_bottom_field_flag;
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst;
ps_prev_poc->u2_frame_num = u2_frame_num;
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->i1_next_ctxt_idx = 0;
ps_dec->u4_nmb_deblk = 0;
if(ps_dec->u4_num_cores == 1)
ps_dec->u4_nmb_deblk = 1;
if(ps_seq->u1_mb_aff_flag == 1)
{
ps_dec->u4_nmb_deblk = 0;
if(ps_dec->u4_num_cores > 2)
ps_dec->u4_num_cores = 2;
}
ps_dec->u4_use_intrapred_line_copy = 0;
if (ps_seq->u1_mb_aff_flag == 0)
{
ps_dec->u4_use_intrapred_line_copy = 1;
}
ps_dec->u4_app_disable_deblk_frm = 0;
/* If degrade is enabled, set the degrade flags appropriately */
if(ps_dec->i4_degrade_type && ps_dec->i4_degrade_pics)
{
WORD32 degrade_pic;
ps_dec->i4_degrade_pic_cnt++;
degrade_pic = 0;
/* If degrade is to be done in all frames, then do not check further */
switch(ps_dec->i4_degrade_pics)
{
case 4:
{
degrade_pic = 1;
break;
}
case 3:
{
if(ps_cur_slice->u1_slice_type != I_SLICE)
degrade_pic = 1;
break;
}
case 2:
{
/* If pic count hits non-degrade interval or it is an islice, then do not degrade */
if((ps_cur_slice->u1_slice_type != I_SLICE)
&& (ps_dec->i4_degrade_pic_cnt
!= ps_dec->i4_nondegrade_interval))
degrade_pic = 1;
break;
}
case 1:
{
/* Check if the current picture is non-ref */
if(0 == ps_cur_slice->u1_nal_ref_idc)
{
degrade_pic = 1;
}
break;
}
}
if(degrade_pic)
{
if(ps_dec->i4_degrade_type & 0x2)
ps_dec->u4_app_disable_deblk_frm = 1;
/* MC degrading is done only for non-ref pictures */
if(0 == ps_cur_slice->u1_nal_ref_idc)
{
if(ps_dec->i4_degrade_type & 0x4)
ps_dec->i4_mv_frac_mask = 0;
if(ps_dec->i4_degrade_type & 0x8)
ps_dec->i4_mv_frac_mask = 0;
}
}
else
ps_dec->i4_degrade_pic_cnt = 0;
}
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_dec->u1_sl_typ_5_9
&& ((ps_cur_slice->u1_slice_type == I_SLICE)
|| (ps_cur_slice->u1_slice_type
== SI_SLICE)))
ps_err->u1_cur_pic_type = PIC_TYPE_I;
else
ps_err->u1_cur_pic_type = PIC_TYPE_UNKNOWN;
if(ps_err->u1_pic_aud_i == PIC_TYPE_I)
{
ps_err->u1_cur_pic_type = PIC_TYPE_I;
ps_err->u1_pic_aud_i = PIC_TYPE_UNKNOWN;
}
if(ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
if(ps_err->u1_err_flag)
ih264d_reset_ref_bufs(ps_dec->ps_dpb_mgr);
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
}
}
if(ps_dec->u1_init_dec_flag && ps_dec->s_prev_seq_params.u1_eoseq_pending)
{
/* Reset the decoder picture buffers */
WORD32 j;
for(j = 0; j < MAX_DISP_BUFS_NEW; j++)
{
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
ps_dec->au1_pic_buf_id_mv_buf_id_map[j],
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_IO);
}
/* reset the decoder structure parameters related to buffer handling */
ps_dec->u1_second_field = 0;
ps_dec->i4_cur_display_seq = 0;
/********************************************************************/
/* indicate in the decoder output i4_status that some frames are being */
/* dropped, so that it resets timestamp and wait for a new sequence */
/********************************************************************/
ps_dec->s_prev_seq_params.u1_eoseq_pending = 0;
}
ret = ih264d_init_pic(ps_dec, u2_frame_num, i4_poc, ps_pps);
if(ret != OK)
return ret;
ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data;
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data;
ps_dec->ps_nmb_info = ps_dec->ps_frm_mb_info;
if(ps_dec->u1_separate_parse)
{
UWORD16 pic_wd = ps_dec->u4_width_at_init;
UWORD16 pic_ht = ps_dec->u4_height_at_init;
UWORD32 num_mbs;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
pic_wd = ps_dec->u2_pic_wd;
pic_ht = ps_dec->u2_pic_ht;
}
num_mbs = (pic_wd * pic_ht) >> 8;
if(ps_dec->pu1_dec_mb_map)
{
memset((void *)ps_dec->pu1_dec_mb_map, 0, num_mbs);
}
if(ps_dec->pu1_recon_mb_map)
{
memset((void *)ps_dec->pu1_recon_mb_map, 0, num_mbs);
}
if(ps_dec->pu2_slice_num_map)
{
memset((void *)ps_dec->pu2_slice_num_map, 0,
(num_mbs * sizeof(UWORD16)));
}
}
ps_dec->ps_parse_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->ps_decode_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->ps_computebs_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->u2_cur_slice_num = 0;
/* Initialize all the HP toolsets to zero */
ps_dec->s_high_profile.u1_scaling_present = 0;
ps_dec->s_high_profile.u1_transform8x8_present = 0;
/* Get Next Free Picture */
if(1 == ps_dec->u4_share_disp_buf)
{
UWORD32 i;
/* Free any buffer that is in the queue to be freed */
for(i = 0; i < MAX_DISP_BUFS_NEW; i++)
{
if(0 == ps_dec->u4_disp_buf_to_be_freed[i])
continue;
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, i,
BUF_MGR_IO);
ps_dec->u4_disp_buf_to_be_freed[i] = 0;
ps_dec->u4_disp_buf_mapping[i] = 0;
}
}
if(!(u1_field_pic_flag && 0 != ps_dec->u1_top_bottom_decoded)) //ps_dec->u1_second_field))
{
pic_buffer_t *ps_cur_pic;
WORD32 cur_pic_buf_id, cur_mv_buf_id;
col_mv_buf_t *ps_col_mv;
while(1)
{
ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
&cur_pic_buf_id);
if(ps_cur_pic == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T;
return ERROR_UNAVAIL_PICBUF_T;
}
if(0 == ps_dec->u4_disp_buf_mapping[cur_pic_buf_id])
{
break;
}
}
ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
&cur_mv_buf_id);
if(ps_col_mv == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T;
return ERROR_UNAVAIL_MVBUF_T;
}
ps_dec->ps_cur_pic = ps_cur_pic;
ps_dec->u1_pic_buf_id = cur_pic_buf_id;
ps_cur_pic->u4_ts = ps_dec->u4_ts;
ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id;
ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id;
ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag;
ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv;
ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0;
{
/*make first entry of list0 point to cur pic,so that if first Islice is in error, ref pic struct will have valid entries*/
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0];
*(ps_dec->ps_dpb_mgr->ps_init_dpb[0][0]) = *ps_cur_pic;
/* Initialize for field reference as well */
*(ps_dec->ps_dpb_mgr->ps_init_dpb[0][MAX_REF_BUFS]) = *ps_cur_pic;
}
if(!ps_dec->ps_cur_pic)
{
WORD32 j;
H264_DEC_DEBUG_PRINT("------- Display Buffers Reset --------\n");
for(j = 0; j < MAX_DISP_BUFS_NEW; j++)
{
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
ps_dec->au1_pic_buf_id_mv_buf_id_map[j],
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_IO);
}
ps_dec->i4_cur_display_seq = 0;
ps_dec->i4_prev_max_display_seq = 0;
ps_dec->i4_max_poc = 0;
ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
&cur_pic_buf_id);
if(ps_cur_pic == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T;
return ERROR_UNAVAIL_PICBUF_T;
}
ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
&cur_mv_buf_id);
if(ps_col_mv == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T;
return ERROR_UNAVAIL_MVBUF_T;
}
ps_dec->ps_cur_pic = ps_cur_pic;
ps_dec->u1_pic_buf_id = cur_pic_buf_id;
ps_cur_pic->u4_ts = ps_dec->u4_ts;
ps_dec->apv_buf_id_pic_buf_map[cur_pic_buf_id] = (void *)ps_cur_pic;
ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id;
ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id;
ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag;
ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv;
ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0;
}
ps_dec->ps_cur_pic->u1_picturetype = u1_field_pic_flag;
ps_dec->ps_cur_pic->u4_pack_slc_typ = SKIP_NONE;
H264_DEC_DEBUG_PRINT("got a buffer\n");
}
else
{
H264_DEC_DEBUG_PRINT("did not get a buffer\n");
}
ps_dec->u4_pic_buf_got = 1;
ps_dec->ps_cur_pic->i4_poc = i4_poc;
ps_dec->ps_cur_pic->i4_frame_num = u2_frame_num;
ps_dec->ps_cur_pic->i4_pic_num = u2_frame_num;
ps_dec->ps_cur_pic->i4_top_field_order_cnt = ps_pps->i4_top_field_order_cnt;
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt =
ps_pps->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_avg_poc = ps_pps->i4_avg_poc;
ps_dec->ps_cur_pic->u4_time_stamp = ps_dec->u4_pts;
ps_dec->s_cur_pic = *(ps_dec->ps_cur_pic);
if(u1_field_pic_flag && u1_bottom_field_flag)
{
WORD32 i4_temp_poc;
WORD32 i4_top_field_order_poc, i4_bot_field_order_poc;
/* Point to odd lines, since it's bottom field */
ps_dec->s_cur_pic.pu1_buf1 += ps_dec->s_cur_pic.u2_frm_wd_y;
ps_dec->s_cur_pic.pu1_buf2 += ps_dec->s_cur_pic.u2_frm_wd_uv;
ps_dec->s_cur_pic.pu1_buf3 += ps_dec->s_cur_pic.u2_frm_wd_uv;
ps_dec->s_cur_pic.ps_mv +=
((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5);
ps_dec->s_cur_pic.pu1_col_zero_flag += ((ps_dec->u2_pic_ht
* ps_dec->u2_pic_wd) >> 5);
ps_dec->ps_cur_pic->u1_picturetype |= BOT_FLD;
i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
i4_temp_poc = MIN(i4_top_field_order_poc,
i4_bot_field_order_poc);
ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc;
}
ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag
&& (!u1_field_pic_flag);
ps_dec->ps_cur_pic->u1_picturetype |= (ps_cur_slice->u1_mbaff_frame_flag
<< 2);
ps_dec->ps_cur_mb_row = ps_dec->ps_nbr_mb_row; //[0];
ps_dec->ps_cur_mb_row++; //Increment by 1 ,so that left mb will always be valid
ps_dec->ps_top_mb_row =
ps_dec->ps_nbr_mb_row
+ ((ps_dec->u2_frm_wd_in_mbs + 1)
<< (1
- ps_dec->ps_cur_sps->u1_frame_mbs_only_flag));
ps_dec->ps_top_mb_row++; //Increment by 1 ,so that left mb will always be valid
ps_dec->pu1_y = ps_dec->pu1_y_scratch[0];
ps_dec->pu1_u = ps_dec->pu1_u_scratch[0];
ps_dec->pu1_v = ps_dec->pu1_v_scratch[0];
ps_dec->u1_yuv_scratch_idx = 0;
/* CHANGED CODE */
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv;
ps_dec->ps_mv_top = ps_dec->ps_mv_top_p[0];
/* CHANGED CODE */
ps_dec->u1_mv_top_p = 0;
ps_dec->u1_mb_idx = 0;
/* CHANGED CODE */
ps_dec->ps_mv_left = ps_dec->s_cur_pic.ps_mv;
ps_dec->pu1_yleft = 0;
ps_dec->pu1_uleft = 0;
ps_dec->pu1_vleft = 0;
ps_dec->u1_not_wait_rec = 2;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->i4_submb_ofst = -(SUB_BLK_SIZE);
ps_dec->u4_pred_info_idx = 0;
ps_dec->u4_pred_info_pkd_idx = 0;
ps_dec->u4_dma_buf_idx = 0;
ps_dec->ps_mv = ps_dec->s_cur_pic.ps_mv;
ps_dec->ps_mv_bank_cur = ps_dec->s_cur_pic.ps_mv;
ps_dec->pu1_col_zero_flag = ps_dec->s_cur_pic.pu1_col_zero_flag;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->i2_prev_slice_mbx = -1;
ps_dec->i2_prev_slice_mby = 0;
ps_dec->u2_mv_2mb[0] = 0;
ps_dec->u2_mv_2mb[1] = 0;
ps_dec->u1_last_pic_not_decoded = 0;
ps_dec->u2_cur_slice_num_dec_thread = 0;
ps_dec->u2_cur_slice_num_bs = 0;
ps_dec->u4_intra_pred_line_ofst = 0;
ps_dec->pu1_cur_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line;
ps_dec->pu1_cur_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line;
ps_dec->pu1_cur_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line;
ps_dec->pu1_cur_y_intra_pred_line_base = ps_dec->pu1_y_intra_pred_line;
ps_dec->pu1_cur_u_intra_pred_line_base = ps_dec->pu1_u_intra_pred_line;
ps_dec->pu1_cur_v_intra_pred_line_base = ps_dec->pu1_v_intra_pred_line;
ps_dec->pu1_prev_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line
+ (ps_dec->u2_frm_wd_in_mbs * MB_SIZE);
ps_dec->pu1_prev_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line
+ ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE * YUV420SP_FACTOR;
ps_dec->pu1_prev_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line
+ ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE;
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic;
ps_dec->ps_deblk_mbn_curr = ps_dec->ps_deblk_mbn;
ps_dec->ps_deblk_mbn_prev = ps_dec->ps_deblk_mbn + ps_dec->u1_recon_mb_grp;
/* Initialize The Function Pointer Depending Upon the Entropy and MbAff Flag */
{
if(ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_compute_bs = ih264d_compute_bs_mbaff;
ps_dec->pf_mvpred = ih264d_mvpred_mbaff;
}
else
{
ps_dec->pf_compute_bs = ih264d_compute_bs_non_mbaff;
ps_dec->u1_cur_mb_fld_dec_flag = ps_cur_slice->u1_field_pic_flag;
}
}
/* Set up the Parameter for DMA transfer */
{
UWORD8 u1_field_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag;
UWORD8 u1_mbaff = ps_cur_slice->u1_mbaff_frame_flag;
UWORD8 uc_lastmbs = (((ps_dec->u2_pic_wd) >> 4)
% (ps_dec->u1_recon_mb_grp >> u1_mbaff));
UWORD16 ui16_lastmbs_widthY =
(uc_lastmbs ? (uc_lastmbs << 4) : ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) << 4));
UWORD16 ui16_lastmbs_widthUV =
uc_lastmbs ? (uc_lastmbs << 3) : ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) << 3);
ps_dec->s_tran_addrecon.pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1;
ps_dec->s_tran_addrecon.pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2;
ps_dec->s_tran_addrecon.pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3;
ps_dec->s_tran_addrecon.u2_frm_wd_y = ps_dec->u2_frm_wd_y
<< u1_field_pic_flag;
ps_dec->s_tran_addrecon.u2_frm_wd_uv = ps_dec->u2_frm_wd_uv
<< u1_field_pic_flag;
if(u1_field_pic_flag)
{
ui16_lastmbs_widthY += ps_dec->u2_frm_wd_y;
ui16_lastmbs_widthUV += ps_dec->u2_frm_wd_uv;
}
/* Normal Increment of Pointer */
ps_dec->s_tran_addrecon.u4_inc_y[0] = ((ps_dec->u1_recon_mb_grp << 4)
>> u1_mbaff);
ps_dec->s_tran_addrecon.u4_inc_uv[0] = ((ps_dec->u1_recon_mb_grp << 4)
>> u1_mbaff);
/* End of Row Increment */
ps_dec->s_tran_addrecon.u4_inc_y[1] = (ui16_lastmbs_widthY
+ (PAD_LEN_Y_H << 1)
+ ps_dec->s_tran_addrecon.u2_frm_wd_y
* ((15 << u1_mbaff) + u1_mbaff));
ps_dec->s_tran_addrecon.u4_inc_uv[1] = (ui16_lastmbs_widthUV
+ (PAD_LEN_UV_H << 2)
+ ps_dec->s_tran_addrecon.u2_frm_wd_uv
* ((15 << u1_mbaff) + u1_mbaff));
/* Assign picture numbers to each frame/field */
/* only once per picture. */
ih264d_assign_pic_num(ps_dec);
ps_dec->s_tran_addrecon.u2_mv_top_left_inc = (ps_dec->u1_recon_mb_grp
<< 2) - 1 - (u1_mbaff << 2);
ps_dec->s_tran_addrecon.u2_mv_left_inc = ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) - 1) << (4 + u1_mbaff);
}
/**********************************************************************/
/* High profile related initialization at pictrue level */
/**********************************************************************/
if(ps_seq->u1_profile_idc == HIGH_PROFILE_IDC)
{
if((ps_seq->i4_seq_scaling_matrix_present_flag)
|| (ps_pps->i4_pic_scaling_matrix_present_flag))
{
ih264d_form_scaling_matrix_picture(ps_seq, ps_pps, ps_dec);
ps_dec->s_high_profile.u1_scaling_present = 1;
}
else
{
ih264d_form_default_scaling_matrix(ps_dec);
}
if(ps_pps->i4_transform_8x8_mode_flag)
{
ps_dec->s_high_profile.u1_transform8x8_present = 1;
}
}
else
{
ih264d_form_default_scaling_matrix(ps_dec);
}
/* required while reading the transform_size_8x8 u4_flag */
ps_dec->s_high_profile.u1_direct_8x8_inference_flag =
ps_seq->u1_direct_8x8_inference_flag;
ps_dec->s_high_profile.s_cavlc_ctxt = ps_dec->s_cavlc_ctxt;
ps_dec->i1_recon_in_thread3_flag = 1;
ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_addrecon;
if(ps_dec->u1_separate_parse)
{
memcpy(&ps_dec->s_tran_addrecon_parse, &ps_dec->s_tran_addrecon,
sizeof(tfr_ctxt_t));
if(ps_dec->u4_num_cores >= 3 && ps_dec->i1_recon_in_thread3_flag)
{
memcpy(&ps_dec->s_tran_iprecon, &ps_dec->s_tran_addrecon,
sizeof(tfr_ctxt_t));
ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_iprecon;
}
}
ih264d_init_deblk_tfr_ctxt(ps_dec,&(ps_dec->s_pad_mgr), &(ps_dec->s_tran_addrecon),
ps_dec->u2_frm_wd_in_mbs, 0);
ps_dec->ps_cur_deblk_mb = ps_dec->ps_deblk_pic;
ps_dec->u4_cur_deblk_mb_num = 0;
ps_dec->u4_deblk_mb_x = 0;
ps_dec->u4_deblk_mb_y = 0;
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex);
return OK;
}
Commit Message: Decoder: Fixed initialization of first_slice_in_pic
To handle some errors, first_slice_in_pic was being set to 2.
This is now cleaned up and first_slice_in_pic is set to 1 only once per pic.
This will ensure picture level initializations are done only once even in case
of error clips
Bug: 33717589
Bug: 33551775
Bug: 33716442
Bug: 33677995
Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba
CWE ID: CWE-200
Target: 1
Example 2:
Code: const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const {
if (idx < 0)
return 0;
if (idx >= m_void_element_count)
return 0;
return m_void_elements + idx;
}
Commit Message: Fix ParseElementHeader to support 0 payload elements
Cherry-pick'ing Change 5c83bbec9a5f6f00a349674ddad85b753d2ea219
from upstream. This fixes regression in some edge cases for mkv
playback.
BUG=26499283
Change-Id: I88de03219a3d941b6b2f251d384e29c36bdd4d9b
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int http_connect(http_subtransport *t)
{
int error;
char *proxy_url;
if (t->connected &&
http_should_keep_alive(&t->parser) &&
t->parse_finished)
return 0;
if (t->io) {
git_stream_close(t->io);
git_stream_free(t->io);
t->io = NULL;
t->connected = 0;
}
if (t->connection_data.use_ssl) {
error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
} else {
#ifdef GIT_CURL
error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#else
error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#endif
}
if (error < 0)
return error;
GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream");
if (git_stream_supports_proxy(t->io) &&
!git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url)) {
error = git_stream_set_proxy(t->io, proxy_url);
git__free(proxy_url);
if (error < 0)
return error;
}
error = git_stream_connect(t->io);
#if defined(GIT_OPENSSL) || defined(GIT_SECURE_TRANSPORT) || defined(GIT_CURL)
if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL &&
git_stream_is_encrypted(t->io)) {
git_cert *cert;
int is_valid;
if ((error = git_stream_certificate(&cert, t->io)) < 0)
return error;
giterr_clear();
is_valid = error != GIT_ECERTIFICATE;
error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload);
if (error < 0) {
if (!giterr_last())
giterr_set(GITERR_NET, "user cancelled certificate check");
return error;
}
}
#endif
if (error < 0)
return error;
t->connected = 1;
return 0;
}
Commit Message: http: check certificate validity before clobbering the error variable
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::string* GetTestingDMToken() {
static std::string dm_token;
return &dm_token;
}
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <[email protected]>
Reviewed-by: Tien Mai <[email protected]>
Reviewed-by: Daniel Rubery <[email protected]>
Cr-Commit-Position: refs/heads/master@{#714196}
CWE ID: CWE-20
Target: 1
Example 2:
Code: const char* menu_cache_item_get_file_basename( MenuCacheItem* item )
{
return item->file_name;
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add a few more confusability mapping entries
U+0153(œ) => ce
U+00E6(æ), U+04D5 (ӕ) => ae
U+0499(ҙ) => 3
U+0525(ԥ) => n
Bug: 835554, 826019, 836885
Test: components_unittests --gtest_filter=*IDN*
Change-Id: Ic89211f70359d3d67cc25c1805b426b72cdb16ae
Reviewed-on: https://chromium-review.googlesource.com/1055894
Commit-Queue: Jungshik Shin <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#558928}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void ssl_check_for_safari(SSL *s, const unsigned char *data,
const unsigned char *limit)
{
unsigned short type, size;
static const unsigned char kSafariExtensionsBlock[] = {
0x00, 0x0a, /* elliptic_curves extension */
0x00, 0x08, /* 8 bytes */
0x00, 0x06, /* 6 bytes of curve ids */
0x00, 0x17, /* P-256 */
0x00, 0x18, /* P-384 */
0x00, 0x19, /* P-521 */
0x00, 0x0b, /* ec_point_formats */
0x00, 0x02, /* 2 bytes */
0x01, /* 1 point format */
0x00, /* uncompressed */
};
/* The following is only present in TLS 1.2 */
static const unsigned char kSafariTLS12ExtensionsBlock[] = {
0x00, 0x0d, /* signature_algorithms */
0x00, 0x0c, /* 12 bytes */
0x00, 0x0a, /* 10 bytes */
0x05, 0x01, /* SHA-384/RSA */
0x04, 0x01, /* SHA-256/RSA */
0x02, 0x01, /* SHA-1/RSA */
0x04, 0x03, /* SHA-256/ECDSA */
0x02, 0x03, /* SHA-1/ECDSA */
};
if (data >= (limit - 2))
return;
data += 2;
if (data > (limit - 4))
return;
n2s(data, type);
n2s(data, size);
if (type != TLSEXT_TYPE_server_name)
return;
if (data + size > limit)
return;
data += size;
if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
const size_t len1 = sizeof(kSafariExtensionsBlock);
const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
if (data + len1 + len2 != limit)
return;
if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
return;
if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
return;
} else {
const size_t len = sizeof(kSafariExtensionsBlock);
if (data + len != limit)
return;
if (memcmp(data, kSafariExtensionsBlock, len) != 0)
return;
}
s->s3->is_probably_safari = 1;
}
Commit Message:
CWE ID: CWE-190
Target: 1
Example 2:
Code: LayoutUnit RenderFlexibleBox::marginBoxAscentForChild(RenderBox* child)
{
LayoutUnit ascent = child->firstLineBoxBaseline();
if (ascent == -1)
ascent = crossAxisExtentForChild(child);
return ascent + flowAwareMarginBeforeForChild(child);
}
Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1)
Previously StyleDifference was an enum that proximately bigger values
imply smaller values (e.g. StyleDifferenceLayout implies
StyleDifferenceRepaint). This causes unnecessary repaints in some cases
on layout change.
Convert StyleDifference to a structure containing relatively independent
flags.
This change doesn't directly improve the result, but can make further
repaint optimizations possible.
Step 1 doesn't change any functionality. RenderStyle still generate the
legacy StyleDifference enum when comparing styles and convert the result
to the new StyleDifference. Implicit requirements are not handled during
the conversion.
Converted call sites to use the new StyleDifference according to the
following conversion rules:
- diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange()
- diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly()
- diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout()
- diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout()
- diff > StyleDifferenceRepaintLayer => diff.needsLayout()
- diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly()
- diff == StyleDifferenceLayout => diff.needsFullLayout()
BUG=358460
TEST=All existing layout tests.
[email protected], [email protected], [email protected]
Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983
Review URL: https://codereview.chromium.org/236203020
git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void local_socket_close_locked(asocket* s) {
D("entered local_socket_close_locked. LS(%d) fd=%d", s->id, s->fd);
if (s->peer) {
D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
/* Note: it's important to call shutdown before disconnecting from
* the peer, this ensures that remote sockets can still get the id
* of the local socket they're connected to, to send a CLOSE()
* protocol event. */
if (s->peer->shutdown) {
s->peer->shutdown(s->peer);
}
s->peer->peer = 0;
if (s->peer->close == local_socket_close) {
local_socket_close_locked(s->peer);
} else {
s->peer->close(s->peer);
}
s->peer = 0;
}
/* If we are already closing, or if there are no
** pending packets, destroy immediately
*/
if (s->closing || s->has_write_error || s->pkt_first == NULL) {
int id = s->id;
local_socket_destroy(s);
D("LS(%d): closed", id);
return;
}
/* otherwise, put on the closing list
*/
D("LS(%d): closing", s->id);
s->closing = 1;
fdevent_del(&s->fde, FDE_READ);
remove_socket(s);
D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd);
insert_local_socket(s, &local_socket_closing_list);
CHECK_EQ(FDE_WRITE, s->fde.state & FDE_WRITE);
}
Commit Message: adb: switch the socket list mutex to a recursive_mutex.
sockets.cpp was branching on whether a socket close function was
local_socket_close in order to avoid a potential deadlock if the socket
list lock was held while closing a peer socket.
Bug: http://b/28347842
Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3
(cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa)
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int lxc_attach_drop_privs(struct lxc_proc_context_info *ctx)
{
int last_cap = lxc_caps_last_cap();
int cap;
for (cap = 0; cap <= last_cap; cap++) {
if (ctx->capability_mask & (1LL << cap))
continue;
if (prctl(PR_CAPBSET_DROP, cap, 0, 0, 0)) {
SYSERROR("failed to remove capability id %d", cap);
return -1;
}
}
return 0;
}
Commit Message: CVE-2015-1334: Don't use the container's /proc during attach
A user could otherwise over-mount /proc and prevent the apparmor profile
or selinux label from being written which combined with a modified
/bin/sh or other commonly used binary would lead to unconfined code
execution.
Reported-by: Roman Fiedler
Signed-off-by: Stéphane Graber <[email protected]>
CWE ID: CWE-17
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void rawsock_report_error(struct sock *sk, int err)
{
pr_debug("sk=%p err=%d\n", sk, err);
sk->sk_shutdown = SHUTDOWN_MASK;
sk->sk_err = -err;
sk->sk_error_report(sk);
rawsock_write_queue_purge(sk);
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long Track::ParseContentEncodingsEntry(long long start, long long size) {
IMkvReader* const pReader = m_pSegment->m_pReader;
assert(pReader);
long long pos = start;
const long long stop = start + size;
int count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x2240) // ContentEncoding ID
++count;
pos += size; //consume payload
assert(pos <= stop);
}
if (count <= 0)
return -1;
content_encoding_entries_ = new (std::nothrow) ContentEncoding*[count];
if (!content_encoding_entries_)
return -1;
content_encoding_entries_end_ = content_encoding_entries_;
pos = start;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x2240) { // ContentEncoding ID
ContentEncoding* const content_encoding =
new (std::nothrow) ContentEncoding();
if (!content_encoding)
return -1;
status = content_encoding->ParseContentEncodingEntry(pos,
size,
pReader);
if (status) {
delete content_encoding;
return status;
}
*content_encoding_entries_end_++ = content_encoding;
}
pos += size; //consume payload
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: 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
Target: 1
Example 2:
Code: SoftOpus::SoftOpus(
const char *name,
const OMX_CALLBACKTYPE *callbacks,
OMX_PTR appData,
OMX_COMPONENTTYPE **component)
: SimpleSoftOMXComponent(name, callbacks, appData, component),
mInputBufferCount(0),
mDecoder(NULL),
mHeader(NULL),
mCodecDelay(0),
mSeekPreRoll(0),
mAnchorTimeUs(0),
mNumFramesOutput(0),
mOutputPortSettingsChange(NONE) {
initPorts();
CHECK_EQ(initDecoder(), (status_t)OK);
}
Commit Message: DO NOT MERGE codecs: check OMX buffer size before use in (vorbis|opus)dec
Bug: 27833616
Change-Id: I1ccdd16a00741da072527a6d13e87fd7c7fe8c54
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Con_Dump_f (void)
{
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if (Cmd_Argc() != 2)
{
Com_Printf ("usage: condump <filename>\n");
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
f = FS_FOpenFileWrite( filename );
if (!f)
{
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
for (l = con.current - con.totallines + 1 ; l <= con.current ; l++)
{
line = con.text + (l%con.totallines)*con.linewidth;
for (x=0 ; x<con.linewidth ; x++)
if ((line[x] & 0xff) != ' ')
break;
if (x != con.linewidth)
break;
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++)
{
line = con.text + (l%con.totallines)*con.linewidth;
for(i=0; i<con.linewidth; i++)
buffer[i] = line[i] & 0xff;
for (x=con.linewidth-1 ; x>=0 ; x--)
{
if (buffer[x] == ' ')
buffer[x] = 0;
else
break;
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write(buffer, strlen(buffer), f);
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
Commit Message: Merge some file writing extension checks from OpenJK.
Thanks Ensiform.
https://github.com/JACoders/OpenJK/commit/05928a57f9e4aae15a3bd0
https://github.com/JACoders/OpenJK/commit/ef124fd0fc48af164581176
CWE ID: CWE-269
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param) {
case EQ_PARAM_CUR_PRESET:
preset = (int32_t)(*(uint16_t *)pValue);
if ((preset >= EqualizerGetNumPresets())||(preset < 0)) {
status = -EINVAL;
break;
}
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
if (band >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
EqualizerSetBandLevel(pContext, band, level);
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
if ((int)p[0] >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
if (p[0] >= 0) {
EqualizerSetPreset(pContext, (int)p[0]);
} else {
if ((int)p[1] != FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
}
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_setParameter */
Commit Message: Fix security vulnerability: Effect command might allow negative indexes
Bug: 32448258
Bug: 32095626
Test: Use POC bug or cts security test
Change-Id: I69f24eac5866f8d9090fc4c0ebe58c2c297b63df
(cherry picked from commit 01183402d757f0c28bfd5e3b127b3809dfd67459)
CWE ID: CWE-200
Target: 1
Example 2:
Code: const EVP_CIPHER *EVP_aes_256_wrap(void)
{
return &aes_256_wrap;
}
Commit Message: crypto/evp: harden AEAD ciphers.
Originally a crash in 32-bit build was reported CHACHA20-POLY1305
cipher. The crash is triggered by truncated packet and is result
of excessive hashing to the edge of accessible memory. Since hash
operation is read-only it is not considered to be exploitable
beyond a DoS condition. Other ciphers were hardened.
Thanks to Robert Święcki for report.
CVE-2017-3731
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_cipher rcipher;
snprintf(rcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "cipher");
rcipher.blocksize = alg->cra_blocksize;
rcipher.min_keysize = alg->cra_cipher.cia_min_keysize;
rcipher.max_keysize = alg->cra_cipher.cia_max_keysize;
if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER,
sizeof(struct crypto_report_cipher), &rcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool SessionService::CreateTabsAndWindows(
const std::vector<SessionCommand*>& data,
std::map<int, SessionTab*>* tabs,
std::map<int, SessionWindow*>* windows) {
for (std::vector<SessionCommand*>::const_iterator i = data.begin();
i != data.end(); ++i) {
const SessionCommand::id_type kCommandSetWindowBounds2 = 10;
const SessionCommand* command = *i;
switch (command->id()) {
case kCommandSetTabWindow: {
SessionID::id_type payload[2];
if (!command->GetPayload(payload, sizeof(payload)))
return true;
GetTab(payload[1], tabs)->window_id.set_id(payload[0]);
break;
}
case kCommandSetWindowBounds2: {
WindowBoundsPayload2 payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x,
payload.y,
payload.w,
payload.h);
GetWindow(payload.window_id, windows)->show_state =
payload.is_maximized ?
ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL;
break;
}
case kCommandSetWindowBounds3: {
WindowBoundsPayload3 payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x,
payload.y,
payload.w,
payload.h);
ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL;
if (payload.show_state > ui::SHOW_STATE_DEFAULT &&
payload.show_state < ui::SHOW_STATE_END &&
payload.show_state != ui::SHOW_STATE_INACTIVE) {
show_state = static_cast<ui::WindowShowState>(payload.show_state);
} else {
NOTREACHED();
}
GetWindow(payload.window_id, windows)->show_state = show_state;
break;
}
case kCommandSetTabIndexInWindow: {
TabIndexInWindowPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetTab(payload.id, tabs)->tab_visual_index = payload.index;
break;
}
case kCommandTabClosed:
case kCommandWindowClosed: {
ClosedPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
if (command->id() == kCommandTabClosed) {
delete GetTab(payload.id, tabs);
tabs->erase(payload.id);
} else {
delete GetWindow(payload.id, windows);
windows->erase(payload.id);
}
break;
}
case kCommandTabNavigationPathPrunedFromBack: {
TabNavigationPathPrunedFromBackPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
SessionTab* tab = GetTab(payload.id, tabs);
tab->navigations.erase(
FindClosestNavigationWithIndex(&(tab->navigations), payload.index),
tab->navigations.end());
break;
}
case kCommandTabNavigationPathPrunedFromFront: {
TabNavigationPathPrunedFromFrontPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)) ||
payload.index <= 0) {
return true;
}
SessionTab* tab = GetTab(payload.id, tabs);
tab->current_navigation_index =
std::max(-1, tab->current_navigation_index - payload.index);
for (std::vector<TabNavigation>::iterator i = tab->navigations.begin();
i != tab->navigations.end();) {
i->set_index(i->index() - payload.index);
if (i->index() < 0)
i = tab->navigations.erase(i);
else
++i;
}
break;
}
case kCommandUpdateTabNavigation: {
TabNavigation navigation;
SessionID::id_type tab_id;
if (!RestoreUpdateTabNavigationCommand(*command, &navigation, &tab_id))
return true;
SessionTab* tab = GetTab(tab_id, tabs);
std::vector<TabNavigation>::iterator i =
FindClosestNavigationWithIndex(&(tab->navigations),
navigation.index());
if (i != tab->navigations.end() && i->index() == navigation.index())
*i = navigation;
else
tab->navigations.insert(i, navigation);
break;
}
case kCommandSetSelectedNavigationIndex: {
SelectedNavigationIndexPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetTab(payload.id, tabs)->current_navigation_index = payload.index;
break;
}
case kCommandSetSelectedTabInIndex: {
SelectedTabInIndexPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetWindow(payload.id, windows)->selected_tab_index = payload.index;
break;
}
case kCommandSetWindowType: {
WindowTypePayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetWindow(payload.id, windows)->is_constrained = false;
GetWindow(payload.id, windows)->type =
BrowserTypeForWindowType(
static_cast<WindowType>(payload.index));
break;
}
case kCommandSetPinnedState: {
PinnedStatePayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetTab(payload.tab_id, tabs)->pinned = payload.pinned_state;
break;
}
case kCommandSetExtensionAppID: {
SessionID::id_type tab_id;
std::string extension_app_id;
if (!RestoreSetTabExtensionAppIDCommand(
*command, &tab_id, &extension_app_id)) {
return true;
}
GetTab(tab_id, tabs)->extension_app_id.swap(extension_app_id);
break;
}
default:
return true;
}
}
return true;
}
Commit Message: Metrics for measuring how much overhead reading compressed content states adds.
BUG=104293
TEST=NONE
Review URL: https://chromiumcodereview.appspot.com/9426039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@123733 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: xsltGetExtInfo(xsltStylesheetPtr style, const xmlChar * URI)
{
xsltExtDataPtr data;
/*
* TODO: Why do we have a return type of xmlHashTablePtr?
* Is the user-allocated data for extension modules expected
* to be a xmlHashTablePtr only? Or is this intended for
* the EXSLT module only?
*/
if (style != NULL && style->extInfos != NULL) {
data = xmlHashLookup(style->extInfos, URI);
if (data != NULL && data->extData != NULL)
return data->extData;
}
return NULL;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n");
if (!CDROM_CAN(CDC_SELECT_DISC))
return -ENOSYS;
if (arg != CDSL_CURRENT && arg != CDSL_NONE) {
if ((int)arg >= cdi->capacity)
return -EINVAL;
}
/*
* ->select_disc is a hook to allow a driver-specific way of
* seleting disc. However, since there is no equivalent hook for
* cdrom_slot_status this may not actually be useful...
*/
if (cdi->ops->select_disc)
return cdi->ops->select_disc(cdi, arg);
cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n");
return cdrom_select_disc(cdi, arg);
}
Commit Message: cdrom: fix improper type cast, which can leat to information leak.
There is another cast from unsigned long to int which causes
a bounds check to fail with specially crafted input. The value is
then used as an index in the slot array in cdrom_slot_status().
This issue is similar to CVE-2018-16658 and CVE-2018-10940.
Signed-off-by: Young_X <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void traverse_for_entities(
const char *old,
size_t oldlen,
char *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
size_t *retlen,
int all,
int flags,
const entity_ht *inv_map,
enum entity_charset charset)
{
const char *p,
*lim;
char *q;
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
lim = old + oldlen; /* terminator address */
assert(*lim == '\0');
for (p = old, q = ret; p < lim;) {
unsigned code, code2 = 0;
const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
/* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
* ASCII range byte can be part of a multi-byte sequence.
* However, they start at 0x40, therefore if we find a 0x26 byte,
* we're sure it represents the '&' character. */
/* assumes there are no single-char entities */
if (p[0] != '&' || (p + 3 >= lim)) {
*(q++) = *(p++);
continue;
}
/* now p[3] is surely valid and is no terminator */
/* numerical entity */
if (p[1] == '#') {
next = &p[2];
if (process_numeric_entity(&next, &code) == FAILURE)
goto invalid_code;
/* If we're in htmlspecialchars_decode, we're only decoding entities
* that represent &, <, >, " and '. Is this one of them? */
if (!all && (code > 63U ||
stage3_table_be_apos_00000[code].data.ent.entity == NULL))
goto invalid_code;
/* are we allowed to decode this entity in this document type?
* HTML 5 is the only that has a character that cannot be used in
* a numeric entity but is allowed literally (U+000D). The
* unoptimized version would be ... || !numeric_entity_is_allowed(code) */
if (!unicode_cp_is_allowed(code, doctype) ||
(doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
goto invalid_code;
} else {
const char *start;
size_t ent_len;
next = &p[1];
start = next;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto invalid_code;
if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
code = (unsigned) '\'';
} else {
goto invalid_code;
}
}
}
assert(*next == ';');
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
/* && code2 == '\0' always true for current maps */)
goto invalid_code;
/* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
* the call is needed to ensure the codepoint <= U+00FF) */
if (charset != cs_utf_8) {
/* replace unicode code point */
if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
goto invalid_code; /* not representable in target charset */
}
q += write_octet_sequence(q, charset, code);
if (code2) {
q += write_octet_sequence(q, charset, code2);
}
/* jump over the valid entity; may go beyond size of buffer; np */
p = next + 1;
continue;
invalid_code:
for (; p < next; p++) {
*(q++) = *p;
}
}
*q = '\0';
*retlen = (size_t)(q - ret);
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
Target: 1
Example 2:
Code: bool WebContentsImpl::IsAudioMuted() const {
if (base::FeatureList::IsEnabled(features::kAudioServiceAudioStreams)) {
return audio_stream_factory_ && audio_stream_factory_->IsMuted();
}
return audio_muter_.get() && audio_muter_->is_muting();
}
Commit Message: Prevent renderer initiated back navigation to cancel a browser one.
Renderer initiated back/forward navigations must not be able to cancel ongoing
browser initiated navigation if they are not user initiated.
Note: 'normal' renderer initiated navigation uses the
FrameHost::BeginNavigation() path. A code similar to this patch is done
in NavigatorImpl::OnBeginNavigation().
Test:
-----
Added: NavigationBrowserTest.
* HistoryBackInBeforeUnload
* HistoryBackInBeforeUnloadAfterSetTimeout
* HistoryBackCancelPendingNavigationNoUserGesture
* HistoryBackCancelPendingNavigationUserGesture
Fixed:
* (WPT) .../the-history-interface/traverse_the_history_2.html
* (WPT) .../the-history-interface/traverse_the_history_3.html
* (WPT) .../the-history-interface/traverse_the_history_4.html
* (WPT) .../the-history-interface/traverse_the_history_5.html
Bug: 879965
Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c
Reviewed-on: https://chromium-review.googlesource.com/1209744
Commit-Queue: Arthur Sonzogni <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Mustaq Ahmed <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#592823}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SPL_METHOD(SplFileObject, fgetcsv)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.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;
}
spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC);
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool net_tx_pkt_do_sw_fragmentation(struct NetTxPkt *pkt,
NetClientState *nc)
{
struct iovec fragment[NET_MAX_FRAG_SG_LIST];
size_t fragment_len = 0;
bool more_frags = false;
/* some pointers for shorter code */
void *l2_iov_base, *l3_iov_base;
size_t l2_iov_len, l3_iov_len;
int src_idx = NET_TX_PKT_PL_START_FRAG, dst_idx;
size_t src_offset = 0;
size_t fragment_offset = 0;
l2_iov_base = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base;
l2_iov_len = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len;
l3_iov_base = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base;
l3_iov_len = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len;
/* Copy headers */
fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_base = l2_iov_base;
fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_len = l2_iov_len;
fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_base = l3_iov_base;
fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_len = l3_iov_len;
/* Put as much data as possible and send */
do {
fragment_len = net_tx_pkt_fetch_fragment(pkt, &src_idx, &src_offset,
fragment, &dst_idx);
more_frags = (fragment_offset + fragment_len < pkt->payload_len);
eth_setup_ip4_fragmentation(l2_iov_base, l2_iov_len, l3_iov_base,
l3_iov_len, fragment_len, fragment_offset, more_frags);
eth_fix_ip4_checksum(l3_iov_base, l3_iov_len);
net_tx_pkt_sendv(pkt, nc, fragment, dst_idx);
fragment_offset += fragment_len;
} while (more_frags);
return true;
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: void TestTransactionConsumer::DidFinish(int result) {
state_ = DONE;
error_ = result;
if (--quit_counter_ == 0)
base::MessageLoop::current()->QuitWhenIdle();
}
Commit Message: Replace fixed string uses of AddHeaderFromString
Uses of AddHeaderFromString() with a static string may as well be
replaced with SetHeader(). Do so.
BUG=None
Review-Url: https://codereview.chromium.org/2236933005
Cr-Commit-Position: refs/heads/master@{#418161}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: sta_t *ieee80211_find_conn_for_aid(struct ar6_softc *ar, u8 aid)
{
sta_t *conn = NULL;
u8 ctr;
for (ctr = 0; ctr < AP_MAX_NUM_STA; ctr++) {
if (ar->sta_list[ctr].aid == aid) {
conn = &ar->sta_list[ctr];
break;
}
}
return conn;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const sp<IMediaPlayerService>& MediaMetadataRetriever::getService()
{
Mutex::Autolock lock(sServiceLock);
if (sService == 0) {
sp<IServiceManager> sm = defaultServiceManager();
sp<IBinder> binder;
do {
binder = sm->getService(String16("media.player"));
if (binder != 0) {
break;
}
ALOGW("MediaPlayerService not published, waiting...");
usleep(500000); // 0.5 s
} while (true);
if (sDeathNotifier == NULL) {
sDeathNotifier = new DeathNotifier();
}
binder->linkToDeath(sDeathNotifier);
sService = interface_cast<IMediaPlayerService>(binder);
}
ALOGE_IF(sService == 0, "no MediaPlayerService!?");
return sService;
}
Commit Message: Get service by value instead of reference
to prevent a cleared service binder from being used.
Bug: 26040840
Change-Id: Ifb5483c55b172d3553deb80dbe27f2204b86ecdb
CWE ID: CWE-119
Target: 1
Example 2:
Code: circuit_queue_streams_are_blocked(circuit_t *circ)
{
if (CIRCUIT_IS_ORIGIN(circ)) {
return circ->streams_blocked_on_n_chan;
} else {
return circ->streams_blocked_on_p_chan;
}
}
Commit Message: TROVE-2017-005: Fix assertion failure in connection_edge_process_relay_cell
On an hidden service rendezvous circuit, a BEGIN_DIR could be sent
(maliciously) which would trigger a tor_assert() because
connection_edge_process_relay_cell() thought that the circuit is an
or_circuit_t but is an origin circuit in reality.
Fixes #22494
Reported-by: Roger Dingledine <[email protected]>
Signed-off-by: David Goulet <[email protected]>
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
struct page *page, unsigned long address)
{
struct hstate *h = hstate_vma(vma);
struct vm_area_struct *iter_vma;
struct address_space *mapping;
struct prio_tree_iter iter;
pgoff_t pgoff;
/*
* vm_pgoff is in PAGE_SIZE units, hence the different calculation
* from page cache lookup which is in HPAGE_SIZE units.
*/
address = address & huge_page_mask(h);
pgoff = vma_hugecache_offset(h, vma, address);
mapping = (struct address_space *)page_private(page);
/*
* Take the mapping lock for the duration of the table walk. As
* this mapping should be shared between all the VMAs,
* __unmap_hugepage_range() is called as the lock is already held
*/
mutex_lock(&mapping->i_mmap_mutex);
vma_prio_tree_foreach(iter_vma, &iter, &mapping->i_mmap, pgoff, pgoff) {
/* Do not unmap the current VMA */
if (iter_vma == vma)
continue;
/*
* Unmap the page from other VMAs without their own reserves.
* They get marked to be SIGKILLed if they fault in these
* areas. This is because a future no-page fault on this VMA
* could insert a zeroed page instead of the data existing
* from the time of fork. This would look like data corruption
*/
if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
__unmap_hugepage_range(iter_vma,
address, address + huge_page_size(h),
page);
}
mutex_unlock(&mapping->i_mmap_mutex);
return 1;
}
Commit Message: hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <[email protected]>
Signed-off-by: David Gibson <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: Hillf Danton <[email protected]>
Cc: Paul Mackerras <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long long Chapters::Atom::GetTime(
const Chapters* pChapters,
long long timecode)
{
if (pChapters == NULL)
return -1;
Segment* const pSegment = pChapters->m_pSegment;
if (pSegment == NULL) // weird
return -1;
const SegmentInfo* const pInfo = pSegment->GetInfo();
if (pInfo == NULL)
return -1;
const long long timecode_scale = pInfo->GetTimeCodeScale();
if (timecode_scale < 1) // weird
return -1;
if (timecode < 0)
return -1;
const long long result = timecode_scale * timecode;
return result;
}
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
Target: 1
Example 2:
Code: xfs_attr_fillstate(xfs_da_state_t *state)
{
xfs_da_state_path_t *path;
xfs_da_state_blk_t *blk;
int level;
trace_xfs_attr_fillstate(state->args);
/*
* Roll down the "path" in the state structure, storing the on-disk
* block number for those buffers in the "path".
*/
path = &state->path;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->bp) {
blk->disk_blkno = XFS_BUF_ADDR(blk->bp);
blk->bp = NULL;
} else {
blk->disk_blkno = 0;
}
}
/*
* Roll down the "altpath" in the state structure, storing the on-disk
* block number for those buffers in the "altpath".
*/
path = &state->altpath;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->bp) {
blk->disk_blkno = XFS_BUF_ADDR(blk->bp);
blk->bp = NULL;
} else {
blk->disk_blkno = 0;
}
}
return(0);
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nfs41_free_stateid(struct nfs_server *server, struct nfs4_state *state)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_free_stateid(server, state),
&exception);
} while (exception.retry);
return err;
}
Commit Message: NFSv4: include bitmap in nfsv4 get acl data
The NFSv4 bitmap size is unbounded: a server can return an arbitrary
sized bitmap in an FATTR4_WORD0_ACL request. Replace using the
nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server
with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data
xdr length to the (cached) acl page data.
This is a general solution to commit e5012d1f "NFSv4.1: update
nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead
when getting ACLs.
Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr
was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.
Cc: [email protected]
Signed-off-by: Andy Adamson <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all)
{
char *str, *hint_charset = NULL;
int str_len, hint_charset_len = 0;
size_t new_len;
long flags = ENT_COMPAT;
char *replaced;
zend_bool double_encode = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!b", &str, &str_len, &flags, &hint_charset, &hint_charset_len, &double_encode) == FAILURE) {
return;
}
replaced = php_escape_html_entities_ex(str, str_len, &new_len, all, (int) flags, hint_charset, double_encode TSRMLS_CC);
RETVAL_STRINGL(replaced, (int)new_len, 0);
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
Target: 1
Example 2:
Code: void TabletModeWindowState::AttachState(
wm::WindowState* window_state,
wm::WindowState::State* previous_state) {
current_state_type_ = previous_state->GetType();
gfx::Rect restore_bounds = GetRestoreBounds(window_state);
if (!restore_bounds.IsEmpty()) {
SetWindowRestoreOverrides(window_state->window(), restore_bounds,
window_state->GetShowState());
}
if (current_state_type_ != WindowStateType::kMaximized &&
current_state_type_ != WindowStateType::kMinimized &&
current_state_type_ != WindowStateType::kFullscreen &&
current_state_type_ != WindowStateType::kPinned &&
current_state_type_ != WindowStateType::kTrustedPinned) {
UpdateWindow(window_state, state_type_on_attach_,
animate_bounds_on_attach_);
}
}
Commit Message: Fix the crash after clamshell -> tablet transition in overview mode.
This CL just reverted some changes that were made in
https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In
that CL, we changed the clamshell <-> tablet transition when clamshell
split view mode is enabled, however, we should keep the old behavior
unchanged if the feature is not enabled, i.e., overview should be ended
if it's active before the transition. Otherwise, it will cause a nullptr
dereference crash since |split_view_drag_indicators_| is not created in
clamshell overview and will be used in tablet overview.
Bug: 982507
Change-Id: I238fe9472648a446cff4ab992150658c228714dd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679306}
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: DWORD UnprivilegedProcessDelegate::GetExitCode() {
DCHECK(main_task_runner_->BelongsToCurrentThread());
DWORD exit_code = CONTROL_C_EXIT;
if (worker_process_.IsValid()) {
if (!::GetExitCodeProcess(worker_process_, &exit_code)) {
LOG_GETLASTERROR(INFO)
<< "Failed to query the exit code of the worker process";
exit_code = CONTROL_C_EXIT;
}
}
return exit_code;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: hstore_from_array(PG_FUNCTION_ARGS)
{
ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
int ndims = ARR_NDIM(in_array);
int count;
int32 buflen;
HStore *out;
Pairs *pairs;
Datum *in_datums;
bool *in_nulls;
int in_count;
int i;
Assert(ARR_ELEMTYPE(in_array) == TEXTOID);
switch (ndims)
{
case 0:
out = hstorePairs(NULL, 0, 0);
PG_RETURN_POINTER(out);
case 1:
if ((ARR_DIMS(in_array)[0]) % 2)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("array must have even number of elements")));
break;
case 2:
if ((ARR_DIMS(in_array)[1]) != 2)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("array must have two columns")));
break;
default:
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
}
deconstruct_array(in_array,
TEXTOID, -1, false, 'i',
&in_datums, &in_nulls, &in_count);
count = in_count / 2;
pairs = palloc(count * sizeof(Pairs));
for (i = 0; i < count; ++i)
{
if (in_nulls[i * 2])
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null value not allowed for hstore key")));
if (in_nulls[i * 2 + 1])
{
pairs[i].key = VARDATA_ANY(in_datums[i * 2]);
pairs[i].val = NULL;
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));
pairs[i].vallen = 4;
pairs[i].isnull = true;
pairs[i].needfree = false;
}
else
{
pairs[i].key = VARDATA_ANY(in_datums[i * 2]);
pairs[i].val = VARDATA_ANY(in_datums[i * 2 + 1]);
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));
pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1]));
pairs[i].isnull = false;
pairs[i].needfree = false;
}
}
count = hstoreUniquePairs(pairs, count, &buflen);
out = hstorePairs(pairs, count, buflen);
PG_RETURN_POINTER(out);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void SetImpl(Handle<JSObject> holder, uint32_t entry, Object* value) {
uint32_t length = static_cast<uint32_t>(GetString(*holder)->length());
if (entry < length) {
return; // String contents are read-only.
}
BackingStoreAccessor::SetImpl(holder->elements(), entry - length, value);
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int itacns_add_data_files(sc_pkcs15_card_t *p15card)
{
const size_t array_size =
sizeof(itacns_data_files)/sizeof(itacns_data_files[0]);
unsigned int i;
int rv;
sc_pkcs15_data_t *p15_personaldata = NULL;
sc_pkcs15_data_info_t dinfo;
struct sc_pkcs15_object *objs[32];
struct sc_pkcs15_data_info *cinfo;
for(i=0; i < array_size; i++) {
sc_path_t path;
sc_pkcs15_data_info_t data;
sc_pkcs15_object_t obj;
if (itacns_data_files[i].cie_only &&
p15card->card->type != SC_CARD_TYPE_ITACNS_CIE_V2)
continue;
sc_format_path(itacns_data_files[i].path, &path);
memset(&data, 0, sizeof(data));
memset(&obj, 0, sizeof(obj));
strlcpy(data.app_label, itacns_data_files[i].label,
sizeof(data.app_label));
strlcpy(obj.label, itacns_data_files[i].label,
sizeof(obj.label));
data.path = path;
rv = sc_pkcs15emu_add_data_object(p15card, &obj, &data);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, rv,
"Could not add data file");
}
/*
* If we got this far, we can read the Personal Data file and glean
* the user's full name. Thus we can use it to put together a
* user-friendlier card name.
*/
memset(&dinfo, 0, sizeof(dinfo));
strcpy(dinfo.app_label, "EF_DatiPersonali");
/* Find EF_DatiPersonali */
rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT,
objs, 32);
if(rv < 0) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Data enumeration failed");
return SC_SUCCESS;
}
for(i=0; i<32; i++) {
cinfo = (struct sc_pkcs15_data_info *) objs[i]->data;
if(!strcmp("EF_DatiPersonali", objs[i]->label))
break;
}
if(i>=32) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not find EF_DatiPersonali: "
"keeping generic card name");
return SC_SUCCESS;
}
rv = sc_pkcs15_read_data_object(p15card, cinfo, &p15_personaldata);
if (rv) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not read EF_DatiPersonali: "
"keeping generic card name");
}
{
char fullname[160];
if(get_name_from_EF_DatiPersonali(p15_personaldata->data,
fullname, sizeof(fullname))) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not parse EF_DatiPersonali: "
"keeping generic card name");
sc_pkcs15_free_data_object(p15_personaldata);
return SC_SUCCESS;
}
set_string(&p15card->tokeninfo->label, fullname);
}
sc_pkcs15_free_data_object(p15_personaldata);
return SC_SUCCESS;
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr,
const u_char **pktdata, const char *funcname,
const int line, const char *file)
{
int res = pcap_next_ex(pcap, pkthdr, pktdata);
if (*pktdata && *pkthdr) {
if ((*pkthdr)->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, (*pkthdr)->len, MAXPACKET);
exit(-1);
}
if ((*pkthdr)->len < (*pkthdr)->caplen) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n",
file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen);
exit(-1);
}
}
return res;
}
Commit Message: Bug #520 Fix heap overflow on zero or 0xFFFF packet length
Add check for packets that report zero packet length. Example
of fix:
src/tcpprep --auto=bridge --pcap=poc16-get_l2len-heapoverflow --cachefile=/dev/null
Warning: poc16-get_l2len-heapoverflow was captured using a snaplen of 17 bytes. This may mean you have truncated packets.
safe_pcap_next ERROR: Invalid packet length in tcpprep.c:process_raw_packets() line 334: packet length=0 capture length=0
CWE ID: CWE-125
Target: 1
Example 2:
Code: void WebMediaPlayerImpl::ExitPictureInPicture(
blink::WebMediaPlayer::PipWindowClosedCallback callback) {
delegate_->DidPictureInPictureModeEnd(delegate_id_, std::move(callback));
OnPictureInPictureModeEnded();
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GestureProviderAura::OnTouchEventAck(bool event_consumed) {
DCHECK(pending_gestures_.empty());
DCHECK(!handling_event_);
base::AutoReset<bool> handling_event(&handling_event_, true);
filtered_gesture_provider_.OnTouchEventAck(event_consumed);
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(snmp, __construct)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1, *a2;
int a1_len, a2_len;
long timeout = SNMP_DEFAULT_TIMEOUT;
long retries = SNMP_DEFAULT_RETRIES;
long version = SNMP_DEFAULT_VERSION;
int argc = ZEND_NUM_ARGS();
zend_error_handling error_handling;
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
switch(version) {
case SNMP_VERSION_1:
case SNMP_VERSION_2c:
case SNMP_VERSION_3:
break;
default:
zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC);
return;
}
/* handle re-open of snmp session */
if (snmp_object->session) {
netsnmp_session_free(&(snmp_object->session));
}
if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) {
return;
}
snmp_object->max_oids = 0;
snmp_object->valueretrieval = SNMP_G(valueretrieval);
snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
snmp_object->oid_increasing_check = TRUE;
snmp_object->exceptions_enabled = 0;
}
Commit Message:
CWE ID: CWE-416
Target: 1
Example 2:
Code: DOMHighResTimeStamp PerformanceNavigationTiming::unloadEventEnd() const {
bool allow_redirect_details = GetAllowRedirectDetails();
DocumentLoadTiming* timing = GetDocumentLoadTiming();
if (!allow_redirect_details || !timing ||
!timing->HasSameOriginAsPreviousDocument())
return 0;
return Performance::MonotonicTimeToDOMHighResTimeStamp(
TimeOrigin(), timing->UnloadEventEnd(), false /* allow_negative_value */);
}
Commit Message: Fix the |name| of PerformanceNavigationTiming
Previously, the |name| of a PerformanceNavigationTiming entry was the initial
URL (the request URL). After this CL, it is the response URL, so for example
a url of the form 'redirect?location=newLoc' will have 'newLoc' as the |name|.
Bug: 797465
Change-Id: Icab53ad8027d066422562c82bcf0354c264fea40
Reviewed-on: https://chromium-review.googlesource.com/996579
Reviewed-by: Yoav Weiss <[email protected]>
Commit-Queue: Nicolás Peña Moreno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548773}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
bool check_fullscreen) const {
bool hide_ui_for_fullscreen = false;
#if !defined(OS_MACOSX)
hide_ui_for_fullscreen = check_fullscreen && window_ &&
window_->IsFullscreen();
#endif
unsigned int features = FEATURE_INFOBAR | FEATURE_SIDEBAR;
#if !defined(OS_CHROMEOS)
features |= FEATURE_DOWNLOADSHELF;
#endif // !defined(OS_CHROMEOS)
if (is_type_tabbed())
features |= FEATURE_BOOKMARKBAR;
if (!hide_ui_for_fullscreen) {
if (!is_type_tabbed())
features |= FEATURE_TITLEBAR;
if (is_type_tabbed())
features |= FEATURE_TABSTRIP;
if (is_type_tabbed())
features |= FEATURE_TOOLBAR;
if (!is_app())
features |= FEATURE_LOCATIONBAR;
}
return !!(features & feature);
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int key_notify_policy_flush(const struct km_event *c)
{
struct sk_buff *skb_out;
struct sadb_msg *hdr;
skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb_out)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
hdr->sadb_msg_type = SADB_X_SPDFLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
Commit Message: af_key: initialize satype in key_notify_policy_flush()
This field was left uninitialized. Some user daemons perform check against this
field.
Signed-off-by: Nicolas Dichtel <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: int valid_swaphandles(swp_entry_t entry, unsigned long *offset)
{
struct swap_info_struct *si;
int our_page_cluster = page_cluster;
pgoff_t target, toff;
pgoff_t base, end;
int nr_pages = 0;
if (!our_page_cluster) /* no readahead */
return 0;
si = swap_info[swp_type(entry)];
target = swp_offset(entry);
base = (target >> our_page_cluster) << our_page_cluster;
end = base + (1 << our_page_cluster);
if (!base) /* first page is swap header */
base++;
spin_lock(&swap_lock);
if (end > si->max) /* don't go beyond end of map */
end = si->max;
/* Count contiguous allocated slots above our target */
for (toff = target; ++toff < end; nr_pages++) {
/* Don't read in free or bad pages */
if (!si->swap_map[toff])
break;
if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
break;
}
/* Count contiguous allocated slots below our target */
for (toff = target; --toff >= base; nr_pages++) {
/* Don't read in free or bad pages */
if (!si->swap_map[toff])
break;
if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
break;
}
spin_unlock(&swap_lock);
/*
* Indicate starting offset, and return number of pages to get:
* if only 1, say 0, since there's then no readahead to be done.
*/
*offset = ++toff;
return nr_pages? ++nr_pages: 0;
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static u64 __skb_get_nlattr_nest(u64 ctx, u64 A, u64 X, u64 r4, u64 r5)
{
struct sk_buff *skb = (struct sk_buff *)(long) ctx;
struct nlattr *nla;
if (skb_is_nonlinear(skb))
return 0;
if (A > skb->len - sizeof(struct nlattr))
return 0;
nla = (struct nlattr *) &skb->data[A];
if (nla->nla_len > A - skb->len)
return 0;
nla = nla_find_nested(nla, X);
if (nla)
return (void *) nla - (void *) skb->data;
return 0;
}
Commit Message: filter: prevent nla extensions to peek beyond the end of the message
The BPF_S_ANC_NLATTR and BPF_S_ANC_NLATTR_NEST extensions fail to check
for a minimal message length before testing the supplied offset to be
within the bounds of the message. This allows the subtraction of the nla
header to underflow and therefore -- as the data type is unsigned --
allowing far to big offset and length values for the search of the
netlink attribute.
The remainder calculation for the BPF_S_ANC_NLATTR_NEST extension is
also wrong. It has the minuend and subtrahend mixed up, therefore
calculates a huge length value, allowing to overrun the end of the
message while looking for the netlink attribute.
The following three BPF snippets will trigger the bugs when attached to
a UNIX datagram socket and parsing a message with length 1, 2 or 3.
,-[ PoC for missing size check in BPF_S_ANC_NLATTR ]--
| ld #0x87654321
| ldx #42
| ld #nla
| ret a
`---
,-[ PoC for the same bug in BPF_S_ANC_NLATTR_NEST ]--
| ld #0x87654321
| ldx #42
| ld #nlan
| ret a
`---
,-[ PoC for wrong remainder calculation in BPF_S_ANC_NLATTR_NEST ]--
| ; (needs a fake netlink header at offset 0)
| ld #0
| ldx #42
| ld #nlan
| ret a
`---
Fix the first issue by ensuring the message length fulfills the minimal
size constrains of a nla header. Fix the second bug by getting the math
for the remainder calculation right.
Fixes: 4738c1db15 ("[SKFILTER]: Add SKF_ADF_NLATTR instruction")
Fixes: d214c7537b ("filter: add SKF_AD_NLATTR_NEST to look for nested..")
Cc: Patrick McHardy <[email protected]>
Cc: Pablo Neira Ayuso <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int omx_venc::async_message_process (void *context, void* message)
{
omx_video* omx = NULL;
struct venc_msg *m_sVenc_msg = NULL;
OMX_BUFFERHEADERTYPE* omxhdr = NULL;
struct venc_buffer *temp_buff = NULL;
if (context == NULL || message == NULL) {
DEBUG_PRINT_ERROR("ERROR: omx_venc::async_message_process invalid i/p params");
return -1;
}
m_sVenc_msg = (struct venc_msg *)message;
omx = reinterpret_cast<omx_video*>(context);
if (m_sVenc_msg->statuscode != VEN_S_SUCCESS) {
DEBUG_PRINT_ERROR("ERROR: async_msg_process() - Error statuscode = %lu",
m_sVenc_msg->statuscode);
if(m_sVenc_msg->msgcode == VEN_MSG_HW_OVERLOAD) {
omx->omx_report_hw_overload();
} else
omx->omx_report_error();
}
DEBUG_PRINT_LOW("omx_venc::async_message_process- msgcode = %lu",
m_sVenc_msg->msgcode);
switch (m_sVenc_msg->msgcode) {
case VEN_MSG_START:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_START_DONE);
break;
case VEN_MSG_STOP:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_STOP_DONE);
break;
case VEN_MSG_RESUME:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_RESUME_DONE);
break;
case VEN_MSG_PAUSE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_PAUSE_DONE);
break;
case VEN_MSG_FLUSH_INPUT_DONE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_EVENT_INPUT_FLUSH);
break;
case VEN_MSG_FLUSH_OUPUT_DONE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_EVENT_OUTPUT_FLUSH);
break;
case VEN_MSG_INPUT_BUFFER_DONE:
omxhdr = (OMX_BUFFERHEADERTYPE* )\
m_sVenc_msg->buf.clientdata;
if (omxhdr == NULL ||
(((OMX_U32)(omxhdr - omx->m_inp_mem_ptr) > omx->m_sInPortDef.nBufferCountActual) &&
((OMX_U32)(omxhdr - omx->meta_buffer_hdr) > omx->m_sInPortDef.nBufferCountActual))) {
omxhdr = NULL;
m_sVenc_msg->statuscode = VEN_S_EFAIL;
}
#ifdef _ANDROID_ICS_
omx->omx_release_meta_buffer(omxhdr);
#endif
omx->post_event ((unsigned long)omxhdr,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_EBD);
break;
case VEN_MSG_OUTPUT_BUFFER_DONE:
omxhdr = (OMX_BUFFERHEADERTYPE*)m_sVenc_msg->buf.clientdata;
if ( (omxhdr != NULL) &&
((OMX_U32)(omxhdr - omx->m_out_mem_ptr) < omx->m_sOutPortDef.nBufferCountActual)) {
if (m_sVenc_msg->buf.len <= omxhdr->nAllocLen) {
omxhdr->nFilledLen = m_sVenc_msg->buf.len;
omxhdr->nOffset = m_sVenc_msg->buf.offset;
omxhdr->nTimeStamp = m_sVenc_msg->buf.timestamp;
DEBUG_PRINT_LOW("o/p TS = %u", (unsigned int)m_sVenc_msg->buf.timestamp);
omxhdr->nFlags = m_sVenc_msg->buf.flags;
/*Use buffer case*/
if (omx->output_use_buffer && !omx->m_use_output_pmem) {
DEBUG_PRINT_LOW("memcpy() for o/p Heap UseBuffer");
memcpy(omxhdr->pBuffer,
(m_sVenc_msg->buf.ptrbuffer),
m_sVenc_msg->buf.len);
}
} else {
omxhdr->nFilledLen = 0;
}
} else {
omxhdr = NULL;
m_sVenc_msg->statuscode = VEN_S_EFAIL;
}
omx->post_event ((unsigned long)omxhdr,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_FBD);
break;
case VEN_MSG_NEED_OUTPUT_BUFFER:
break;
#ifndef _MSM8974_
case VEN_MSG_LTRUSE_FAILED:
DEBUG_PRINT_ERROR("LTRUSE Failed!");
omx->post_event (NULL,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_LTRUSE_FAILED);
break;
#endif
default:
DEBUG_PRINT_HIGH("Unknown msg received : %lu", m_sVenc_msg->msgcode);
break;
}
return 0;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200
Target: 1
Example 2:
Code: INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K
int d = ((buf[0] & 0x30) >> 3) + 24;
int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30);
op->val = k;
ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr)
ESIL_A ("r%d,0x80,&,!,!," // V
"0,RPICK,0x8000,&,!,"
"&,vf,=,", d + 1);
ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("r%d,0x80,&,!," // C
"0,RPICK,0x8000,&,!,!,"
"&,cf,=,", d + 1);
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result
}
Commit Message: Fix #9943 - Invalid free on RAnal.avr
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void toggle_fpga_eeprom_bus(bool cpu_own)
{
qrio_gpio_direction_output(GPIO_A, PROM_SEL_L, !cpu_own);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void Sp_replace_regexp(js_State *J)
{
js_Regexp *re;
const char *source, *s, *r;
js_Buffer *sb = NULL;
int n, x;
Resub m;
source = checkstring(J, 0);
re = js_toregexp(J, 1);
if (js_regexec(re->prog, source, &m, 0)) {
js_copy(J, 0);
return;
}
re->last = 0;
loop:
s = m.sub[0].sp;
n = m.sub[0].ep - m.sub[0].sp;
if (js_iscallable(J, 2)) {
js_copy(J, 2);
js_pushundefined(J);
for (x = 0; m.sub[x].sp; ++x) /* arg 0..x: substring and subexps that matched */
js_pushlstring(J, m.sub[x].sp, m.sub[x].ep - m.sub[x].sp);
js_pushnumber(J, s - source); /* arg x+2: offset within search string */
js_copy(J, 0); /* arg x+3: search string */
js_call(J, 2 + x);
r = js_tostring(J, -1);
js_putm(J, &sb, source, s);
js_puts(J, &sb, r);
js_pop(J, 1);
} else {
r = js_tostring(J, 2);
js_putm(J, &sb, source, s);
while (*r) {
if (*r == '$') {
switch (*(++r)) {
case 0: --r; /* end of string; back up */
/* fallthrough */
case '$': js_putc(J, &sb, '$'); break;
case '`': js_putm(J, &sb, source, s); break;
case '\'': js_puts(J, &sb, s + n); break;
case '&':
js_putm(J, &sb, s, s + n);
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
x = *r - '0';
if (r[1] >= '0' && r[1] <= '9')
x = x * 10 + *(++r) - '0';
if (x > 0 && x < m.nsub) {
js_putm(J, &sb, m.sub[x].sp, m.sub[x].ep);
} else {
js_putc(J, &sb, '$');
if (x > 10) {
js_putc(J, &sb, '0' + x / 10);
js_putc(J, &sb, '0' + x % 10);
} else {
js_putc(J, &sb, '0' + x);
}
}
break;
default:
js_putc(J, &sb, '$');
js_putc(J, &sb, *r);
break;
}
++r;
} else {
js_putc(J, &sb, *r++);
}
}
}
if (re->flags & JS_REGEXP_G) {
source = m.sub[0].ep;
if (n == 0) {
if (*source)
js_putc(J, &sb, *source++);
else
goto end;
}
if (!js_regexec(re->prog, source, &m, REG_NOTBOL))
goto loop;
}
end:
js_puts(J, &sb, s + n);
js_putc(J, &sb, 0);
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
js_pushstring(J, sb ? sb->s : "");
js_endtry(J);
js_free(J, sb);
}
Commit Message: Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.
CWE ID: CWE-400
Target: 1
Example 2:
Code: RunLengthStream::RunLengthStream(Stream *strA):
FilterStream(strA) {
bufPtr = bufEnd = buf;
eof = gFalse;
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void fake_update_pmtu(struct dst_entry *dst, u32 mtu)
{
}
Commit Message: bridge: reset IPCB in br_parse_ip_options
Commit 462fb2af9788a82 (bridge : Sanitize skb before it enters the IP
stack), missed one IPCB init before calling ip_options_compile()
Thanks to Scot Doyle for his tests and bug reports.
Reported-by: Scot Doyle <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Hiroaki SHIMODA <[email protected]>
Acked-by: Bandan Das <[email protected]>
Acked-by: Stephen Hemminger <[email protected]>
Cc: Jan Lübbe <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp,
(ep < ep2) ? ep : ep2, map, nmap);
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking.
Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds
checking, and return null on a bounds overflow. Have their callers
check for a null return.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125
Target: 1
Example 2:
Code: void GLES2Implementation::SetColorSpaceMetadataCHROMIUM(
GLuint texture_id,
GLColorSpace color_space) {
#if defined(__native_client__)
SetGLError(GL_INVALID_VALUE, "GLES2::SetColorSpaceMetadataCHROMIUM",
"not supported");
#else
gfx::ColorSpace* gfx_color_space =
reinterpret_cast<gfx::ColorSpace*>(color_space);
base::Pickle color_space_data;
IPC::ParamTraits<gfx::ColorSpace>::Write(&color_space_data, *gfx_color_space);
ScopedTransferBufferPtr buffer(color_space_data.size(), helper_,
transfer_buffer_);
if (!buffer.valid() || buffer.size() < color_space_data.size()) {
SetGLError(GL_OUT_OF_MEMORY, "GLES2::SetColorSpaceMetadataCHROMIUM",
"out of memory");
return;
}
memcpy(buffer.address(), color_space_data.data(), color_space_data.size());
helper_->SetColorSpaceMetadataCHROMIUM(
texture_id, buffer.shm_id(), buffer.offset(), color_space_data.size());
#endif
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int git_index_set_caps(git_index *index, int caps)
{
unsigned int old_ignore_case;
assert(index);
old_ignore_case = index->ignore_case;
if (caps == GIT_INDEXCAP_FROM_OWNER) {
git_repository *repo = INDEX_OWNER(index);
int val;
if (!repo)
return create_index_error(
-1, "cannot access repository to set index caps");
if (!git_repository__cvar(&val, repo, GIT_CVAR_IGNORECASE))
index->ignore_case = (val != 0);
if (!git_repository__cvar(&val, repo, GIT_CVAR_FILEMODE))
index->distrust_filemode = (val == 0);
if (!git_repository__cvar(&val, repo, GIT_CVAR_SYMLINKS))
index->no_symlinks = (val == 0);
}
else {
index->ignore_case = ((caps & GIT_INDEXCAP_IGNORE_CASE) != 0);
index->distrust_filemode = ((caps & GIT_INDEXCAP_NO_FILEMODE) != 0);
index->no_symlinks = ((caps & GIT_INDEXCAP_NO_SYMLINKS) != 0);
}
if (old_ignore_case != index->ignore_case) {
git_index__set_ignore_case(index, (bool)index->ignore_case);
}
return 0;
}
Commit Message: index: convert `read_entry` to return entry size via an out-param
The function `read_entry` does not conform to our usual coding style of
returning stuff via the out parameter and to use the return value for
reporting errors. Due to most of our code conforming to that pattern, it
has become quite natural for us to actually return `-1` in case there is
any error, which has also slipped in with commit 5625d86b9 (index:
support index v4, 2016-05-17). As the function returns an `size_t` only,
though, the return value is wrapped around, causing the caller of
`read_tree` to continue with an invalid index entry. Ultimately, this
can lead to a double-free.
Improve code and fix the bug by converting the function to return the
index entry size via an out parameter and only using the return value to
indicate errors.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>
CWE ID: CWE-415
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebContentsImpl::CreateNewWindow(
RenderFrameHost* opener,
int32_t render_view_route_id,
int32_t main_frame_route_id,
int32_t main_frame_widget_route_id,
const mojom::CreateNewWindowParams& params,
SessionStorageNamespace* session_storage_namespace) {
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_route_id == MSG_ROUTING_NONE));
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_widget_route_id == MSG_ROUTING_NONE));
DCHECK(opener);
int render_process_id = opener->GetProcess()->GetID();
SiteInstance* source_site_instance = opener->GetSiteInstance();
DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id));
bool is_guest = BrowserPluginGuest::IsGuest(this);
DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE);
scoped_refptr<SiteInstance> site_instance =
params.opener_suppressed && !is_guest
? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
: source_site_instance;
const std::string& partition_id =
GetContentClient()->browser()->
GetStoragePartitionIdForSite(GetBrowserContext(),
site_instance->GetSiteURL());
StoragePartition* partition = BrowserContext::GetStoragePartition(
GetBrowserContext(), site_instance.get());
DOMStorageContextWrapper* dom_storage_context =
static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
SessionStorageNamespaceImpl* session_storage_namespace_impl =
static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
if (delegate_ &&
!delegate_->ShouldCreateWebContents(
this, opener, source_site_instance, render_view_route_id,
main_frame_route_id, main_frame_widget_route_id,
params.window_container_type, opener->GetLastCommittedURL(),
params.frame_name, params.target_url, partition_id,
session_storage_namespace)) {
RenderFrameHostImpl* rfh =
RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id);
if (rfh) {
DCHECK(rfh->IsRenderFrameLive());
rfh->Init();
}
return;
}
CreateParams create_params(GetBrowserContext(), site_instance.get());
create_params.routing_id = render_view_route_id;
create_params.main_frame_routing_id = main_frame_route_id;
create_params.main_frame_widget_routing_id = main_frame_widget_route_id;
create_params.main_frame_name = params.frame_name;
create_params.opener_render_process_id = render_process_id;
create_params.opener_render_frame_id = opener->GetRoutingID();
create_params.opener_suppressed = params.opener_suppressed;
if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB)
create_params.initially_hidden = true;
create_params.renderer_initiated_creation =
main_frame_route_id != MSG_ROUTING_NONE;
WebContentsImpl* new_contents = NULL;
if (!is_guest) {
create_params.context = view_->GetNativeView();
create_params.initial_size = GetContainerBounds().size();
new_contents = static_cast<WebContentsImpl*>(
WebContents::Create(create_params));
} else {
new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
}
new_contents->GetController().SetSessionStorageNamespace(
partition_id,
session_storage_namespace);
if (!params.frame_name.empty())
new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
if (!params.opener_suppressed) {
if (!is_guest) {
WebContentsView* new_view = new_contents->view_.get();
new_view->CreateViewForWidget(
new_contents->GetRenderViewHost()->GetWidget(), false);
}
DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id);
pending_contents_[std::make_pair(
render_process_id, main_frame_widget_route_id)] = new_contents;
AddDestructionObserver(new_contents);
}
if (delegate_) {
delegate_->WebContentsCreated(this, render_process_id,
opener->GetRoutingID(), params.frame_name,
params.target_url, new_contents);
}
if (opener) {
for (auto& observer : observers_) {
observer.DidOpenRequestedURL(new_contents, opener, params.target_url,
params.referrer, params.disposition,
ui::PAGE_TRANSITION_LINK,
false, // started_from_context_menu
true); // renderer_initiated
}
}
if (params.opener_suppressed) {
bool was_blocked = false;
if (delegate_) {
gfx::Rect initial_rect;
base::WeakPtr<WebContentsImpl> weak_new_contents =
new_contents->weak_factory_.GetWeakPtr();
delegate_->AddNewContents(
this, new_contents, params.disposition, initial_rect,
params.user_gesture, &was_blocked);
if (!weak_new_contents)
return; // The delegate deleted |new_contents| during AddNewContents().
}
if (!was_blocked) {
OpenURLParams open_params(params.target_url, params.referrer,
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_LINK,
true /* is_renderer_initiated */);
open_params.user_gesture = params.user_gesture;
if (delegate_ && !is_guest &&
!delegate_->ShouldResumeRequestsForCreatedWindow()) {
new_contents->delayed_open_url_params_.reset(
new OpenURLParams(open_params));
} else {
new_contents->OpenURL(open_params);
}
}
}
}
Commit Message: If a page shows a popup, end fullscreen.
This was implemented in Blink r159834, but it is susceptible
to a popup/fullscreen race. This CL reverts that implementation
and re-implements it in WebContents.
BUG=752003
TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen
Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f
Reviewed-on: https://chromium-review.googlesource.com/606987
Commit-Queue: Avi Drissman <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498171}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void print_pem_cert(FILE *out, certificate_t *cert)
{
chunk_t encoded;
if (cert->get_encoding(cert, CERT_PEM, &encoded))
{
fprintf(out, "%.*s", (int)encoded.len, encoded.ptr);
free(encoded.ptr);
}
}
Commit Message:
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: OMX_ERRORTYPE SoftVorbis::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.vorbis",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioVorbis:
{
const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(const OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: setup_server_realm(krb5_principal sprinc)
{
krb5_error_code kret;
kdc_realm_t *newrealm;
kret = 0;
if (kdc_numrealms > 1) {
if (!(newrealm = find_realm_data(sprinc->realm.data,
(krb5_ui_4) sprinc->realm.length)))
kret = ENOENT;
else
kdc_active_realm = newrealm;
}
else
kdc_active_realm = kdc_realmlist[0];
return(kret);
}
Commit Message: Multi-realm KDC null deref [CVE-2013-1418]
If a KDC serves multiple realms, certain requests can cause
setup_server_realm() to dereference a null pointer, crashing the KDC.
CVSSv2: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C
A related but more minor vulnerability requires authentication to
exploit, and is only present if a third-party KDC database module can
dereference a null pointer under certain conditions.
(back ported from commit 5d2d9a1abe46a2c1a8614d4672d08d9d30a5f8bf)
ticket: 7757 (new)
version_fixed: 1.10.7
status: resolved
CWE ID:
Target: 1
Example 2:
Code: static void sysbus_ahci_realize(DeviceState *dev, Error **errp)
{
SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
SysbusAHCIState *s = SYSBUS_AHCI(dev);
ahci_init(&s->ahci, dev, &address_space_memory, s->num_ports);
sysbus_init_mmio(sbd, &s->ahci.mem);
sysbus_init_irq(sbd, &s->ahci.irq);
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t *p_header_size)
{
Jbig2Segment *result;
uint8_t rtscarf;
uint32_t rtscarf_long;
uint32_t *referred_to_segments;
int referred_to_segment_count;
int referred_to_segment_size;
int pa_size;
int offset;
/* minimum possible size of a jbig2 segment header */
if (buf_size < 11)
return NULL;
result = jbig2_new(ctx, Jbig2Segment, 1);
if (result == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate segment in jbig2_parse_segment_header");
return result;
}
/* 7.2.2 */
result->number = jbig2_get_uint32(buf);
/* 7.2.3 */
result->flags = buf[4];
/* 7.2.4 referred-to segments */
rtscarf = buf[5];
if ((rtscarf & 0xe0) == 0xe0) {
rtscarf_long = jbig2_get_uint32(buf + 5);
referred_to_segment_count = rtscarf_long & 0x1fffffff;
offset = 5 + 4 + (referred_to_segment_count + 1) / 8;
} else {
referred_to_segment_count = (rtscarf >> 5);
offset = 5 + 1;
}
result->referred_to_segment_count = referred_to_segment_count;
/* we now have enough information to compute the full header length */
referred_to_segment_size = result->number <= 256 ? 1 : result->number <= 65536 ? 2 : 4; /* 7.2.5 */
pa_size = result->flags & 0x40 ? 4 : 1; /* 7.2.6 */
if (offset + referred_to_segment_count * referred_to_segment_size + pa_size + 4 > buf_size) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "jbig2_parse_segment_header() called with insufficient data", -1);
jbig2_free(ctx->allocator, result);
return NULL;
}
/* 7.2.5 */
if (referred_to_segment_count) {
int i;
referred_to_segments = jbig2_new(ctx, uint32_t, referred_to_segment_count * referred_to_segment_size);
if (referred_to_segments == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate referred_to_segments " "in jbig2_parse_segment_header");
return NULL;
}
for (i = 0; i < referred_to_segment_count; i++) {
referred_to_segments[i] =
(referred_to_segment_size == 1) ? buf[offset] :
(referred_to_segment_size == 2) ? jbig2_get_uint16(buf + offset) : jbig2_get_uint32(buf + offset);
offset += referred_to_segment_size;
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d refers to segment %d", result->number, referred_to_segments[i]);
}
result->referred_to_segments = referred_to_segments;
} else { /* no referred-to segments */
result->referred_to_segments = NULL;
}
/* 7.2.6 */
if (result->flags & 0x40) {
result->page_association = jbig2_get_uint32(buf + offset);
offset += 4;
} else {
result->page_association = buf[offset++];
}
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d is associated with page %d", result->number, result->page_association);
/* 7.2.7 */
result->data_length = jbig2_get_uint32(buf + offset);
*p_header_size = offset + 4;
/* no body parsing results yet */
result->result = NULL;
return result;
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->vfs_inode.i_version = 1;
ei->vfs_inode.i_data.writeback_index = 0;
memset(&ei->i_cached_extent, 0, sizeof(struct ext4_ext_cache));
INIT_LIST_HEAD(&ei->i_prealloc_list);
spin_lock_init(&ei->i_prealloc_lock);
/*
* Note: We can be called before EXT4_SB(sb)->s_journal is set,
* therefore it can be null here. Don't check it, just initialize
* jinode.
*/
jbd2_journal_init_jbd_inode(&ei->jinode, &ei->vfs_inode);
ei->i_reserved_data_blocks = 0;
ei->i_reserved_meta_blocks = 0;
ei->i_allocated_meta_blocks = 0;
ei->i_da_metadata_calc_len = 0;
ei->i_delalloc_reserved_flag = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
#endif
INIT_LIST_HEAD(&ei->i_completed_io_list);
ei->cur_aio_dio = NULL;
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
return &ei->vfs_inode;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: ProgramManager::ProgramInfo* GetProgramInfoNotShader(
GLuint client_id, const char* function_name) {
ProgramManager::ProgramInfo* info = GetProgramInfo(client_id);
if (!info) {
if (GetShaderInfo(client_id)) {
SetGLError(
GL_INVALID_OPERATION, function_name, "shader passed for program");
} else {
SetGLError(GL_INVALID_VALUE, function_name, "unknown program");
}
}
return info;
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: OMX_ERRORTYPE omx_vdec::set_config(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_INDEXTYPE configIndex,
OMX_IN OMX_PTR configData)
{
(void) hComp;
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Get Config in Invalid State");
return OMX_ErrorInvalidState;
}
OMX_ERRORTYPE ret = OMX_ErrorNone;
OMX_VIDEO_CONFIG_NALSIZE *pNal;
DEBUG_PRINT_LOW("Set Config Called");
if (configIndex == (OMX_INDEXTYPE)OMX_IndexVendorVideoExtraData) {
OMX_VENDOR_EXTRADATATYPE *config = (OMX_VENDOR_EXTRADATATYPE *) configData;
DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData called");
if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc") ||
!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc")) {
DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData AVC");
OMX_U32 extra_size;
nal_length = (config->pData[4] & 0x03) + 1;
extra_size = 0;
if (nal_length > 2) {
/* Presently we assume that only one SPS and one PPS in AvC1 Atom */
extra_size = (nal_length - 2) * 2;
}
OMX_U8 *pSrcBuf = (OMX_U8 *) (&config->pData[6]);
OMX_U8 *pDestBuf;
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize - 6 - 1 + extra_size;
m_vendor_config.pData = (OMX_U8 *) malloc(m_vendor_config.nDataSize);
OMX_U32 len;
OMX_U8 index = 0;
pDestBuf = m_vendor_config.pData;
DEBUG_PRINT_LOW("Rxd SPS+PPS nPortIndex[%u] len[%u] data[%p]",
(unsigned int)m_vendor_config.nPortIndex,
(unsigned int)m_vendor_config.nDataSize,
m_vendor_config.pData);
while (index < 2) {
uint8 *psize;
len = *pSrcBuf;
len = len << 8;
len |= *(pSrcBuf + 1);
psize = (uint8 *) & len;
memcpy(pDestBuf + nal_length, pSrcBuf + 2,len);
for (unsigned int i = 0; i < nal_length; i++) {
pDestBuf[i] = psize[nal_length - 1 - i];
}
pDestBuf += len + nal_length;
pSrcBuf += len + 2;
index++;
pSrcBuf++; // skip picture param set
len = 0;
}
} else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4") ||
!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2")) {
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData = (OMX_U8 *) malloc((config->nDataSize));
memcpy(m_vendor_config.pData, config->pData,config->nDataSize);
} else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1")) {
if (m_vendor_config.pData) {
free(m_vendor_config.pData);
m_vendor_config.pData = NULL;
m_vendor_config.nDataSize = 0;
}
if (((*((OMX_U32 *) config->pData)) &
VC1_SP_MP_START_CODE_MASK) ==
VC1_SP_MP_START_CODE) {
DEBUG_PRINT_LOW("set_config - VC1 simple/main profile");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData =
(OMX_U8 *) malloc(config->nDataSize);
memcpy(m_vendor_config.pData, config->pData,
config->nDataSize);
m_vc1_profile = VC1_SP_MP_RCV;
} else if (*((OMX_U32 *) config->pData) == VC1_AP_SEQ_START_CODE) {
DEBUG_PRINT_LOW("set_config - VC1 Advance profile");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData =
(OMX_U8 *) malloc((config->nDataSize));
memcpy(m_vendor_config.pData, config->pData,
config->nDataSize);
m_vc1_profile = VC1_AP;
} else if ((config->nDataSize == VC1_STRUCT_C_LEN)) {
DEBUG_PRINT_LOW("set_config - VC1 Simple/Main profile struct C only");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData = (OMX_U8*)malloc(config->nDataSize);
memcpy(m_vendor_config.pData,config->pData,config->nDataSize);
m_vc1_profile = VC1_SP_MP_RCV;
} else {
DEBUG_PRINT_LOW("set_config - Error: Unknown VC1 profile");
}
}
return ret;
} else if (configIndex == OMX_IndexConfigVideoNalSize) {
struct v4l2_control temp;
temp.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT;
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_NALSIZE);
pNal = reinterpret_cast < OMX_VIDEO_CONFIG_NALSIZE * >(configData);
switch (pNal->nNaluBytes) {
case 0:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES;
break;
case 2:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH;
break;
case 4:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH;
break;
default:
return OMX_ErrorUnsupportedSetting;
}
if (!arbitrary_bytes) {
/* In arbitrary bytes mode, the assembler strips out nal size and replaces
* with start code, so only need to notify driver in frame by frame mode */
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &temp)) {
DEBUG_PRINT_ERROR("Failed to set V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT");
return OMX_ErrorHardware;
}
}
nal_length = pNal->nNaluBytes;
m_frame_parser.init_nal_length(nal_length);
DEBUG_PRINT_LOW("OMX_IndexConfigVideoNalSize called with Size %d", nal_length);
return ret;
} else if ((int)configIndex == (int)OMX_IndexVendorVideoFrameRate) {
OMX_VENDOR_VIDEOFRAMERATE *config = (OMX_VENDOR_VIDEOFRAMERATE *) configData;
DEBUG_PRINT_HIGH("Index OMX_IndexVendorVideoFrameRate %u", (unsigned int)config->nFps);
if (config->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) {
if (config->bEnabled) {
if ((config->nFps >> 16) > 0) {
DEBUG_PRINT_HIGH("set_config: frame rate set by omx client : %u",
(unsigned int)config->nFps >> 16);
Q16ToFraction(config->nFps, drv_ctx.frame_rate.fps_numerator,
drv_ctx.frame_rate.fps_denominator);
if (!drv_ctx.frame_rate.fps_numerator) {
DEBUG_PRINT_ERROR("Numerator is zero setting to 30");
drv_ctx.frame_rate.fps_numerator = 30;
}
if (drv_ctx.frame_rate.fps_denominator) {
drv_ctx.frame_rate.fps_numerator = (int)
drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator;
}
drv_ctx.frame_rate.fps_denominator = 1;
frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 /
drv_ctx.frame_rate.fps_numerator;
struct v4l2_outputparm oparm;
/*XXX: we're providing timing info as seconds per frame rather than frames
* per second.*/
oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator;
oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator;
struct v4l2_streamparm sparm;
sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
sparm.parm.output = oparm;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) {
DEBUG_PRINT_ERROR("Unable to convey fps info to driver, \
performance might be affected");
ret = OMX_ErrorHardware;
}
client_set_fps = true;
} else {
DEBUG_PRINT_ERROR("Frame rate not supported.");
ret = OMX_ErrorUnsupportedSetting;
}
} else {
DEBUG_PRINT_HIGH("set_config: Disabled client's frame rate");
client_set_fps = false;
}
} else {
DEBUG_PRINT_ERROR(" Set_config: Bad Port idx %d",
(int)config->nPortIndex);
ret = OMX_ErrorBadPortIndex;
}
return ret;
} else if ((int)configIndex == (int)OMX_QcomIndexConfigPerfLevel) {
OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf =
(OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData;
struct v4l2_control control;
DEBUG_PRINT_LOW("Set perf level: %d", perf->ePerfLevel);
control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL;
switch (perf->ePerfLevel) {
case OMX_QCOM_PerfLevelNominal:
control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL;
break;
case OMX_QCOM_PerfLevelTurbo:
control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO;
break;
default:
ret = OMX_ErrorUnsupportedSetting;
break;
}
if (ret == OMX_ErrorNone) {
ret = (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) ?
OMX_ErrorUnsupportedSetting : OMX_ErrorNone;
}
return ret;
} else if ((int)configIndex == (int)OMX_IndexConfigPriority) {
OMX_PARAM_U32TYPE *priority = (OMX_PARAM_U32TYPE *)configData;
DEBUG_PRINT_LOW("Set_config: priority %d", priority->nU32);
struct v4l2_control control;
control.id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY;
if (priority->nU32 == 0)
control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE;
else
control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
DEBUG_PRINT_ERROR("Failed to set Priority");
ret = OMX_ErrorUnsupportedSetting;
}
return ret;
} else if ((int)configIndex == (int)OMX_IndexConfigOperatingRate) {
OMX_PARAM_U32TYPE *rate = (OMX_PARAM_U32TYPE *)configData;
DEBUG_PRINT_LOW("Set_config: operating-rate %u fps", rate->nU32 >> 16);
struct v4l2_control control;
control.id = V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE;
control.value = rate->nU32;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
ret = errno == -EBUSY ? OMX_ErrorInsufficientResources :
OMX_ErrorUnsupportedSetting;
DEBUG_PRINT_ERROR("Failed to set operating rate %u fps (%s)",
rate->nU32 >> 16, errno == -EBUSY ? "HW Overload" : strerror(errno));
}
return ret;
}
return OMX_ErrorNotImplemented;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: deprecate unused config OMX_IndexVendorVideoExtraData
This config (used to set header offline) is no longer used. Remove handling
this config since it uses non-process-safe ways to pass memory pointers.
Fixes: Security Vulnerability - Segfault in MediaServer (libOmxVdec problem #2)
Bug: 27475409
Change-Id: I7a535a3da485cbe83cf4605a05f9faf70dcca42f
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AcceleratedStaticBitmapImage::Transfer() {
CheckThread();
EnsureMailbox(kVerifiedSyncToken, GL_NEAREST);
detach_thread_at_next_check_ = true;
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ReadUserLogFileState::UninitState( ReadUserLog::FileState &state )
{
ReadUserLogState::FileStatePub *istate =
(ReadUserLogState::FileStatePub *) state.buf;
delete istate;
state.buf = NULL;
state.size = 0;
return true;
}
Commit Message:
CWE ID: CWE-134
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int mov_write_vmhd_tag(AVIOContext *pb)
{
avio_wb32(pb, 0x14); /* size (always 0x14) */
ffio_wfourcc(pb, "vmhd");
avio_wb32(pb, 0x01); /* version & flags */
avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
return 0x14;
}
Commit Message: avformat/movenc: Write version 2 of audio atom if channels is not known
The version 1 needs the channel count and would divide by 0
Fixes: division by 0
Fixes: fpe_movenc.c_1108_1.ogg
Fixes: fpe_movenc.c_1108_2.ogg
Fixes: fpe_movenc.c_1108_3.wav
Found-by: #CHEN HONGXU# <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-369
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct sk_buff *skb;
size_t copied;
int err;
IRDA_DEBUG(4, "%s()\n", __func__);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n",
__func__, copied, size);
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
skb_free_datagram(sk, skb);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
Commit Message: irda: Fix missing msg_namelen update in irda_recvmsg_dgram()
The current code does not fill the msg_name member in case it is set.
It also does not set the msg_namelen member to 0 and therefore makes
net/socket.c leak the local, uninitialized sockaddr_storage variable
to userland -- 128 bytes of kernel stack memory.
Fix that by simply setting msg_namelen to 0 as obviously nobody cared
about irda_recvmsg_dgram() not filling the msg_name in case it was
set.
Cc: Samuel Ortiz <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: static struct tgid_iter next_tgid(struct pid_namespace *ns, struct tgid_iter iter)
{
struct pid *pid;
if (iter.task)
put_task_struct(iter.task);
rcu_read_lock();
retry:
iter.task = NULL;
pid = find_ge_pid(iter.tgid, ns);
if (pid) {
iter.tgid = pid_nr_ns(pid, ns);
iter.task = pid_task(pid, PIDTYPE_PID);
/* What we to know is if the pid we have find is the
* pid of a thread_group_leader. Testing for task
* being a thread_group_leader is the obvious thing
* todo but there is a window when it fails, due to
* the pid transfer logic in de_thread.
*
* So we perform the straight forward test of seeing
* if the pid we have found is the pid of a thread
* group leader, and don't worry if the task we have
* found doesn't happen to be a thread group leader.
* As we don't care in the case of readdir.
*/
if (!iter.task || !has_group_leader_pid(iter.task)) {
iter.tgid += 1;
goto retry;
}
get_task_struct(iter.task);
}
rcu_read_unlock();
return iter;
}
Commit Message: proc: restrict access to /proc/PID/io
/proc/PID/io may be used for gathering private information. E.g. for
openssh and vsftpd daemons wchars/rchars may be used to learn the
precise password length. Restrict it to processes being able to ptrace
the target process.
ptrace_may_access() is needed to prevent keeping open file descriptor of
"io" file, executing setuid binary and gathering io information of the
setuid'ed process.
Signed-off-by: Vasiliy Kulikov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
int32_t injectionResult;
String8 reason;
if (mFocusedWindowHandle == NULL) {
if (mFocusedApplicationHandle != NULL) {
injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
mFocusedApplicationHandle, NULL, nextWakeupTime,
"Waiting because no window has focus but there is a "
"focused application that may eventually add a window "
"when it finishes starting up.");
goto Unresponsive;
}
ALOGI("Dropping event because there is no focused window or focused application.");
injectionResult = INPUT_EVENT_INJECTION_FAILED;
goto Failed;
}
if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
goto Failed;
}
reason = checkWindowReadyForMoreInputLocked(currentTime,
mFocusedWindowHandle, entry, "focused");
if (!reason.isEmpty()) {
injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.string());
goto Unresponsive;
}
injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
addWindowTargetLocked(mFocusedWindowHandle,
InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
inputTargets);
Failed:
Unresponsive:
nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
updateDispatchStatisticsLocked(currentTime, entry,
injectionResult, timeSpentWaitingForApplication);
#if DEBUG_FOCUS
ALOGD("findFocusedWindow finished: injectionResult=%d, "
"timeSpentWaitingForApplication=%0.1fms",
injectionResult, timeSpentWaitingForApplication / 1000000.0);
#endif
return injectionResult;
}
Commit Message: Add new MotionEvent flag for partially obscured windows.
Due to more complex window layouts resulting in lots of overlapping
windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to
only be set when the point at which the window was touched is
obscured. Unfortunately, this doesn't prevent tapjacking attacks that
overlay the dialog's text, making a potentially dangerous operation
seem innocuous. To avoid this on particularly sensitive dialogs,
introduce a new flag that really does tell you when your window is
being even partially overlapped.
We aren't exposing this as API since we plan on making the original
flag more robust. This is really a workaround for system dialogs
since we generally know their layout and screen position, and that
they're unlikely to be overlapped by other applications.
Bug: 26677796
Change-Id: I9e336afe90f262ba22015876769a9c510048fd47
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static enum integrity_status evm_verify_hmac(struct dentry *dentry,
const char *xattr_name,
char *xattr_value,
size_t xattr_value_len,
struct integrity_iint_cache *iint)
{
struct evm_ima_xattr_data *xattr_data = NULL;
struct evm_ima_xattr_data calc;
enum integrity_status evm_status = INTEGRITY_PASS;
int rc, xattr_len;
if (iint && iint->evm_status == INTEGRITY_PASS)
return iint->evm_status;
/* if status is not PASS, try to check again - against -ENOMEM */
/* first need to know the sig type */
rc = vfs_getxattr_alloc(dentry, XATTR_NAME_EVM, (char **)&xattr_data, 0,
GFP_NOFS);
if (rc <= 0) {
evm_status = INTEGRITY_FAIL;
if (rc == -ENODATA) {
rc = evm_find_protected_xattrs(dentry);
if (rc > 0)
evm_status = INTEGRITY_NOLABEL;
else if (rc == 0)
evm_status = INTEGRITY_NOXATTRS; /* new file */
} else if (rc == -EOPNOTSUPP) {
evm_status = INTEGRITY_UNKNOWN;
}
goto out;
}
xattr_len = rc;
/* check value type */
switch (xattr_data->type) {
case EVM_XATTR_HMAC:
rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = memcmp(xattr_data->digest, calc.digest,
sizeof(calc.digest));
if (rc)
rc = -EINVAL;
break;
case EVM_IMA_XATTR_DIGSIG:
rc = evm_calc_hash(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM,
(const char *)xattr_data, xattr_len,
calc.digest, sizeof(calc.digest));
if (!rc) {
/* Replace RSA with HMAC if not mounted readonly and
* not immutable
*/
if (!IS_RDONLY(d_backing_inode(dentry)) &&
!IS_IMMUTABLE(d_backing_inode(dentry)))
evm_update_evmxattr(dentry, xattr_name,
xattr_value,
xattr_value_len);
}
break;
default:
rc = -EINVAL;
break;
}
if (rc)
evm_status = (rc == -ENODATA) ?
INTEGRITY_NOXATTRS : INTEGRITY_FAIL;
out:
if (iint)
iint->evm_status = evm_status;
kfree(xattr_data);
return evm_status;
}
Commit Message: EVM: Use crypto_memneq() for digest comparisons
This patch fixes vulnerability CVE-2016-2085. The problem exists
because the vm_verify_hmac() function includes a use of memcmp().
Unfortunately, this allows timing side channel attacks; specifically
a MAC forgery complexity drop from 2^128 to 2^12. This patch changes
the memcmp() to the cryptographically safe crypto_memneq().
Reported-by: Xiaofei Rex Guo <[email protected]>
Signed-off-by: Ryan Ware <[email protected]>
Cc: [email protected]
Signed-off-by: Mimi Zohar <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-19
Target: 1
Example 2:
Code: void PopulateURLResponse(
const GURL& url,
const ResourceResponseInfo& info,
WebURLResponse* response) {
response->setURL(url);
response->setResponseTime(info.response_time.ToDoubleT());
response->setMIMEType(WebString::fromUTF8(info.mime_type));
response->setTextEncodingName(WebString::fromUTF8(info.charset));
response->setExpectedContentLength(info.content_length);
response->setSecurityInfo(info.security_info);
response->setAppCacheID(info.appcache_id);
response->setAppCacheManifestURL(info.appcache_manifest_url);
response->setWasCached(!info.load_timing.request_start_time.is_null() &&
info.response_time < info.load_timing.request_start_time);
response->setRemoteIPAddress(
WebString::fromUTF8(info.socket_address.host()));
response->setRemotePort(info.socket_address.port());
response->setConnectionID(info.load_timing.socket_log_id);
response->setConnectionReused(info.load_timing.socket_reused);
response->setDownloadFilePath(
webkit_base::FilePathToWebString(info.download_file_path));
WebURLResponseExtraDataImpl* extra_data =
new WebURLResponseExtraDataImpl(info.npn_negotiated_protocol);
response->setExtraData(extra_data);
extra_data->set_was_fetched_via_spdy(info.was_fetched_via_spdy);
extra_data->set_was_npn_negotiated(info.was_npn_negotiated);
extra_data->set_was_alternate_protocol_available(
info.was_alternate_protocol_available);
extra_data->set_was_fetched_via_proxy(info.was_fetched_via_proxy);
if (!info.load_timing.receive_headers_end.is_null()) {
WebURLLoadTiming timing;
PopulateURLLoadTiming(info.load_timing, &timing);
response->setLoadTiming(timing);
}
if (info.devtools_info) {
WebHTTPLoadInfo load_info;
load_info.setHTTPStatusCode(info.devtools_info->http_status_code);
load_info.setHTTPStatusText(WebString::fromUTF8(
info.devtools_info->http_status_text));
load_info.setEncodedDataLength(info.encoded_data_length);
load_info.setRequestHeadersText(WebString::fromUTF8(
info.devtools_info->request_headers_text));
load_info.setResponseHeadersText(WebString::fromUTF8(
info.devtools_info->response_headers_text));
const HeadersVector& request_headers = info.devtools_info->request_headers;
for (HeadersVector::const_iterator it = request_headers.begin();
it != request_headers.end(); ++it) {
load_info.addRequestHeader(WebString::fromUTF8(it->first),
WebString::fromUTF8(it->second));
}
const HeadersVector& response_headers =
info.devtools_info->response_headers;
for (HeadersVector::const_iterator it = response_headers.begin();
it != response_headers.end(); ++it) {
load_info.addResponseHeader(WebString::fromUTF8(it->first),
WebString::fromUTF8(it->second));
}
response->setHTTPLoadInfo(load_info);
}
const net::HttpResponseHeaders* headers = info.headers;
if (!headers)
return;
WebURLResponse::HTTPVersion version = WebURLResponse::Unknown;
if (headers->GetHttpVersion() == net::HttpVersion(0, 9))
version = WebURLResponse::HTTP_0_9;
else if (headers->GetHttpVersion() == net::HttpVersion(1, 0))
version = WebURLResponse::HTTP_1_0;
else if (headers->GetHttpVersion() == net::HttpVersion(1, 1))
version = WebURLResponse::HTTP_1_1;
response->setHTTPVersion(version);
response->setHTTPStatusCode(headers->response_code());
response->setHTTPStatusText(WebString::fromUTF8(headers->GetStatusText()));
std::string value;
headers->EnumerateHeader(NULL, "content-disposition", &value);
response->setSuggestedFileName(
net::GetSuggestedFilename(url,
value,
std::string(), // referrer_charset
std::string(), // suggested_name
std::string(), // mime_type
std::string())); // default_name
Time time_val;
if (headers->GetLastModifiedValue(&time_val))
response->setLastModifiedDate(time_val.ToDoubleT());
void* iter = NULL;
std::string name;
while (headers->EnumerateHeaderLines(&iter, &name, &value)) {
response->addHTTPHeaderField(WebString::fromUTF8(name),
WebString::fromUTF8(value));
}
}
Commit Message: Protect WebURLLoaderImpl::Context while receiving responses.
A client's didReceiveResponse can cancel a request; by protecting the
Context we avoid a use after free in this case.
Interestingly, we really had very good warning about this problem, see
https://codereview.chromium.org/11900002/ back in January.
R=darin
BUG=241139
Review URL: https://chromiumcodereview.appspot.com/15738007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202821 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BOOL pnm2png (FILE *pnm_file, FILE *png_file, FILE *alpha_file, BOOL interlace, BOOL alpha)
{
png_struct *png_ptr = NULL;
png_info *info_ptr = NULL;
png_byte *png_pixels = NULL;
png_byte **row_pointers = NULL;
png_byte *pix_ptr = NULL;
png_uint_32 row_bytes;
char type_token[16];
char width_token[16];
char height_token[16];
char maxval_token[16];
int color_type;
unsigned long ul_width=0, ul_alpha_width=0;
unsigned long ul_height=0, ul_alpha_height=0;
unsigned long ul_maxval=0;
png_uint_32 width, alpha_width;
png_uint_32 height, alpha_height;
png_uint_32 maxval;
int bit_depth = 0;
int channels;
int alpha_depth = 0;
int alpha_present;
int row, col;
BOOL raw, alpha_raw = FALSE;
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
BOOL packed_bitmap = FALSE;
#endif
png_uint_32 tmp16;
int i;
/* read header of PNM file */
get_token(pnm_file, type_token);
if (type_token[0] != 'P')
{
return FALSE;
}
else if ((type_token[1] == '1') || (type_token[1] == '4'))
{
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
raw = (type_token[1] == '4');
color_type = PNG_COLOR_TYPE_GRAY;
get_token(pnm_file, width_token);
sscanf (width_token, "%lu", &ul_width);
width = (png_uint_32) ul_width;
get_token(pnm_file, height_token);
sscanf (height_token, "%lu", &ul_height);
height = (png_uint_32) ul_height;
bit_depth = 1;
packed_bitmap = TRUE;
#else
fprintf (stderr, "PNM2PNG built without PNG_WRITE_INVERT_SUPPORTED and \n");
fprintf (stderr, "PNG_WRITE_PACK_SUPPORTED can't read PBM (P1,P4) files\n");
#endif
}
else if ((type_token[1] == '2') || (type_token[1] == '5'))
{
raw = (type_token[1] == '5');
color_type = PNG_COLOR_TYPE_GRAY;
get_token(pnm_file, width_token);
sscanf (width_token, "%lu", &ul_width);
width = (png_uint_32) ul_width;
get_token(pnm_file, height_token);
sscanf (height_token, "%lu", &ul_height);
height = (png_uint_32) ul_height;
get_token(pnm_file, maxval_token);
sscanf (maxval_token, "%lu", &ul_maxval);
maxval = (png_uint_32) ul_maxval;
if (maxval <= 1)
bit_depth = 1;
else if (maxval <= 3)
bit_depth = 2;
else if (maxval <= 15)
bit_depth = 4;
else if (maxval <= 255)
bit_depth = 8;
else /* if (maxval <= 65535) */
bit_depth = 16;
}
else if ((type_token[1] == '3') || (type_token[1] == '6'))
{
raw = (type_token[1] == '6');
color_type = PNG_COLOR_TYPE_RGB;
get_token(pnm_file, width_token);
sscanf (width_token, "%lu", &ul_width);
width = (png_uint_32) ul_width;
get_token(pnm_file, height_token);
sscanf (height_token, "%lu", &ul_height);
height = (png_uint_32) ul_height;
get_token(pnm_file, maxval_token);
sscanf (maxval_token, "%lu", &ul_maxval);
maxval = (png_uint_32) ul_maxval;
if (maxval <= 1)
bit_depth = 1;
else if (maxval <= 3)
bit_depth = 2;
else if (maxval <= 15)
bit_depth = 4;
else if (maxval <= 255)
bit_depth = 8;
else /* if (maxval <= 65535) */
bit_depth = 16;
}
else
{
return FALSE;
}
/* read header of PGM file with alpha channel */
if (alpha)
{
if (color_type == PNG_COLOR_TYPE_GRAY)
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
if (color_type == PNG_COLOR_TYPE_RGB)
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
get_token(alpha_file, type_token);
if (type_token[0] != 'P')
{
return FALSE;
}
else if ((type_token[1] == '2') || (type_token[1] == '5'))
{
alpha_raw = (type_token[1] == '5');
get_token(alpha_file, width_token);
sscanf (width_token, "%lu", &ul_alpha_width);
alpha_width=(png_uint_32) ul_alpha_width;
if (alpha_width != width)
return FALSE;
get_token(alpha_file, height_token);
sscanf (height_token, "%lu", &ul_alpha_height);
alpha_height = (png_uint_32) ul_alpha_height;
if (alpha_height != height)
return FALSE;
get_token(alpha_file, maxval_token);
sscanf (maxval_token, "%lu", &ul_maxval);
maxval = (png_uint_32) ul_maxval;
if (maxval <= 1)
alpha_depth = 1;
else if (maxval <= 3)
alpha_depth = 2;
else if (maxval <= 15)
alpha_depth = 4;
else if (maxval <= 255)
alpha_depth = 8;
else /* if (maxval <= 65535) */
alpha_depth = 16;
if (alpha_depth != bit_depth)
return FALSE;
}
else
{
return FALSE;
}
} /* end if alpha */
/* calculate the number of channels and store alpha-presence */
if (color_type == PNG_COLOR_TYPE_GRAY)
channels = 1;
else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
channels = 2;
else if (color_type == PNG_COLOR_TYPE_RGB)
channels = 3;
else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
channels = 4;
else
channels = 0; /* should not happen */
alpha_present = (channels - 1) % 2;
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
if (packed_bitmap)
/* row data is as many bytes as can fit width x channels x bit_depth */
row_bytes = (width * channels * bit_depth + 7) / 8;
else
#endif
/* row_bytes is the width x number of channels x (bit-depth / 8) */
row_bytes = width * channels * ((bit_depth <= 8) ? 1 : 2);
if ((png_pixels = (png_byte *) malloc (row_bytes * height * sizeof (png_byte))) == NULL)
return FALSE;
/* read data from PNM file */
pix_ptr = png_pixels;
for (row = 0; row < height; row++)
{
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
if (packed_bitmap) {
for (i = 0; i < row_bytes; i++)
/* png supports this format natively so no conversion is needed */
*pix_ptr++ = get_data (pnm_file, 8);
} else
#endif
{
for (col = 0; col < width; col++)
{
for (i = 0; i < (channels - alpha_present); i++)
{
if (raw)
*pix_ptr++ = get_data (pnm_file, bit_depth);
else
if (bit_depth <= 8)
*pix_ptr++ = get_value (pnm_file, bit_depth);
else
{
tmp16 = get_value (pnm_file, bit_depth);
*pix_ptr = (png_byte) ((tmp16 >> 8) & 0xFF);
pix_ptr++;
*pix_ptr = (png_byte) (tmp16 & 0xFF);
pix_ptr++;
}
}
if (alpha) /* read alpha-channel from pgm file */
{
if (alpha_raw)
*pix_ptr++ = get_data (alpha_file, alpha_depth);
else
if (alpha_depth <= 8)
*pix_ptr++ = get_value (alpha_file, bit_depth);
else
{
tmp16 = get_value (alpha_file, bit_depth);
*pix_ptr++ = (png_byte) ((tmp16 >> 8) & 0xFF);
*pix_ptr++ = (png_byte) (tmp16 & 0xFF);
}
} /* if alpha */
} /* if packed_bitmap */
} /* end for col */
} /* end for row */
/* prepare the standard PNG structures */
png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
{
return FALSE;
}
info_ptr = png_create_info_struct (png_ptr);
if (!info_ptr)
{
png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
return FALSE;
}
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
if (packed_bitmap == TRUE)
{
png_set_packing (png_ptr);
png_set_invert_mono (png_ptr);
}
#endif
/* setjmp() must be called in every function that calls a PNG-reading libpng function */
if (setjmp (png_jmpbuf(png_ptr)))
{
png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
return FALSE;
}
/* initialize the png structure */
png_init_io (png_ptr, png_file);
/* we're going to write more or less the same PNG as the input file */
png_set_IHDR (png_ptr, info_ptr, width, height, bit_depth, color_type,
(!interlace) ? PNG_INTERLACE_NONE : PNG_INTERLACE_ADAM7,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
/* write the file header information */
png_write_info (png_ptr, info_ptr);
/* if needed we will allocate memory for an new array of row-pointers */
if (row_pointers == (unsigned char**) NULL)
{
if ((row_pointers = (png_byte **) malloc (height * sizeof (png_bytep))) == NULL)
{
png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
return FALSE;
}
}
/* set the individual row_pointers to point at the correct offsets */
for (i = 0; i < (height); i++)
row_pointers[i] = png_pixels + i * row_bytes;
/* write out the entire image data in one call */
png_write_image (png_ptr, row_pointers);
/* write the additional chuncks to the PNG file (not really needed) */
png_write_end (png_ptr, info_ptr);
/* clean up after the write, and free any memory allocated */
png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
if (row_pointers != (unsigned char**) NULL)
free (row_pointers);
if (png_pixels != (unsigned char*) NULL)
free (png_pixels);
return TRUE;
} /* end of pnm2png */
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: flac_buffer_copy (SF_PRIVATE *psf)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
const FLAC__Frame *frame = pflac->frame ;
const int32_t* const *buffer = pflac->wbuffer ;
unsigned i = 0, j, offset, channels, len ;
/*
** frame->header.blocksize is variable and we're using a constant blocksize
** of FLAC__MAX_BLOCK_SIZE.
** Check our assumptions here.
*/
if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE)
{ psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ;
psf->error = SFE_INTERNAL ;
return 0 ;
} ;
if (frame->header.channels > FLAC__MAX_CHANNELS)
psf_log_printf (psf, "Ooops : frame->header.channels (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.channels, FLAC__MAX_CHANNELS) ;
channels = SF_MIN (frame->header.channels, FLAC__MAX_CHANNELS) ;
if (pflac->ptr == NULL)
{ /*
** Not sure why this code is here and not elsewhere.
** Removing it causes valgrind errors.
*/
pflac->bufferbackup = SF_TRUE ;
for (i = 0 ; i < channels ; i++)
{
if (pflac->rbuffer [i] == NULL)
pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ;
memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (int32_t)) ;
} ;
pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ;
return 0 ;
} ;
len = SF_MIN (pflac->len, frame->header.blocksize) ;
switch (pflac->pcmtype)
{ case PFLAC_PCM_SHORT :
{ short *retpcm = (short*) pflac->ptr ;
int shift = 16 - frame->header.bits_per_sample ;
if (shift < 0)
{ shift = abs (shift) ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
}
}
else
{ for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
} ;
break ;
case PFLAC_PCM_INT :
{ int *retpcm = (int*) pflac->ptr ;
int shift = 32 - frame->header.bits_per_sample ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
case PFLAC_PCM_FLOAT :
{ float *retpcm = (float*) pflac->ptr ;
float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
case PFLAC_PCM_DOUBLE :
{ double *retpcm = (double*) pflac->ptr ;
double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
default :
return 0 ;
} ;
offset = i * channels ;
pflac->pos += i * channels ;
return offset ;
} /* flac_buffer_copy */
Commit Message: src/flac.c: Improve error handling
Especially when dealing with corrupt or malicious files.
CWE ID: CWE-119
Target: 1
Example 2:
Code: void BaseRenderingContext2D::CheckOverdraw(
const SkRect& rect,
const PaintFlags* flags,
CanvasRenderingContext2DState::ImageType image_type,
DrawType draw_type) {
PaintCanvas* c = DrawingCanvas();
if (!c)
return;
SkRect device_rect;
if (draw_type == kUntransformedUnclippedFill) {
device_rect = rect;
} else {
DCHECK_EQ(draw_type, kClipFill);
if (GetState().HasComplexClip())
return;
SkIRect sk_i_bounds;
if (!c->getDeviceClipBounds(&sk_i_bounds))
return;
device_rect = SkRect::Make(sk_i_bounds);
}
const SkImageInfo& image_info = c->imageInfo();
if (!device_rect.contains(
SkRect::MakeWH(image_info.width(), image_info.height())))
return;
bool is_source_over = true;
unsigned alpha = 0xFF;
if (flags) {
if (flags->getLooper() || flags->getImageFilter() || flags->getMaskFilter())
return;
SkBlendMode mode = flags->getBlendMode();
is_source_over = mode == SkBlendMode::kSrcOver;
if (!is_source_over && mode != SkBlendMode::kSrc &&
mode != SkBlendMode::kClear)
return; // The code below only knows how to handle Src, SrcOver, and
alpha = flags->getAlpha();
if (is_source_over &&
image_type == CanvasRenderingContext2DState::kNoImage) {
if (flags->HasShader()) {
if (flags->ShaderIsOpaque() && alpha == 0xFF)
this->WillOverwriteCanvas();
return;
}
}
}
if (is_source_over) {
if (image_type == CanvasRenderingContext2DState::kNonOpaqueImage)
return;
if (alpha < 0xFF)
return;
}
this->WillOverwriteCanvas();
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Chris Harrelson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
DelogoContext *s = inlink->dst->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
AVFrame *out;
int hsub0 = desc->log2_chroma_w;
int vsub0 = desc->log2_chroma_h;
int direct = 0;
int plane;
AVRational sar;
if (av_frame_is_writable(in)) {
direct = 1;
out = in;
} else {
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
}
sar = in->sample_aspect_ratio;
/* Assume square pixels if SAR is unknown */
if (!sar.num)
sar.num = sar.den = 1;
for (plane = 0; plane < 4 && in->data[plane]; plane++) {
int hsub = plane == 1 || plane == 2 ? hsub0 : 0;
int vsub = plane == 1 || plane == 2 ? vsub0 : 0;
apply_delogo(out->data[plane], out->linesize[plane],
in ->data[plane], in ->linesize[plane],
FF_CEIL_RSHIFT(inlink->w, hsub),
FF_CEIL_RSHIFT(inlink->h, vsub),
sar, s->x>>hsub, s->y>>vsub,
/* Up and left borders were rounded down, inject lost bits
* into width and height to avoid error accumulation */
FF_CEIL_RSHIFT(s->w + (s->x & ((1<<hsub)-1)), hsub),
FF_CEIL_RSHIFT(s->h + (s->y & ((1<<vsub)-1)), vsub),
s->band>>FFMIN(hsub, vsub),
s->show, direct);
}
if (!direct)
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
{
for (unsigned i = 0; i < nSamples; ++i) {
for (unsigned c = 0; c < nChannels; ++c) {
*dst++ = src[c][i] << 8;
}
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119
Target: 1
Example 2:
Code: gfx::Vector2d GetBoundFramebufferDrawOffset() const {
if (GetBoundDrawFramebuffer() || offscreen_target_frame_buffer_.get())
return gfx::Vector2d();
return surface_->GetDrawOffset();
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int efx_register_netdev(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct efx_channel *channel;
int rc;
net_dev->watchdog_timeo = 5 * HZ;
net_dev->irq = efx->pci_dev->irq;
net_dev->netdev_ops = &efx_netdev_ops;
SET_ETHTOOL_OPS(net_dev, &efx_ethtool_ops);
/* Clear MAC statistics */
efx->mac_op->update_stats(efx);
memset(&efx->mac_stats, 0, sizeof(efx->mac_stats));
rtnl_lock();
rc = dev_alloc_name(net_dev, net_dev->name);
if (rc < 0)
goto fail_locked;
efx_update_name(efx);
rc = register_netdevice(net_dev);
if (rc)
goto fail_locked;
efx_for_each_channel(channel, efx) {
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_init_tx_queue_core_txq(tx_queue);
}
/* Always start with carrier off; PHY events will detect the link */
netif_carrier_off(efx->net_dev);
rtnl_unlock();
rc = device_create_file(&efx->pci_dev->dev, &dev_attr_phy_type);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to init net dev attributes\n");
goto fail_registered;
}
return 0;
fail_locked:
rtnl_unlock();
netif_err(efx, drv, efx->net_dev, "could not register net dev\n");
return rc;
fail_registered:
unregister_netdev(net_dev);
return rc;
}
Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size
[ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ]
Currently an skb requiring TSO may not fit within a minimum-size TX
queue. The TX queue selected for the skb may stall and trigger the TX
watchdog repeatedly (since the problem skb will be retried after the
TX reset). This issue is designated as CVE-2012-3412.
Set the maximum number of TSO segments for our devices to 100. This
should make no difference to behaviour unless the actual MSS is less
than about 700. Increase the minimum TX queue size accordingly to
allow for 2 worst-case skbs, so that there will definitely be space
to add an skb after we wake a queue.
To avoid invalidating existing configurations, change
efx_ethtool_set_ringparam() to fix up values that are too small rather
than returning -EINVAL.
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */
{
struct _store_object *obj;
int failure = 0;
if (!EG(objects_store).object_buckets) {
return;
}
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
/* Make sure we hold a reference count during the destructor call
otherwise, when the destructor ends the storage might be freed
when the refcount reaches 0 a second time
*/
if (EG(objects_store).object_buckets[handle].valid) {
if (obj->refcount == 1) {
if (!EG(objects_store).object_buckets[handle].destructor_called) {
EG(objects_store).object_buckets[handle].destructor_called = 1;
if (obj->dtor) {
if (handlers && !obj->handlers) {
obj->handlers = handlers;
}
zend_try {
obj->dtor(obj->object, handle TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
}
/* re-read the object from the object store as the store might have been reallocated in the dtor */
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
if (obj->refcount == 1) {
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
if (obj->free_storage) {
zend_try {
obj->free_storage(obj->object TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();
}
}
}
obj->refcount--;
#if ZEND_DEBUG_OBJECTS
if (obj->refcount == 0) {
fprintf(stderr, "Deallocated object id #%d\n", handle);
} else {
fprintf(stderr, "Decreased refcount of object id #%d\n", handle);
}
#endif
if (failure) {
zend_bailout();
}
}
/* }}} */
Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction
CWE ID: CWE-119
Target: 1
Example 2:
Code: R_API int r_bin_dwarf_parse_aranges_raw(const ut8 *obuf, int len, FILE *f) {
ut32 length, offset;
ut16 version;
ut32 debug_info_offset;
ut8 address_size, segment_size;
const ut8 *buf = obuf;
int idx = 0;
if (!buf || len< 4) {
return false;
}
READ_BUF (length, ut32);
if (f) {
printf("parse_aranges\n");
printf("length 0x%x\n", length);
}
if (idx+12>=len)
return false;
READ_BUF (version, ut16);
if (f) {
printf("Version %d\n", version);
}
READ_BUF (debug_info_offset, ut32);
if (f) {
fprintf (f, "Debug info offset %d\n", debug_info_offset);
}
READ_BUF (address_size, ut8);
if (f) {
fprintf (f, "address size %d\n", (int)address_size);
}
READ_BUF (segment_size, ut8);
if (f) {
fprintf (f, "segment size %d\n", (int)segment_size);
}
offset = segment_size + address_size * 2;
if (offset) {
ut64 n = (((ut64) (size_t)buf / offset) + 1) * offset - ((ut64)(size_t)buf);
if (idx+n>=len) {
return false;
}
buf += n;
idx += n;
}
while ((buf - obuf) < len) {
ut64 adr, length;
if ((idx+8)>=len) {
break;
}
READ_BUF (adr, ut64);
READ_BUF (length, ut64);
if (f) printf("length 0x%"PFMT64x" address 0x%"PFMT64x"\n", length, adr);
}
return 0;
}
Commit Message: Fix #8813 - segfault in dwarf parser
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct ctl_table_header *sysctl_head_grab(struct ctl_table_header *head)
{
BUG_ON(!head);
spin_lock(&sysctl_lock);
if (!use_table(head))
head = ERR_PTR(-ENOENT);
spin_unlock(&sysctl_lock);
return head;
}
Commit Message: sysctl: Drop reference added by grab_header in proc_sys_readdir
Fixes CVE-2016-9191, proc_sys_readdir doesn't drop reference
added by grab_header when return from !dir_emit_dots path.
It can cause any path called unregister_sysctl_table will
wait forever.
The calltrace of CVE-2016-9191:
[ 5535.960522] Call Trace:
[ 5535.963265] [<ffffffff817cdaaf>] schedule+0x3f/0xa0
[ 5535.968817] [<ffffffff817d33fb>] schedule_timeout+0x3db/0x6f0
[ 5535.975346] [<ffffffff817cf055>] ? wait_for_completion+0x45/0x130
[ 5535.982256] [<ffffffff817cf0d3>] wait_for_completion+0xc3/0x130
[ 5535.988972] [<ffffffff810d1fd0>] ? wake_up_q+0x80/0x80
[ 5535.994804] [<ffffffff8130de64>] drop_sysctl_table+0xc4/0xe0
[ 5536.001227] [<ffffffff8130de17>] drop_sysctl_table+0x77/0xe0
[ 5536.007648] [<ffffffff8130decd>] unregister_sysctl_table+0x4d/0xa0
[ 5536.014654] [<ffffffff8130deff>] unregister_sysctl_table+0x7f/0xa0
[ 5536.021657] [<ffffffff810f57f5>] unregister_sched_domain_sysctl+0x15/0x40
[ 5536.029344] [<ffffffff810d7704>] partition_sched_domains+0x44/0x450
[ 5536.036447] [<ffffffff817d0761>] ? __mutex_unlock_slowpath+0x111/0x1f0
[ 5536.043844] [<ffffffff81167684>] rebuild_sched_domains_locked+0x64/0xb0
[ 5536.051336] [<ffffffff8116789d>] update_flag+0x11d/0x210
[ 5536.057373] [<ffffffff817cf61f>] ? mutex_lock_nested+0x2df/0x450
[ 5536.064186] [<ffffffff81167acb>] ? cpuset_css_offline+0x1b/0x60
[ 5536.070899] [<ffffffff810fce3d>] ? trace_hardirqs_on+0xd/0x10
[ 5536.077420] [<ffffffff817cf61f>] ? mutex_lock_nested+0x2df/0x450
[ 5536.084234] [<ffffffff8115a9f5>] ? css_killed_work_fn+0x25/0x220
[ 5536.091049] [<ffffffff81167ae5>] cpuset_css_offline+0x35/0x60
[ 5536.097571] [<ffffffff8115aa2c>] css_killed_work_fn+0x5c/0x220
[ 5536.104207] [<ffffffff810bc83f>] process_one_work+0x1df/0x710
[ 5536.110736] [<ffffffff810bc7c0>] ? process_one_work+0x160/0x710
[ 5536.117461] [<ffffffff810bce9b>] worker_thread+0x12b/0x4a0
[ 5536.123697] [<ffffffff810bcd70>] ? process_one_work+0x710/0x710
[ 5536.130426] [<ffffffff810c3f7e>] kthread+0xfe/0x120
[ 5536.135991] [<ffffffff817d4baf>] ret_from_fork+0x1f/0x40
[ 5536.142041] [<ffffffff810c3e80>] ? kthread_create_on_node+0x230/0x230
One cgroup maintainer mentioned that "cgroup is trying to offline
a cpuset css, which takes place under cgroup_mutex. The offlining
ends up trying to drain active usages of a sysctl table which apprently
is not happening."
The real reason is that proc_sys_readdir doesn't drop reference added
by grab_header when return from !dir_emit_dots path. So this cpuset
offline path will wait here forever.
See here for details: http://www.openwall.com/lists/oss-security/2016/11/04/13
Fixes: f0c3b5093add ("[readdir] convert procfs")
Cc: [email protected]
Reported-by: CAI Qian <[email protected]>
Tested-by: Yang Shukui <[email protected]>
Signed-off-by: Zhou Chengming <[email protected]>
Acked-by: Al Viro <[email protected]>
Signed-off-by: Eric W. Biederman <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void EmulationHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
if (host_ == frame_host)
return;
host_ = frame_host;
if (touch_emulation_enabled_)
UpdateTouchEventEmulationState();
UpdateDeviceEmulationState();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int SocketStream::DoGenerateProxyAuthTokenComplete(int result) {
if (result != OK) {
next_state_ = STATE_CLOSE;
return result;
}
next_state_ = STATE_WRITE_TUNNEL_HEADERS;
return result;
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: header_seek (SF_PRIVATE *psf, sf_count_t position, int whence)
{
switch (whence)
{ case SEEK_SET :
if (position > SIGNED_SIZEOF (psf->header))
{ /* Too much header to cache so just seek instead. */
psf_fseek (psf, position, whence) ;
return ;
} ;
if (position > psf->headend)
psf->headend += psf_fread (psf->header + psf->headend, 1, position - psf->headend, psf) ;
psf->headindex = position ;
break ;
case SEEK_CUR :
if (psf->headindex + position < 0)
break ;
if (psf->headindex >= SIGNED_SIZEOF (psf->header))
{ psf_fseek (psf, position, whence) ;
return ;
} ;
if (psf->headindex + position <= psf->headend)
{ psf->headindex += position ;
break ;
} ;
if (psf->headindex + position > SIGNED_SIZEOF (psf->header))
{ /* Need to jump this without caching it. */
psf->headindex = psf->headend ;
psf_fseek (psf, position, SEEK_CUR) ;
break ;
} ;
psf->headend += psf_fread (psf->header + psf->headend, 1, position - (psf->headend - psf->headindex), psf) ;
psf->headindex = psf->headend ;
break ;
case SEEK_END :
default :
psf_log_printf (psf, "Bad whence param in header_seek().\n") ;
break ;
} ;
return ;
} /* header_seek */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ExtensionsGuestViewMessageFilter::MimeHandlerViewGuestCreatedCallback(
int element_instance_id,
int embedder_render_process_id,
int embedder_render_frame_id,
int32_t plugin_frame_routing_id,
const gfx::Size& element_size,
mime_handler::BeforeUnloadControlPtrInfo before_unload_control,
bool is_full_page_plugin,
WebContents* web_contents) {
auto* guest_view = MimeHandlerViewGuest::FromWebContents(web_contents);
if (!guest_view)
return;
guest_view->SetBeforeUnloadController(std::move(before_unload_control));
int guest_instance_id = guest_view->guest_instance_id();
auto* rfh = RenderFrameHost::FromID(embedder_render_process_id,
embedder_render_frame_id);
if (!rfh)
return;
guest_view->SetEmbedderFrame(embedder_render_process_id,
embedder_render_frame_id);
base::DictionaryValue attach_params;
attach_params.SetInteger(guest_view::kElementWidth, element_size.width());
attach_params.SetInteger(guest_view::kElementHeight, element_size.height());
auto* manager = GuestViewManager::FromBrowserContext(browser_context_);
if (!manager) {
guest_view::bad_message::ReceivedBadMessage(
this,
guest_view::bad_message::GVMF_UNEXPECTED_MESSAGE_BEFORE_GVM_CREATION);
guest_view->Destroy(true);
return;
}
manager->AttachGuest(embedder_render_process_id, element_instance_id,
guest_instance_id, attach_params);
if (!content::MimeHandlerViewMode::UsesCrossProcessFrame()) {
rfh->Send(new ExtensionsGuestViewMsg_CreateMimeHandlerViewGuestACK(
element_instance_id));
return;
}
auto* plugin_rfh = RenderFrameHost::FromID(embedder_render_process_id,
plugin_frame_routing_id);
if (!plugin_rfh) {
plugin_rfh = RenderFrameHost::FromPlaceholderId(embedder_render_process_id,
plugin_frame_routing_id);
}
if (!plugin_rfh) {
guest_view->GetEmbedderFrame()->Send(
new ExtensionsGuestViewMsg_RetryCreatingMimeHandlerViewGuest(
element_instance_id));
guest_view->Destroy(true);
return;
}
if (guest_view->web_contents()->CanAttachToOuterContentsFrame(plugin_rfh)) {
guest_view->AttachToOuterWebContentsFrame(plugin_rfh, element_instance_id,
is_full_page_plugin);
} else {
frame_navigation_helpers_[element_instance_id] =
std::make_unique<FrameNavigationHelper>(
plugin_rfh, guest_view->guest_instance_id(), element_instance_id,
is_full_page_plugin, this);
}
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362
Target: 1
Example 2:
Code: rsvg_acquire_file_data (const char *filename,
const char *base_uri,
char **out_mime_type,
gsize *out_len,
GCancellable *cancellable,
GError **error)
{
gchar *path, *data;
gsize len;
char *content_type;
rsvg_return_val_if_fail (filename != NULL, NULL, error);
g_assert (out_len != NULL);
path = _rsvg_io_get_file_path (filename, base_uri);
if (path == NULL)
return NULL;
if (!g_file_get_contents (path, &data, &len, error)) {
g_free (path);
return NULL;
}
if (out_mime_type &&
(content_type = g_content_type_guess (path, (guchar *) data, len, NULL))) {
*out_mime_type = g_content_type_get_mime_type (content_type);
g_free (content_type);
}
g_free (path);
*out_len = len;
return data;
}
Commit Message: Fixed possible credentials leaking reported by Alex Birsan.
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void sem_lock_and_putref(struct sem_array *sma)
{
ipc_lock_by_ptr(&sma->sem_perm);
ipc_rcu_putref(sma);
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ResourceDispatcherHostImpl::InitializeURLRequest(
net::URLRequest* request,
const Referrer& referrer,
bool is_download,
int render_process_host_id,
int render_view_routing_id,
int render_frame_routing_id,
PreviewsState previews_state,
ResourceContext* context) {
DCHECK(io_thread_task_runner_->BelongsToCurrentThread());
DCHECK(!request->is_pending());
Referrer::SetReferrerForRequest(request, referrer);
ResourceRequestInfoImpl* info = CreateRequestInfo(
render_process_host_id, render_view_routing_id, render_frame_routing_id,
previews_state, is_download, context);
info->AssociateWithRequest(request);
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
Target: 1
Example 2:
Code: atm_print(netdissect_options *ndo,
u_int vpi, u_int vci, u_int traftype, const u_char *p, u_int length,
u_int caplen)
{
if (ndo->ndo_eflag)
ND_PRINT((ndo, "VPI:%u VCI:%u ", vpi, vci));
if (vpi == 0) {
switch (vci) {
case VCI_PPC:
sig_print(ndo, p);
return;
case VCI_BCC:
ND_PRINT((ndo, "broadcast sig: "));
return;
case VCI_OAMF4SC: /* fall through */
case VCI_OAMF4EC:
oam_print(ndo, p, length, ATM_OAM_HEC);
return;
case VCI_METAC:
ND_PRINT((ndo, "meta: "));
return;
case VCI_ILMIC:
ND_PRINT((ndo, "ilmi: "));
snmp_print(ndo, p, length);
return;
}
}
switch (traftype) {
case ATM_LLC:
default:
/*
* Assumes traffic is LLC if unknown.
*/
atm_llc_print(ndo, p, length, caplen);
break;
case ATM_LANE:
lane_print(ndo, p, length, caplen);
break;
}
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t OMXNodeInstance::updateGraphicBufferInMeta_l(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer, OMX_BUFFERHEADERTYPE *header) {
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
bufferMeta->setGraphicBuffer(graphicBuffer);
if (mMetadataType[portIndex] == kMetadataBufferTypeGrallocSource
&& header->nAllocLen >= sizeof(VideoGrallocMetadata)) {
VideoGrallocMetadata &metadata = *(VideoGrallocMetadata *)(header->pBuffer);
metadata.eType = kMetadataBufferTypeGrallocSource;
metadata.pHandle = graphicBuffer == NULL ? NULL : graphicBuffer->handle;
} else if (mMetadataType[portIndex] == kMetadataBufferTypeANWBuffer
&& header->nAllocLen >= sizeof(VideoNativeMetadata)) {
VideoNativeMetadata &metadata = *(VideoNativeMetadata *)(header->pBuffer);
metadata.eType = kMetadataBufferTypeANWBuffer;
metadata.pBuffer = graphicBuffer == NULL ? NULL : graphicBuffer->getNativeBuffer();
metadata.nFenceFd = -1;
} else {
CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x bad type (%d) or size (%u)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], header->nAllocLen);
return BAD_VALUE;
}
CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
graphicBuffer == NULL ? NULL : graphicBuffer->handle);
return OK;
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)
{
int i, j;
BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;
X509_ALGOR *xa;
ASN1_OCTET_STRING *data_body = NULL;
const EVP_MD *evp_md;
const EVP_CIPHER *evp_cipher = NULL;
EVP_CIPHER_CTX *evp_ctx = NULL;
X509_ALGOR *enc_alg = NULL;
STACK_OF(X509_ALGOR) *md_sk = NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
PKCS7_RECIP_INFO *ri = NULL;
unsigned char *ek = NULL, *tkey = NULL;
int eklen = 0, tkeylen = 0;
if (p7 == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);
return NULL;
}
if (p7->d.ptr == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);
return NULL;
}
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
switch (i) {
case NID_pkcs7_signed:
data_body = PKCS7_get_octet_string(p7->d.sign->contents);
if (!PKCS7_is_detached(p7) && data_body == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_INVALID_SIGNED_DATA_TYPE);
goto err;
}
md_sk = p7->d.sign->md_algs;
break;
case NID_pkcs7_signedAndEnveloped:
rsk = p7->d.signed_and_enveloped->recipientinfo;
md_sk = p7->d.signed_and_enveloped->md_algs;
data_body = p7->d.signed_and_enveloped->enc_data->enc_data;
enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;
evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto err;
}
break;
case NID_pkcs7_enveloped:
rsk = p7->d.enveloped->recipientinfo;
enc_alg = p7->d.enveloped->enc_data->algorithm;
data_body = p7->d.enveloped->enc_data->enc_data;
evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto err;
}
break;
default:
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
/* We will be checking the signature */
if (md_sk != NULL) {
for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {
xa = sk_X509_ALGOR_value(md_sk, i);
if ((btmp = BIO_new(BIO_f_md())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
goto err;
}
j = OBJ_obj2nid(xa->algorithm);
evp_md = EVP_get_digestbynid(j);
if (evp_md == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNKNOWN_DIGEST_TYPE);
goto err;
}
BIO_set_md(btmp, evp_md);
if (out == NULL)
out = btmp;
else
BIO_push(out, btmp);
btmp = NULL;
}
}
if (evp_cipher != NULL) {
if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
goto err;
}
/*
* It was encrypted, we need to decrypt the secret key with the
* private key
*/
/*
* Find the recipientInfo which matches the passed certificate (if
* any)
*/
if (pcert) {
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if (!pkcs7_cmp_ri(ri, pcert))
break;
ri = NULL;
}
if (ri == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);
goto err;
}
}
/* If we haven't got a certificate try each ri in turn */
if (pcert == NULL) {
/*
* Always attempt to decrypt all rinfo even after success as a
* defence against MMA timing attacks.
*/
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)
goto err;
ERR_clear_error();
}
} else {
/* Only exit on fatal errors, not decrypt failure */
if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)
goto err;
ERR_clear_error();
}
evp_ctx = NULL;
BIO_get_cipher_ctx(etmp, &evp_ctx);
if (EVP_CipherInit_ex(evp_ctx, evp_cipher, NULL, NULL, NULL, 0) <= 0)
goto err;
if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) < 0)
goto err;
/* Generate random key as MMA defence */
tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);
tkey = OPENSSL_malloc(tkeylen);
if (!tkey)
goto err;
if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)
goto err;
if (ek == NULL) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
if (eklen != EVP_CIPHER_CTX_key_length(evp_ctx)) {
/*
* Some S/MIME clients don't use the same key and effective key
* length. The key length is determined by the size of the
* decrypted RSA key.
*/
if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen)) {
/* Use random key as MMA defence */
OPENSSL_clear_free(ek, eklen);
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
}
/* Clear errors so we don't leak information useful in MMA */
ERR_clear_error();
if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)
goto err;
OPENSSL_clear_free(ek, eklen);
ek = NULL;
OPENSSL_clear_free(tkey, tkeylen);
tkey = NULL;
if (out == NULL)
out = etmp;
else
BIO_push(out, etmp);
etmp = NULL;
}
if (PKCS7_is_detached(p7) || (in_bio != NULL)) {
bio = in_bio;
} else {
if (data_body->length > 0)
bio = BIO_new_mem_buf(data_body->data, data_body->length);
else {
bio = BIO_new(BIO_s_mem());
BIO_set_mem_eof_return(bio, 0);
}
if (bio == NULL)
goto err;
}
BIO_push(out, bio);
bio = NULL;
return out;
err:
OPENSSL_clear_free(ek, eklen);
OPENSSL_clear_free(tkey, tkeylen);
BIO_free_all(out);
BIO_free_all(btmp);
BIO_free_all(etmp);
BIO_free_all(bio);
return NULL;
}
Commit Message: PKCS#7: Fix NULL dereference with missing EncryptedContent.
CVE-2015-1790
Reviewed-by: Rich Salz <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void reset_stats() { num_invocations_ = 0; }
Commit Message: ash: Make UserActivityDetector ignore synthetic mouse events
This may have been preventing us from suspending (e.g.
mouse event is synthesized in response to lock window being
shown so Chrome tells powerd that the user is active).
BUG=133419
TEST=added
Review URL: https://chromiumcodereview.appspot.com/10574044
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143437 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostViewAura::OnPaint(const ui::PaintContext& context) {
NOTREACHED();
}
Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash
RenderWidgetHostViewChildFrame expects its parent to have a valid
FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even
if DelegatedFrameHost is not used (in mus+ash).
BUG=706553
[email protected]
Review-Url: https://codereview.chromium.org/2847253003
Cr-Commit-Position: refs/heads/master@{#468179}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int su3000_frontend_attach(struct dvb_usb_adapter *d)
{
u8 obuf[3] = { 0xe, 0x80, 0 };
u8 ibuf[] = { 0 };
if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)
err("command 0x0e transfer failed.");
obuf[0] = 0xe;
obuf[1] = 0x02;
obuf[2] = 1;
if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)
err("command 0x0e transfer failed.");
msleep(300);
obuf[0] = 0xe;
obuf[1] = 0x83;
obuf[2] = 0;
if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)
err("command 0x0e transfer failed.");
obuf[0] = 0xe;
obuf[1] = 0x83;
obuf[2] = 1;
if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)
err("command 0x0e transfer failed.");
obuf[0] = 0x51;
if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0)
err("command 0x51 transfer failed.");
d->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config,
&d->dev->i2c_adap);
if (d->fe_adap[0].fe == NULL)
return -EIO;
if (dvb_attach(ts2020_attach, d->fe_adap[0].fe,
&dw2104_ts2020_config,
&d->dev->i2c_adap)) {
info("Attached DS3000/TS2020!");
return 0;
}
info("Failed to attach DS3000/TS2020!");
return -EIO;
}
Commit Message: [media] dw2102: don't do DMA on stack
On Kernel 4.9, WARNINGs about doing DMA on stack are hit at
the dw2102 driver: one in su3000_power_ctrl() and the other in tt_s2_4600_frontend_attach().
Both were due to the use of buffers on the stack as parameters to
dvb_usb_generic_rw() and the resulting attempt to do DMA with them.
The device was non-functional as a result.
So, switch this driver over to use a buffer within the device state
structure, as has been done with other DVB-USB drivers.
Tested with TechnoTrend TT-connect S2-4600.
[[email protected]: fixed a warning at su3000_i2c_transfer() that
state var were dereferenced before check 'd']
Signed-off-by: Jonathan McDowell <[email protected]>
Cc: <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: garp_group_handler(vector_t *strvec)
{
if (!strvec)
return;
alloc_garp_delay();
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool batadv_frag_init_chain(struct batadv_frag_table_entry *chain,
uint16_t seqno)
{
if (chain->seqno == seqno)
return false;
if (!hlist_empty(&chain->head))
batadv_frag_clear_chain(&chain->head);
chain->size = 0;
chain->seqno = seqno;
return true;
}
Commit Message: batman-adv: Calculate extra tail size based on queued fragments
The fragmentation code was replaced in 610bfc6bc99bc83680d190ebc69359a05fc7f605
("batman-adv: Receive fragmented packets and merge"). The new code provided a
mostly unused parameter skb for the merging function. It is used inside the
function to calculate the additionally needed skb tailroom. But instead of
increasing its own tailroom, it is only increasing the tailroom of the first
queued skb. This is not correct in some situations because the first queued
entry can be a different one than the parameter.
An observed problem was:
1. packet with size 104, total_size 1464, fragno 1 was received
- packet is queued
2. packet with size 1400, total_size 1464, fragno 0 was received
- packet is queued at the end of the list
3. enough data was received and can be given to the merge function
(1464 == (1400 - 20) + (104 - 20))
- merge functions gets 1400 byte large packet as skb argument
4. merge function gets first entry in queue (104 byte)
- stored as skb_out
5. merge function calculates the required extra tail as total_size - skb->len
- pskb_expand_head tail of skb_out with 64 bytes
6. merge function tries to squeeze the extra 1380 bytes from the second queued
skb (1400 byte aka skb parameter) in the 64 extra tail bytes of skb_out
Instead calculate the extra required tail bytes for skb_out also using skb_out
instead of using the parameter skb. The skb parameter is only used to get the
total_size from the last received packet. This is also the total_size used to
decide that all fragments were received.
Reported-by: Philipp Psurek <[email protected]>
Signed-off-by: Sven Eckelmann <[email protected]>
Acked-by: Martin Hundebøll <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data;
switch (msr) {
case MSR_IA32_PLATFORM_ID:
case MSR_IA32_EBL_CR_POWERON:
case MSR_IA32_DEBUGCTLMSR:
case MSR_IA32_LASTBRANCHFROMIP:
case MSR_IA32_LASTBRANCHTOIP:
case MSR_IA32_LASTINTFROMIP:
case MSR_IA32_LASTINTTOIP:
case MSR_K8_SYSCFG:
case MSR_K7_HWCR:
case MSR_VM_HSAVE_PA:
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
case MSR_K8_INT_PENDING_MSG:
case MSR_AMD64_NB_CFG:
case MSR_FAM10H_MMIO_CONF_BASE:
case MSR_AMD64_BU_CFG2:
data = 0;
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_get_msr(vcpu, msr, pdata);
data = 0;
break;
case MSR_IA32_UCODE_REV:
data = 0x100000000ULL;
break;
case MSR_MTRRcap:
data = 0x500 | KVM_NR_VAR_MTRR;
break;
case 0x200 ... 0x2ff:
return get_msr_mtrr(vcpu, msr, pdata);
case 0xcd: /* fsb frequency */
data = 3;
break;
/*
* MSR_EBC_FREQUENCY_ID
* Conservative value valid for even the basic CPU models.
* Models 0,1: 000 in bits 23:21 indicating a bus speed of
* 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
* and 266MHz for model 3, or 4. Set Core Clock
* Frequency to System Bus Frequency Ratio to 1 (bits
* 31:24) even though these are only valid for CPU
* models > 2, however guests may end up dividing or
* multiplying by zero otherwise.
*/
case MSR_EBC_FREQUENCY_ID:
data = 1 << 24;
break;
case MSR_IA32_APICBASE:
data = kvm_get_apic_base(vcpu);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_read(vcpu, msr, pdata);
break;
case MSR_IA32_TSCDEADLINE:
data = kvm_get_lapic_tscdeadline_msr(vcpu);
break;
case MSR_IA32_TSC_ADJUST:
data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
break;
case MSR_IA32_MISC_ENABLE:
data = vcpu->arch.ia32_misc_enable_msr;
break;
case MSR_IA32_PERF_STATUS:
/* TSC increment by tick */
data = 1000ULL;
/* CPU multiplier */
data |= (((uint64_t)4ULL) << 40);
break;
case MSR_EFER:
data = vcpu->arch.efer;
break;
case MSR_KVM_WALL_CLOCK:
case MSR_KVM_WALL_CLOCK_NEW:
data = vcpu->kvm->arch.wall_clock;
break;
case MSR_KVM_SYSTEM_TIME:
case MSR_KVM_SYSTEM_TIME_NEW:
data = vcpu->arch.time;
break;
case MSR_KVM_ASYNC_PF_EN:
data = vcpu->arch.apf.msr_val;
break;
case MSR_KVM_STEAL_TIME:
data = vcpu->arch.st.msr_val;
break;
case MSR_KVM_PV_EOI_EN:
data = vcpu->arch.pv_eoi.msr_val;
break;
case MSR_IA32_P5_MC_ADDR:
case MSR_IA32_P5_MC_TYPE:
case MSR_IA32_MCG_CAP:
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return get_msr_mce(vcpu, msr, pdata);
case MSR_K7_CLK_CTL:
/*
* Provide expected ramp-up count for K7. All other
* are set to zero, indicating minimum divisors for
* every field.
*
* This prevents guest kernels on AMD host with CPU
* type 6, model 8 and higher from exploding due to
* the rdmsr failing.
*/
data = 0x20000000;
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = get_msr_hyperv_pw(vcpu, msr, pdata);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return get_msr_hyperv(vcpu, msr, pdata);
break;
case MSR_IA32_BBL_CR_CTL3:
/* This legacy MSR exists but isn't fully documented in current
* silicon. It is however accessed by winxp in very narrow
* scenarios where it sets bit #19, itself documented as
* a "reserved" bit. Best effort attempt to source coherent
* read data here should the balance of the register be
* interpreted by the guest:
*
* L2 cache control register 3: 64GB range, 256KB size,
* enabled, latency 0x1, configured
*/
data = 0xbe702111;
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
data = vcpu->arch.osvw.length;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
data = vcpu->arch.osvw.status;
break;
default:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_get_msr(vcpu, msr, pdata);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
data = 0;
}
break;
}
*pdata = data;
return 0;
}
Commit Message: KVM: x86: Don't report guest userspace emulation error to userspace
Commit fc3a9157d314 ("KVM: X86: Don't report L2 emulation failures to
user-space") disabled the reporting of L2 (nested guest) emulation failures to
userspace due to race-condition between a vmexit and the instruction emulator.
The same rational applies also to userspace applications that are permitted by
the guest OS to access MMIO area or perform PIO.
This patch extends the current behavior - of injecting a #UD instead of
reporting it to userspace - also for guest userspace code.
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void Ins_JMPR( INS_ARG )
{
CUR.IP += (Int)(args[0]);
CUR.step_ins = FALSE;
* allow for simple cases here by just checking the preceding byte.
* Fonts with this problem are not uncommon.
*/
CUR.IP -= 1;
}
Commit Message:
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static unsigned xen_netbk_tx_build_gops(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop;
struct sk_buff *skb;
int ret;
while (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) &&
!list_empty(&netbk->net_schedule_list)) {
struct xenvif *vif;
struct xen_netif_tx_request txreq;
struct xen_netif_tx_request txfrags[MAX_SKB_FRAGS];
struct page *page;
struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];
u16 pending_idx;
RING_IDX idx;
int work_to_do;
unsigned int data_len;
pending_ring_idx_t index;
/* Get a netif from the list with work to do. */
vif = poll_net_schedule_list(netbk);
if (!vif)
continue;
RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do);
if (!work_to_do) {
xenvif_put(vif);
continue;
}
idx = vif->tx.req_cons;
rmb(); /* Ensure that we see the request before we copy it. */
memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));
/* Credit-based scheduling. */
if (txreq.size > vif->remaining_credit &&
tx_credit_exceeded(vif, txreq.size)) {
xenvif_put(vif);
continue;
}
vif->remaining_credit -= txreq.size;
work_to_do--;
vif->tx.req_cons = ++idx;
memset(extras, 0, sizeof(extras));
if (txreq.flags & XEN_NETTXF_extra_info) {
work_to_do = xen_netbk_get_extras(vif, extras,
work_to_do);
idx = vif->tx.req_cons;
if (unlikely(work_to_do < 0)) {
netbk_tx_err(vif, &txreq, idx);
continue;
}
}
ret = netbk_count_requests(vif, &txreq, txfrags, work_to_do);
if (unlikely(ret < 0)) {
netbk_tx_err(vif, &txreq, idx - ret);
continue;
}
idx += ret;
if (unlikely(txreq.size < ETH_HLEN)) {
netdev_dbg(vif->dev,
"Bad packet size: %d\n", txreq.size);
netbk_tx_err(vif, &txreq, idx);
continue;
}
/* No crossing a page as the payload mustn't fragment. */
if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {
netdev_dbg(vif->dev,
"txreq.offset: %x, size: %u, end: %lu\n",
txreq.offset, txreq.size,
(txreq.offset&~PAGE_MASK) + txreq.size);
netbk_tx_err(vif, &txreq, idx);
continue;
}
index = pending_index(netbk->pending_cons);
pending_idx = netbk->pending_ring[index];
data_len = (txreq.size > PKT_PROT_LEN &&
ret < MAX_SKB_FRAGS) ?
PKT_PROT_LEN : txreq.size;
skb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN,
GFP_ATOMIC | __GFP_NOWARN);
if (unlikely(skb == NULL)) {
netdev_dbg(vif->dev,
"Can't allocate a skb in start_xmit.\n");
netbk_tx_err(vif, &txreq, idx);
break;
}
/* Packets passed to netif_rx() must have some headroom. */
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
struct xen_netif_extra_info *gso;
gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
if (netbk_set_skb_gso(vif, skb, gso)) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
}
/* XXX could copy straight to head */
page = xen_netbk_alloc_page(netbk, skb, pending_idx);
if (!page) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop->source.u.ref = txreq.gref;
gop->source.domid = vif->domid;
gop->source.offset = txreq.offset;
gop->dest.u.gmfn = virt_to_mfn(page_address(page));
gop->dest.domid = DOMID_SELF;
gop->dest.offset = txreq.offset;
gop->len = txreq.size;
gop->flags = GNTCOPY_source_gref;
gop++;
memcpy(&netbk->pending_tx_info[pending_idx].req,
&txreq, sizeof(txreq));
netbk->pending_tx_info[pending_idx].vif = vif;
*((u16 *)skb->data) = pending_idx;
__skb_put(skb, data_len);
skb_shinfo(skb)->nr_frags = ret;
if (data_len < txreq.size) {
skb_shinfo(skb)->nr_frags++;
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
pending_idx);
} else {
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
INVALID_PENDING_IDX);
}
netbk->pending_cons++;
request_gop = xen_netbk_get_requests(netbk, vif,
skb, txfrags, gop);
if (request_gop == NULL) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop = request_gop;
__skb_queue_tail(&netbk->tx_queue, skb);
vif->tx.req_cons = idx;
xen_netbk_check_rx_xenvif(vif);
if ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops))
break;
}
return gop - netbk->tx_copy_ops;
}
Commit Message: xen/netback: shutdown the ring if it contains garbage.
A buggy or malicious frontend should not be able to confuse netback.
If we spot anything which is not as it should be then shutdown the
device and don't try to continue with the ring in a potentially
hostile state. Well behaved and non-hostile frontends will not be
penalised.
As well as making the existing checks for such errors fatal also add a
new check that ensures that there isn't an insane number of requests
on the ring (i.e. more than would fit in the ring). If the ring
contains garbage then previously is was possible to loop over this
insane number, getting an error each time and therefore not generating
any more pending requests and therefore not exiting the loop in
xen_netbk_tx_build_gops for an externded period.
Also turn various netdev_dbg calls which no precipitate a fatal error
into netdev_err, they are rate limited because the device is shutdown
afterwards.
This fixes at least one known DoS/softlockup of the backend domain.
Signed-off-by: Ian Campbell <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: sf_next_chunk_iterator (SF_CHUNK_ITERATOR * iterator)
{ SF_PRIVATE *psf ;
SNDFILE *sndfile = iterator ? iterator->sndfile : NULL ;
VALIDATE_SNDFILE_AND_ASSIGN_PSF (sndfile, psf, 1) ;
if (psf->next_chunk_iterator)
return psf->next_chunk_iterator (psf, iterator) ;
return NULL ;
} /* sf_get_chunk_iterator_next */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: get_policy(kadm5_server_handle_t handle, const char *name,
kadm5_policy_ent_t policy_out, krb5_boolean *have_pol_out)
{
kadm5_ret_t ret;
*have_pol_out = FALSE;
if (name == NULL)
return 0;
ret = kadm5_get_policy(handle->lhandle, (char *)name, policy_out);
if (ret == 0)
*have_pol_out = TRUE;
return (ret == KADM5_UNK_POLICY) ? 0 : ret;
}
Commit Message: Return only new keys in randkey [CVE-2014-5351]
In kadmind's randkey operation, if a client specifies the keepold
flag, do not include the preserved old keys in the response.
CVE-2014-5351:
An authenticated remote attacker can retrieve the current keys for a
service principal when generating a new set of keys for that
principal. The attacker needs to be authenticated as a user who has
the elevated privilege for randomizing the keys of other principals.
Normally, when a Kerberos administrator randomizes the keys of a
service principal, kadmind returns only the new keys. This prevents
an administrator who lacks legitimate privileged access to a service
from forging tickets to authenticate to that service. If the
"keepold" flag to the kadmin randkey RPC operation is true, kadmind
retains the old keys in the KDC database as intended, but also
unexpectedly returns the old keys to the client, which exposes the
service to ticket forgery attacks from the administrator.
A mitigating factor is that legitimate clients of the affected service
will start failing to authenticate to the service once they begin to
receive service tickets encrypted in the new keys. The affected
service will be unable to decrypt the newly issued tickets, possibly
alerting the legitimate administrator of the affected service.
CVSSv2: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C
[[email protected]: CVE description and CVSS score]
ticket: 8018 (new)
target_version: 1.13
tags: pullup
CWE ID: CWE-255
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int sock_recv_all(int sock_fd, uint8_t* buf, int len)
{
int r = len;
int ret = -1;
while(r)
{
do ret = recv(sock_fd, buf, r, MSG_WAITALL);
while(ret < 0 && errno == EINTR);
if(ret <= 0)
{
BTIF_TRACE_ERROR("sock fd:%d recv errno:%d, ret:%d", sock_fd, errno, ret);
return -1;
}
buf += ret;
r -= ret;
}
return len;
}
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
Target: 1
Example 2:
Code: void HistogramEnumerateManifestIsDataURI(bool is_data_uri) {
HistogramEnumerate("NaCl.Manifest.IsDataURI", is_data_uri, 2, -1);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: my_object_finalize (GObject *object)
{
MyObject *mobject = MY_OBJECT (object);
g_free (mobject->this_is_a_string);
(G_OBJECT_CLASS (my_object_parent_class)->finalize) (object);
}
Commit Message:
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
struct perf_event *event = file->private_data;
return perf_read_hw(event, buf, count);
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: static UPNP_INLINE void glob_alias_init(void)
{
struct xml_alias_t *alias = &gAliasDoc;
membuffer_init(&alias->doc);
membuffer_init(&alias->name);
alias->ct = NULL;
alias->last_modified = 0;
}
Commit Message: Don't allow unhandled POSTs to write to the filesystem by default
If there's no registered handler for a POST request, the default behaviour
is to write it to the filesystem. Several million deployed devices appear
to have this behaviour, making it possible to (at least) store arbitrary
data on them. Add a configure option that enables this behaviour, and change
the default to just drop POSTs that aren't directly handled.
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PassRefPtr<ArchiveResource> DocumentLoader::subresource(const KURL& url) const
{
if (!isCommitted())
return 0;
CachedResource* resource = m_cachedResourceLoader->cachedResource(url);
if (!resource || !resource->isLoaded())
return archiveResourceForURL(url);
if (resource->type() == CachedResource::MainResource)
return 0;
if (!resource->makePurgeable(false))
return 0;
ResourceBuffer* data = resource->resourceBuffer();
if (!data)
return 0;
return ArchiveResource::create(data->sharedBuffer(), url, resource->response());
}
Commit Message: Unreviewed, rolling out r147402.
http://trac.webkit.org/changeset/147402
https://bugs.webkit.org/show_bug.cgi?id=112903
Source/WebCore:
* dom/Document.cpp:
(WebCore::Document::processHttpEquiv):
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::responseReceived):
LayoutTests:
* http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html:
* http/tests/security/XFrameOptions/x-frame-options-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(navigation_handle);
if (!navigation_handle->IsInMainFrame() ||
navigation_handle->IsSameDocument()) {
return;
}
first_time_title_set_ = false;
first_time_favicon_set_ = false;
if (!navigation_handle->HasCommitted())
return;
const url::Origin new_origin =
url::Origin::Create(navigation_handle->GetURL());
if (writer_ && new_origin == writer_origin_)
return;
writer_.reset();
writer_origin_ = url::Origin();
if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
return;
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
DCHECK(profile);
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
DCHECK(data_store);
writer_ = data_store->GetWriterForOrigin(
new_origin,
ContentVisibilityToRCVisibility(web_contents()->GetVisibility()));
if (TabLoadTracker::Get()->GetLoadingState(web_contents()) ==
LoadingState::LOADED) {
writer_->NotifySiteLoaded();
}
writer_origin_ = new_origin;
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
Target: 1
Example 2:
Code: void GraphicsContext::releaseWindowsContext(HDC hdc, const IntRect& dstRect, bool supportAlphaBlend, bool mayCreateBitmap)
{
if (hdc) {
if (!dstRect.isEmpty()) {
HBITMAP bitmap = static_cast<HBITMAP>(GetCurrentObject(hdc, OBJ_BITMAP));
BITMAP info;
GetObject(bitmap, sizeof(info), &info);
ASSERT(info.bmBitsPixel == 32);
wxBitmap bmp;
bmp.SetHBITMAP(bitmap);
#if !wxCHECK_VERSION(2,9,0)
if (supportAlphaBlend)
bmp.UseAlpha();
#endif
m_data->context->DrawBitmap(bmp, dstRect.x(), dstRect.y(), supportAlphaBlend);
::DeleteObject(bitmap);
}
::DeleteDC(hdc);
}
}
Commit Message: Reviewed by Kevin Ollivier.
[wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support.
https://bugs.webkit.org/show_bug.cgi?id=60847
git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void TEMPLATE(process_block_dec)(decoder_info_t *decoder_info,int size,int yposY,int xposY,int sub)
{
int width = decoder_info->width;
int height = decoder_info->height;
stream_t *stream = decoder_info->stream;
frame_type_t frame_type = decoder_info->frame_info.frame_type;
int split_flag = 0;
if (yposY >= height || xposY >= width)
return;
int decode_this_size = (yposY + size <= height) && (xposY + size <= width);
int decode_rectangular_size = !decode_this_size && frame_type != I_FRAME;
int bit_start = stream->bitcnt;
int mode = MODE_SKIP;
block_context_t block_context;
TEMPLATE(find_block_contexts)(yposY, xposY, height, width, size, decoder_info->deblock_data, &block_context, decoder_info->use_block_contexts);
decoder_info->block_context = &block_context;
split_flag = decode_super_mode(decoder_info,size,decode_this_size);
mode = decoder_info->mode;
/* Read delta_qp and set block-level qp */
if (size == (1<<decoder_info->log2_sb_size) && (split_flag || mode != MODE_SKIP) && decoder_info->max_delta_qp > 0) {
/* Read delta_qp */
int delta_qp = read_delta_qp(stream);
int prev_qp;
if (yposY == 0 && xposY == 0)
prev_qp = decoder_info->frame_info.qp;
else
prev_qp = decoder_info->frame_info.qpb;
decoder_info->frame_info.qpb = prev_qp + delta_qp;
}
decoder_info->bit_count.super_mode[decoder_info->bit_count.stat_frame_type] += (stream->bitcnt - bit_start);
if (split_flag){
int new_size = size/2;
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+0*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+0*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+1*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+1*new_size,sub);
}
else if (decode_this_size || decode_rectangular_size){
decode_block(decoder_info,size,yposY,xposY,sub);
}
}
Commit Message: Fix possible stack overflows in decoder for illegal bit streams
Fixes CVE-2018-0429
A vulnerability in the Thor decoder (available at:
https://github.com/cisco/thor) could allow an authenticated, local
attacker to cause segmentation faults and stack overflows when using a
non-conformant Thor bitstream as input.
The vulnerability is due to lack of input validation when parsing the
bitstream. A successful exploit could allow the attacker to cause a
stack overflow and potentially inject and execute arbitrary code.
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __ip6_append_data(struct sock *sk,
struct flowi6 *fl6,
struct sk_buff_head *queue,
struct inet_cork *cork,
struct inet6_cork *v6_cork,
struct page_frag *pfrag,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
unsigned int flags, struct ipcm6_cookie *ipc6,
const struct sockcm_cookie *sockc)
{
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu;
int exthdrlen = 0;
int dst_exthdrlen = 0;
int hh_len;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
u32 tskey = 0;
struct rt6_info *rt = (struct rt6_info *)cork->dst;
struct ipv6_txoptions *opt = v6_cork->opt;
int csummode = CHECKSUM_NONE;
unsigned int maxnonfragsize, headersize;
skb = skb_peek_tail(queue);
if (!skb) {
exthdrlen = opt ? opt->opt_flen : 0;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
}
mtu = cork->fragsize;
orig_mtu = mtu;
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen -
sizeof(struct frag_hdr);
headersize = sizeof(struct ipv6hdr) +
(opt ? opt->opt_flen + opt->opt_nflen : 0) +
(dst_allfrag(&rt->dst) ?
sizeof(struct frag_hdr) : 0) +
rt->rt6i_nfheader_len;
if (cork->length + length > mtu - headersize && ipc6->dontfrag &&
(sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_RAW)) {
ipv6_local_rxpmtu(sk, fl6, mtu - headersize +
sizeof(struct ipv6hdr));
goto emsgsize;
}
if (ip6_sk_ignore_df(sk))
maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN;
else
maxnonfragsize = mtu;
if (cork->length + length > maxnonfragsize - headersize) {
emsgsize:
ipv6_local_error(sk, EMSGSIZE, fl6,
mtu - headersize +
sizeof(struct ipv6hdr));
return -EMSGSIZE;
}
/* CHECKSUM_PARTIAL only with no extension headers and when
* we are not going to fragment
*/
if (transhdrlen && sk->sk_protocol == IPPROTO_UDP &&
headersize == sizeof(struct ipv6hdr) &&
length <= mtu - headersize &&
!(flags & MSG_MORE) &&
rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM))
csummode = CHECKSUM_PARTIAL;
if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) {
sock_tx_timestamp(sk, sockc->tsflags, &tx_flags);
if (tx_flags & SKBTX_ANY_SW_TSTAMP &&
sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
tskey = sk->sk_tskey++;
}
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if ((((length + fragheaderlen) > mtu) ||
(skb && skb_is_gso(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) &&
(sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) {
err = ip6_ufo_append_data(sk, queue, getfrag, from, length,
hh_len, fragheaderlen, exthdrlen,
transhdrlen, mtu, flags, fl6);
if (err)
goto error;
return 0;
}
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (!skb || !skb_prev)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
orig_mtu);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(!skb))
err = -ENOBUFS;
}
if (!skb)
goto error;
/*
* Fill in the control structures
*/
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = csummode;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
/* Only the initial fragment is time stamped */
skb_shinfo(skb)->tx_flags = tx_flags;
tx_flags = 0;
skb_shinfo(skb)->tskey = tskey;
tskey = 0;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
if ((flags & MSG_CONFIRM) && !skb_prev)
skb_set_dst_pending_confirm(skb, 1);
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
Commit Message: ipv6: fix out of bound writes in __ip6_append_data()
Andrey Konovalov and [email protected] reported crashes caused by
one skb shared_info being overwritten from __ip6_append_data()
Andrey program lead to following state :
copy -4200 datalen 2000 fraglen 2040
maxfraglen 2040 alloclen 2048 transhdrlen 0 offset 0 fraggap 6200
The skb_copy_and_csum_bits(skb_prev, maxfraglen, data + transhdrlen,
fraggap, 0); is overwriting skb->head and skb_shared_info
Since we apparently detect this rare condition too late, move the
code earlier to even avoid allocating skb and risking crashes.
Once again, many thanks to Andrey and syzkaller team.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Reported-by: <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static unsigned hash(const G* key)
{
return static_cast<unsigned>(unsafeHandleFromRawValue(key)->GetIdentityHash());
}
Commit Message: Replace further questionable HashMap::add usages in bindings
BUG=390928
[email protected]
Review URL: https://codereview.chromium.org/411273002
git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool PepperRendererConnection::OnMessageReceived(const IPC::Message& msg) {
if (in_process_host_->GetPpapiHost()->OnMessageReceived(msg))
return true;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PepperRendererConnection, msg)
IPC_MESSAGE_HANDLER(PpapiHostMsg_CreateResourceHostsFromHost,
OnMsgCreateResourceHostsFromHost)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidCreateInProcessInstance,
OnMsgDidCreateInProcessInstance)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidDeleteInProcessInstance,
OnMsgDidDeleteInProcessInstance)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Validate in-process plugin instance messages.
Bug: 733548, 733549
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba
Reviewed-on: https://chromium-review.googlesource.com/538908
Commit-Queue: Bill Budge <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480696}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
Commit Message: Avoid sharing process for blob URLs with null origin.
Previously, when a frame with a unique origin, such as from a data
URL, created a blob URL, the blob URL looked like blob:null/guid and
resulted in a site URL of "blob:" when navigated to. This incorrectly
allowed all such blob URLs to share a process, even if they were
created by different sites.
This CL changes the site URL assigned in such cases to be the full
blob URL, which includes the GUID. This avoids process sharing for
all blob URLs with unique origins.
This fix is conservative in the sense that it would also isolate
different blob URLs created by the same unique origin from each other.
This case isn't expected to be common, so it's unlikely to affect
process count. There's ongoing work to maintain a GUID for unique
origins, so longer-term, we could try using that to track down the
creator and potentially use that GUID in the site URL instead of the
blob URL's GUID, to avoid unnecessary process isolation in scenarios
like this.
Note that as part of this, we discovered a bug where data URLs aren't
able to script blob URLs that they create: https://crbug.com/865254.
This scripting bug should be fixed independently of this CL, and as
far as we can tell, this CL doesn't regress scripting cases like this
further.
Bug: 863623
Change-Id: Ib50407adbba3d5ee0cf6d72d3df7f8d8f24684ee
Reviewed-on: https://chromium-review.googlesource.com/1142389
Commit-Queue: Alex Moshchuk <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#576318}
CWE ID: CWE-285
Target: 1
Example 2:
Code: DevToolsDockSide DevToolsWindow::GetDockSideFromPrefs(Profile* profile) {
std::string dock_side =
profile->GetPrefs()->GetString(prefs::kDevToolsDockSide);
const char kOldPrefBottom[] = "bottom";
const char kOldPrefRight[] = "right";
if ((dock_side == kOldPrefBottom) || (dock_side == kOldPrefRight)) {
if (!profile->GetPrefs()->GetBoolean(prefs::kDevToolsOpenDocked))
return DEVTOOLS_DOCK_SIDE_UNDOCKED;
return (dock_side == kOldPrefBottom) ?
DEVTOOLS_DOCK_SIDE_BOTTOM : DEVTOOLS_DOCK_SIDE_RIGHT;
}
if (dock_side == kPrefUndocked)
return DEVTOOLS_DOCK_SIDE_UNDOCKED;
if (dock_side == kPrefRight)
return DEVTOOLS_DOCK_SIDE_RIGHT;
return DEVTOOLS_DOCK_SIDE_BOTTOM;
}
Commit Message: DevTools: handle devtools renderer unresponsiveness during beforeunload event interception
This patch fixes the crash which happenes under the following conditions:
1. DevTools window is in undocked state
2. DevTools renderer is unresponsive
3. User attempts to close inspected page
BUG=322380
Review URL: https://codereview.chromium.org/84883002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@237611 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SessionStore::Factory SessionStore::CreateFactory(
SyncSessionsClient* sessions_client,
const RestoredForeignTabCallback& restored_foreign_tab_callback) {
auto factory = std::make_unique<FactoryImpl>(sessions_client,
restored_foreign_tab_callback);
return base::BindRepeating(&FactoryImpl::Create, std::move(factory));
}
Commit Message: Add trace event to sync_sessions::OnReadAllMetadata()
It is likely a cause of janks on UI thread on Android.
Add a trace event to get metrics about the duration.
BUG=902203
Change-Id: I4c4e9c2a20790264b982007ea7ee88ddfa7b972c
Reviewed-on: https://chromium-review.googlesource.com/c/1319369
Reviewed-by: Mikel Astiz <[email protected]>
Commit-Queue: ssid <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606104}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
/* validate the offset, and the data for the two
* values we're about to read
*/
if (offset + 6 > font->length)
{
gs_warn("name table byte offset invalid");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (stringoffset + offset > font->length
|| offset + 6 + count * 12 > font->length)
{
gs_warn("name table invalid");
return;
}
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
return;
}
for (i = 0; i < count; i++)
{
byte *record = namedata + 6 + i * 12;
int pid = u16(record + 0);
int eid = u16(record + 2);
int langid = u16(record + 4);
int nameid = u16(record + 6);
length = u16(record + 8);
offset = u16(record + 10);
/* Full font name or postscript name */
if (nameid == 4 || nameid == 6)
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: GooString *FlateStream::getPSFilter(int psLevel, const char *indent) {
GooString *s;
if (psLevel < 3 || pred) {
return NULL;
}
if (!(s = str->getPSFilter(psLevel, indent))) {
return NULL;
}
s->append(indent)->append("<< >> /FlateDecode filter\n");
return s;
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ptrace_check_attach(struct task_struct *child, bool ignore_state)
{
int ret = -ESRCH;
/*
* We take the read lock around doing both checks to close a
* possible race where someone else was tracing our child and
* detached between these two checks. After this locked check,
* we are sure that this is our traced child and that can only
* be changed by us so it's not changing right after this.
*/
read_lock(&tasklist_lock);
if ((child->ptrace & PT_PTRACED) && child->parent == current) {
/*
* child->sighand can't be NULL, release_task()
* does ptrace_unlink() before __exit_signal().
*/
spin_lock_irq(&child->sighand->siglock);
WARN_ON_ONCE(task_is_stopped(child));
if (ignore_state || (task_is_traced(child) &&
!(child->jobctl & JOBCTL_LISTENING)))
ret = 0;
spin_unlock_irq(&child->sighand->siglock);
}
read_unlock(&tasklist_lock);
if (!ret && !ignore_state)
ret = wait_task_inactive(child, TASK_TRACED) ? 0 : -ESRCH;
/* All systems go.. */
return ret;
}
Commit Message: ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL
putreg() assumes that the tracee is not running and pt_regs_access() can
safely play with its stack. However a killed tracee can return from
ptrace_stop() to the low-level asm code and do RESTORE_REST, this means
that debugger can actually read/modify the kernel stack until the tracee
does SAVE_REST again.
set_task_blockstep() can race with SIGKILL too and in some sense this
race is even worse, the very fact the tracee can be woken up breaks the
logic.
As Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace()
call, this ensures that nobody can ever wakeup the tracee while the
debugger looks at it. Not only this fixes the mentioned problems, we
can do some cleanups/simplifications in arch_ptrace() paths.
Probably ptrace_unfreeze_traced() needs more callers, for example it
makes sense to make the tracee killable for oom-killer before
access_process_vm().
While at it, add the comment into may_ptrace_stop() to explain why
ptrace_stop() still can't rely on SIGKILL and signal_pending_state().
Reported-by: Salman Qazi <[email protected]>
Reported-by: Suleiman Souhlal <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: print_decnet_ctlmsg(netdissect_options *ndo,
register const union routehdr *rhp, u_int length,
u_int caplen)
{
int mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
register const union controlmsg *cmp = (const union controlmsg *)rhp;
int src, dst, info, blksize, eco, ueco, hello, other, vers;
etheraddr srcea, rtea;
int priority;
const char *rhpx = (const char *)rhp;
int ret;
switch (mflags & RMF_CTLMASK) {
case RMF_INIT:
ND_PRINT((ndo, "init "));
if (length < sizeof(struct initmsg))
goto trunc;
ND_TCHECK(cmp->cm_init);
src = EXTRACT_LE_16BITS(cmp->cm_init.in_src);
info = EXTRACT_LE_8BITS(cmp->cm_init.in_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_init.in_blksize);
vers = EXTRACT_LE_8BITS(cmp->cm_init.in_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_init.in_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_init.in_ueco);
hello = EXTRACT_LE_16BITS(cmp->cm_init.in_hello);
print_t_info(ndo, info);
ND_PRINT((ndo,
"src %sblksize %d vers %d eco %d ueco %d hello %d",
dnaddr_string(ndo, src), blksize, vers, eco, ueco,
hello));
ret = 1;
break;
case RMF_VER:
ND_PRINT((ndo, "verification "));
if (length < sizeof(struct verifmsg))
goto trunc;
ND_TCHECK(cmp->cm_ver);
src = EXTRACT_LE_16BITS(cmp->cm_ver.ve_src);
other = EXTRACT_LE_8BITS(cmp->cm_ver.ve_fcnval);
ND_PRINT((ndo, "src %s fcnval %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_TEST:
ND_PRINT((ndo, "test "));
if (length < sizeof(struct testmsg))
goto trunc;
ND_TCHECK(cmp->cm_test);
src = EXTRACT_LE_16BITS(cmp->cm_test.te_src);
other = EXTRACT_LE_8BITS(cmp->cm_test.te_data);
ND_PRINT((ndo, "src %s data %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_L1ROUT:
ND_PRINT((ndo, "lev-1-routing "));
if (length < sizeof(struct l1rout))
goto trunc;
ND_TCHECK(cmp->cm_l1rou);
src = EXTRACT_LE_16BITS(cmp->cm_l1rou.r1_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l1_routes(ndo, &(rhpx[sizeof(struct l1rout)]),
length - sizeof(struct l1rout));
break;
case RMF_L2ROUT:
ND_PRINT((ndo, "lev-2-routing "));
if (length < sizeof(struct l2rout))
goto trunc;
ND_TCHECK(cmp->cm_l2rout);
src = EXTRACT_LE_16BITS(cmp->cm_l2rout.r2_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l2_routes(ndo, &(rhpx[sizeof(struct l2rout)]),
length - sizeof(struct l2rout));
break;
case RMF_RHELLO:
ND_PRINT((ndo, "router-hello "));
if (length < sizeof(struct rhellomsg))
goto trunc;
ND_TCHECK(cmp->cm_rhello);
vers = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_rhello.rh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_blksize);
priority = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_priority);
hello = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_hello);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d pri %d hello %d",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, priority, hello));
ret = print_elist(&(rhpx[sizeof(struct rhellomsg)]),
length - sizeof(struct rhellomsg));
break;
case RMF_EHELLO:
ND_PRINT((ndo, "endnode-hello "));
if (length < sizeof(struct ehellomsg))
goto trunc;
ND_TCHECK(cmp->cm_ehello);
vers = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_ehello.eh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_blksize);
/*seed*/
memcpy((char *)&rtea, (const char *)&(cmp->cm_ehello.eh_router),
sizeof(rtea));
dst = EXTRACT_LE_16BITS(rtea.dne_remote.dne_nodeaddr);
hello = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_hello);
other = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_data);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d rtr %s hello %d data %o",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, dnaddr_string(ndo, dst), hello, other));
ret = 1;
break;
default:
ND_PRINT((ndo, "unknown control message"));
ND_DEFAULTPRINT((const u_char *)rhp, min(length, caplen));
ret = 1;
break;
}
return (ret);
trunc:
return (0);
}
Commit Message: CVE-2017-12899/DECnet: Fix bounds checking.
If we're skipping over padding before the *real* flags, check whether
the real flags are in the captured data before fetching it. This fixes
a buffer over-read discovered by Kamil Frankowicz.
Note one place where we don't need to do bounds checking as it's already
been done.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: void SVGImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, blink::WebBlendMode blendMode)
{
if (!m_page)
return;
GraphicsContextStateSaver stateSaver(*context);
context->setCompositeOperation(compositeOp, blendMode);
context->clip(enclosingIntRect(dstRect));
bool compositingRequiresTransparencyLayer = compositeOp != CompositeSourceOver || blendMode != blink::WebBlendModeNormal;
float opacity = context->getNormalizedAlpha() / 255.f;
bool requiresTransparencyLayer = compositingRequiresTransparencyLayer || opacity < 1;
if (requiresTransparencyLayer) {
context->beginTransparencyLayer(opacity);
if (compositingRequiresTransparencyLayer)
context->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
}
FloatSize scale(dstRect.width() / srcRect.width(), dstRect.height() / srcRect.height());
FloatSize topLeftOffset(srcRect.location().x() * scale.width(), srcRect.location().y() * scale.height());
FloatPoint destOffset = dstRect.location() - topLeftOffset;
context->translate(destOffset.x(), destOffset.y());
context->scale(scale);
FrameView* view = frameView();
view->resize(containerSize());
if (view->needsLayout())
view->layout();
view->paint(context, enclosingIntRect(srcRect));
if (requiresTransparencyLayer)
context->endLayer();
stateSaver.restore();
if (imageObserver())
imageObserver()->didDraw(this);
}
Commit Message: Fix crash when resizing a view destroys the render tree
This is a simple fix for not holding a renderer across FrameView
resizes. Calling view->resize() can destroy renderers so this patch
updates SVGImage::setContainerSize to query the renderer after the
resize is complete. A similar issue does not exist for the dom tree
which is not destroyed.
BUG=344492
Review URL: https://codereview.chromium.org/178043006
git-svn-id: svn://svn.chromium.org/blink/trunk@168113 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint16 *wp = (uint16*) cp0;
tmsize_t wc = cc/2;
assert((cc%(2*stride))==0);
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--)
wc -= stride;
} while (wc > 0);
}
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int udp_push_pending_frames(struct sock *sk)
{
struct udp_sock *up = udp_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
struct sk_buff *skb;
int err = 0;
skb = ip_finish_skb(sk, fl4);
if (!skb)
goto out;
err = udp_send_skb(skb, fl4);
out:
up->len = 0;
up->pending = 0;
return err;
}
Commit Message: ipv6: call udp_push_pending_frames when uncorking a socket with AF_INET pending data
We accidentally call down to ip6_push_pending_frames when uncorking
pending AF_INET data on a ipv6 socket. This results in the following
splat (from Dave Jones):
skbuff: skb_under_panic: text:ffffffff816765f6 len:48 put:40 head:ffff88013deb6df0 data:ffff88013deb6dec tail:0x2c end:0xc0 dev:<NULL>
------------[ cut here ]------------
kernel BUG at net/core/skbuff.c:126!
invalid opcode: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC
Modules linked in: dccp_ipv4 dccp 8021q garp bridge stp dlci mpoa snd_seq_dummy sctp fuse hidp tun bnep nfnetlink scsi_transport_iscsi rfcomm can_raw can_bcm af_802154 appletalk caif_socket can caif ipt_ULOG x25 rose af_key pppoe pppox ipx phonet irda llc2 ppp_generic slhc p8023 psnap p8022 llc crc_ccitt atm bluetooth
+netrom ax25 nfc rfkill rds af_rxrpc coretemp hwmon kvm_intel kvm crc32c_intel snd_hda_codec_realtek ghash_clmulni_intel microcode pcspkr snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep usb_debug snd_seq snd_seq_device snd_pcm e1000e snd_page_alloc snd_timer ptp snd pps_core soundcore xfs libcrc32c
CPU: 2 PID: 8095 Comm: trinity-child2 Not tainted 3.10.0-rc7+ #37
task: ffff8801f52c2520 ti: ffff8801e6430000 task.ti: ffff8801e6430000
RIP: 0010:[<ffffffff816e759c>] [<ffffffff816e759c>] skb_panic+0x63/0x65
RSP: 0018:ffff8801e6431de8 EFLAGS: 00010282
RAX: 0000000000000086 RBX: ffff8802353d3cc0 RCX: 0000000000000006
RDX: 0000000000003b90 RSI: ffff8801f52c2ca0 RDI: ffff8801f52c2520
RBP: ffff8801e6431e08 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000001 R11: 0000000000000001 R12: ffff88022ea0c800
R13: ffff88022ea0cdf8 R14: ffff8802353ecb40 R15: ffffffff81cc7800
FS: 00007f5720a10740(0000) GS:ffff880244c00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000005862000 CR3: 000000022843c000 CR4: 00000000001407e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000600
Stack:
ffff88013deb6dec 000000000000002c 00000000000000c0 ffffffff81a3f6e4
ffff8801e6431e18 ffffffff8159a9aa ffff8801e6431e90 ffffffff816765f6
ffffffff810b756b 0000000700000002 ffff8801e6431e40 0000fea9292aa8c0
Call Trace:
[<ffffffff8159a9aa>] skb_push+0x3a/0x40
[<ffffffff816765f6>] ip6_push_pending_frames+0x1f6/0x4d0
[<ffffffff810b756b>] ? mark_held_locks+0xbb/0x140
[<ffffffff81694919>] udp_v6_push_pending_frames+0x2b9/0x3d0
[<ffffffff81694660>] ? udplite_getfrag+0x20/0x20
[<ffffffff8162092a>] udp_lib_setsockopt+0x1aa/0x1f0
[<ffffffff811cc5e7>] ? fget_light+0x387/0x4f0
[<ffffffff816958a4>] udpv6_setsockopt+0x34/0x40
[<ffffffff815949f4>] sock_common_setsockopt+0x14/0x20
[<ffffffff81593c31>] SyS_setsockopt+0x71/0xd0
[<ffffffff816f5d54>] tracesys+0xdd/0xe2
Code: 00 00 48 89 44 24 10 8b 87 d8 00 00 00 48 89 44 24 08 48 8b 87 e8 00 00 00 48 c7 c7 c0 04 aa 81 48 89 04 24 31 c0 e8 e1 7e ff ff <0f> 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55
RIP [<ffffffff816e759c>] skb_panic+0x63/0x65
RSP <ffff8801e6431de8>
This patch adds a check if the pending data is of address family AF_INET
and directly calls udp_push_ending_frames from udp_v6_push_pending_frames
if that is the case.
This bug was found by Dave Jones with trinity.
(Also move the initialization of fl6 below the AF_INET check, even if
not strictly necessary.)
Cc: Dave Jones <[email protected]>
Cc: YOSHIFUJI Hideaki <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: SProcXFixesShowCursor(ClientPtr client)
{
REQUEST(xXFixesShowCursorReq);
swaps(&stuff->length);
REQUEST_SIZE_MATCH(xXFixesShowCursorReq);
swapl(&stuff->window);
return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long join_session_keyring(const char *name)
{
const struct cred *old;
struct cred *new;
struct key *keyring;
long ret, serial;
new = prepare_creds();
if (!new)
return -ENOMEM;
old = current_cred();
/* if no name is provided, install an anonymous keyring */
if (!name) {
ret = install_session_keyring_to_cred(new, NULL);
if (ret < 0)
goto error;
serial = new->session_keyring->serial;
ret = commit_creds(new);
if (ret == 0)
ret = serial;
goto okay;
}
/* allow the user to join or create a named keyring */
mutex_lock(&key_session_mutex);
/* look for an existing keyring of this name */
keyring = find_keyring_by_name(name, false);
if (PTR_ERR(keyring) == -ENOKEY) {
/* not found - try and create a new one */
keyring = keyring_alloc(
name, old->uid, old->gid, old,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK,
KEY_ALLOC_IN_QUOTA, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
}
} else if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
} else if (keyring == new->session_keyring) {
ret = 0;
goto error2;
}
/* we've got a keyring - now to install it */
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0)
goto error2;
commit_creds(new);
mutex_unlock(&key_session_mutex);
ret = keyring->serial;
key_put(keyring);
okay:
return ret;
error2:
mutex_unlock(&key_session_mutex);
error:
abort_creds(new);
return ret;
}
Commit Message: KEYS: Fix keyring ref leak in join_session_keyring()
This fixes CVE-2016-0728.
If a thread is asked to join as a session keyring the keyring that's already
set as its session, we leak a keyring reference.
This can be tested with the following program:
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <keyutils.h>
int main(int argc, const char *argv[])
{
int i = 0;
key_serial_t serial;
serial = keyctl(KEYCTL_JOIN_SESSION_KEYRING,
"leaked-keyring");
if (serial < 0) {
perror("keyctl");
return -1;
}
if (keyctl(KEYCTL_SETPERM, serial,
KEY_POS_ALL | KEY_USR_ALL) < 0) {
perror("keyctl");
return -1;
}
for (i = 0; i < 100; i++) {
serial = keyctl(KEYCTL_JOIN_SESSION_KEYRING,
"leaked-keyring");
if (serial < 0) {
perror("keyctl");
return -1;
}
}
return 0;
}
If, after the program has run, there something like the following line in
/proc/keys:
3f3d898f I--Q--- 100 perm 3f3f0000 0 0 keyring leaked-keyring: empty
with a usage count of 100 * the number of times the program has been run,
then the kernel is malfunctioning. If leaked-keyring has zero usages or
has been garbage collected, then the problem is fixed.
Reported-by: Yevgeny Pats <[email protected]>
Signed-off-by: David Howells <[email protected]>
Acked-by: Don Zickus <[email protected]>
Acked-by: Prarit Bhargava <[email protected]>
Acked-by: Jarod Wilson <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: gss_process_context_token (minor_status,
context_handle,
token_buffer)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t token_buffer;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
if (minor_status == NULL)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
*minor_status = 0;
if (context_handle == GSS_C_NO_CONTEXT)
return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);
if (token_buffer == GSS_C_NO_BUFFER)
return (GSS_S_CALL_INACCESSIBLE_READ);
if (GSS_EMPTY_BUFFER(token_buffer))
return (GSS_S_CALL_INACCESSIBLE_READ);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_process_context_token) {
status = mech->gss_process_context_token(
minor_status,
ctx->internal_ctx_id,
token_buffer);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
return (GSS_S_BAD_MECH);
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415
Target: 1
Example 2:
Code: PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
{
if (!context)
return 0;
Node* styleNode = context->firstNode();
if (!styleNode) {
styleNode = context->startPosition().deprecatedNode();
if (!styleNode)
return 0;
}
Document* document = styleNode->document();
RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
if (text.isEmpty())
return fragment.release();
String string = text;
string.replace("\r\n", "\n");
string.replace('\r', '\n');
ExceptionCode ec = 0;
RenderObject* renderer = styleNode->renderer();
if (renderer && renderer->style()->preserveNewline()) {
fragment->appendChild(document->createTextNode(string), ec);
ASSERT(!ec);
if (string.endsWith('\n')) {
RefPtr<Element> element = createBreakElement(document);
element->setAttribute(classAttr, AppleInterchangeNewline);
fragment->appendChild(element.release(), ec);
ASSERT(!ec);
}
return fragment.release();
}
if (string.find('\n') == notFound) {
fillContainerFromString(fragment.get(), string);
return fragment.release();
}
Node* blockNode = enclosingBlock(context->firstNode());
Element* block = static_cast<Element*>(blockNode);
bool useClonesOfEnclosingBlock = blockNode
&& blockNode->isElementNode()
&& !block->hasTagName(bodyTag)
&& !block->hasTagName(htmlTag)
&& block != editableRootForPosition(context->startPosition());
bool useLineBreak = enclosingTextFormControl(context->startPosition());
Vector<String> list;
string.split('\n', true, list); // true gets us empty strings in the list
size_t numLines = list.size();
for (size_t i = 0; i < numLines; ++i) {
const String& s = list[i];
RefPtr<Element> element;
if (s.isEmpty() && i + 1 == numLines) {
element = createBreakElement(document);
element->setAttribute(classAttr, AppleInterchangeNewline);
} else if (useLineBreak) {
element = createBreakElement(document);
fillContainerFromString(fragment.get(), s);
} else {
if (useClonesOfEnclosingBlock)
element = block->cloneElementWithoutChildren();
else
element = createDefaultParagraphElement(document);
fillContainerFromString(element.get(), s);
}
fragment->appendChild(element.release(), ec);
ASSERT(!ec);
}
return fragment.release();
}
Commit Message: There are too many poorly named functions to create a fragment from markup
https://bugs.webkit.org/show_bug.cgi?id=87339
Reviewed by Eric Seidel.
Source/WebCore:
Moved all functions that create a fragment from markup to markup.h/cpp.
There should be no behavioral change.
* dom/Range.cpp:
(WebCore::Range::createContextualFragment):
* dom/Range.h: Removed createDocumentFragmentForElement.
* dom/ShadowRoot.cpp:
(WebCore::ShadowRoot::setInnerHTML):
* editing/markup.cpp:
(WebCore::createFragmentFromMarkup):
(WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource.
(WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor.
(WebCore::removeElementPreservingChildren): Moved from Range.
(WebCore::createContextualFragment): Ditto.
* editing/markup.h:
* html/HTMLElement.cpp:
(WebCore::HTMLElement::setInnerHTML):
(WebCore::HTMLElement::setOuterHTML):
(WebCore::HTMLElement::insertAdjacentHTML):
* inspector/DOMPatchSupport.cpp:
(WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using
one of the functions listed in markup.h
* xml/XSLTProcessor.cpp:
(WebCore::XSLTProcessor::transformToFragment):
Source/WebKit/qt:
Replace calls to Range::createDocumentFragmentForElement by calls to
createContextualDocumentFragment.
* Api/qwebelement.cpp:
(QWebElement::appendInside):
(QWebElement::prependInside):
(QWebElement::prependOutside):
(QWebElement::appendOutside):
(QWebElement::encloseContentsWith):
(QWebElement::encloseWith):
git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MaybeRestoreConnections() {
if (IBusConnectionsAreAlive()) {
return;
}
MaybeCreateIBus();
MaybeRestoreIBusConfig();
if (IBusConnectionsAreAlive()) {
ConnectPanelServiceSignals();
if (connection_change_handler_) {
LOG(INFO) << "Notifying Chrome that IBus is ready.";
connection_change_handler_(language_library_, true);
}
}
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void destroy_super(struct super_block *s)
{
int i;
list_lru_destroy(&s->s_dentry_lru);
list_lru_destroy(&s->s_inode_lru);
#ifdef CONFIG_SMP
free_percpu(s->s_files);
#endif
for (i = 0; i < SB_FREEZE_LEVELS; i++)
percpu_counter_destroy(&s->s_writers.counter[i]);
security_sb_free(s);
WARN_ON(!list_empty(&s->s_mounts));
kfree(s->s_subtype);
kfree(s->s_options);
kfree_rcu(s, rcu);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17
Target: 1
Example 2:
Code: bool ChromeContentBrowserClient::IsRendererDebugURLBlacklisted(
const GURL& url,
content::BrowserContext* context) {
PolicyBlacklistService* service =
PolicyBlacklistFactory::GetForBrowserContext(context);
using URLBlacklistState = policy::URLBlacklist::URLBlacklistState;
URLBlacklistState blacklist_state = service->GetURLBlacklistState(url);
return blacklist_state == URLBlacklistState::URL_IN_BLACKLIST;
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void s_wrpkt(Ssh ssh, struct Packet *pkt)
{
int len, backlog, offset;
len = s_wrpkt_prepare(ssh, pkt, &offset);
backlog = s_write(ssh, pkt->data + offset, len);
if (backlog > SSH_MAX_BACKLOG)
ssh_throttle_all(ssh, 1, backlog);
ssh_free_packet(pkt);
}
Commit Message:
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) {
debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
int ret = 400;
BUFFER *dimensions = NULL;
buffer_flush(w->response.data);
char *google_version = "0.6",
*google_reqId = "0",
*google_sig = "0",
*google_out = "json",
*responseHandler = NULL,
*outFileName = NULL;
time_t last_timestamp_in_data = 0, google_timestamp = 0;
char *chart = NULL
, *before_str = NULL
, *after_str = NULL
, *group_time_str = NULL
, *points_str = NULL;
int group = RRDR_GROUPING_AVERAGE;
uint32_t format = DATASOURCE_JSON;
uint32_t options = 0x00000000;
while(url) {
char *value = mystrsep(&url, "?&");
if(!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
if(!strcmp(name, "chart")) chart = value;
else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
if(!dimensions) dimensions = buffer_create(100);
buffer_strcat(dimensions, "|");
buffer_strcat(dimensions, value);
}
else if(!strcmp(name, "after")) after_str = value;
else if(!strcmp(name, "before")) before_str = value;
else if(!strcmp(name, "points")) points_str = value;
else if(!strcmp(name, "gtime")) group_time_str = value;
else if(!strcmp(name, "group")) {
group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE);
}
else if(!strcmp(name, "format")) {
format = web_client_api_request_v1_data_format(value);
}
else if(!strcmp(name, "options")) {
options |= web_client_api_request_v1_data_options(value);
}
else if(!strcmp(name, "callback")) {
responseHandler = value;
}
else if(!strcmp(name, "filename")) {
outFileName = value;
}
else if(!strcmp(name, "tqx")) {
char *tqx_name, *tqx_value;
while(value) {
tqx_value = mystrsep(&value, ";");
if(!tqx_value || !*tqx_value) continue;
tqx_name = mystrsep(&tqx_value, ":");
if(!tqx_name || !*tqx_name) continue;
if(!tqx_value || !*tqx_value) continue;
if(!strcmp(tqx_name, "version"))
google_version = tqx_value;
else if(!strcmp(tqx_name, "reqId"))
google_reqId = tqx_value;
else if(!strcmp(tqx_name, "sig")) {
google_sig = tqx_value;
google_timestamp = strtoul(google_sig, NULL, 0);
}
else if(!strcmp(tqx_name, "out")) {
google_out = tqx_value;
format = web_client_api_request_v1_data_google_format(google_out);
}
else if(!strcmp(tqx_name, "responseHandler"))
responseHandler = tqx_value;
else if(!strcmp(tqx_name, "outFileName"))
outFileName = tqx_value;
}
}
}
if(!chart || !*chart) {
buffer_sprintf(w->response.data, "No chart id is given at the request.");
goto cleanup;
}
RRDSET *st = rrdset_find(host, chart);
if(!st) st = rrdset_find_byname(host, chart);
if(!st) {
buffer_strcat(w->response.data, "Chart is not found: ");
buffer_strcat_htmlescape(w->response.data, chart);
ret = 404;
goto cleanup;
}
st->last_accessed_time = now_realtime_sec();
long long before = (before_str && *before_str)?str2l(before_str):0;
long long after = (after_str && *after_str) ?str2l(after_str):0;
int points = (points_str && *points_str)?str2i(points_str):0;
long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0;
debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'"
, w->id
, chart
, (dimensions)?buffer_tostring(dimensions):""
, after
, before
, points
, group
, format
, options
);
if(outFileName && *outFileName) {
buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
}
if(format == DATASOURCE_DATATABLE_JSONP) {
if(responseHandler == NULL)
responseHandler = "google.visualization.Query.setResponse";
debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
}
else if(format == DATASOURCE_JSONP) {
if(responseHandler == NULL)
responseHandler = "callback";
buffer_strcat(w->response.data, responseHandler);
buffer_strcat(w->response.data, "(");
}
ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time
, options, &last_timestamp_in_data);
if(format == DATASOURCE_DATATABLE_JSONP) {
if(google_timestamp < last_timestamp_in_data)
buffer_strcat(w->response.data, "});");
else {
buffer_flush(w->response.data);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
responseHandler, google_version, google_reqId);
}
}
else if(format == DATASOURCE_JSONP)
buffer_strcat(w->response.data, ");");
cleanup:
buffer_free(dimensions);
return ret;
}
Commit Message: fixed vulnerabilities identified by red4sec.com (#4521)
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int visor_calc_num_ports(struct usb_serial *serial)
{
int num_ports = (int)(long)(usb_get_serial_data(serial));
if (num_ports)
usb_set_serial_data(serial, NULL);
return num_ports;
}
Commit Message: USB: visor: fix null-deref at probe
Fix null-pointer dereference at probe should a (malicious) Treo device
lack the expected endpoints.
Specifically, the Treo port-setup hack was dereferencing the bulk-in and
interrupt-in urbs without first making sure they had been allocated by
core.
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: OMX_ERRORTYPE SoftAACEncoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ShowExtensionInstallDialogImpl(
ExtensionInstallPromptShowParams* show_params,
ExtensionInstallPrompt::Delegate* delegate,
scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
ExtensionInstallDialogView* dialog =
new ExtensionInstallDialogView(show_params->profile(),
show_params->GetParentWebContents(),
delegate,
prompt);
constrained_window::CreateBrowserModalDialogViews(
dialog, show_params->GetParentWindow())->Show();
}
Commit Message: Make the webstore inline install dialog be tab-modal
Also clean up a few minor lint errors while I'm in here.
BUG=550047
Review URL: https://codereview.chromium.org/1496033003
Cr-Commit-Position: refs/heads/master@{#363925}
CWE ID: CWE-17
Target: 1
Example 2:
Code: void ChromeClientImpl::InvalidateRect(const IntRect& update_rect) {
if (!update_rect.IsEmpty())
web_view_->InvalidateRect(update_rect);
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int hns_rcb_set_tx_coalesced_frames(
struct rcb_common_cb *rcb_common, u32 port_idx, u32 coalesced_frames)
{
u32 old_waterline =
hns_rcb_get_tx_coalesced_frames(rcb_common, port_idx);
u64 reg;
if (coalesced_frames == old_waterline)
return 0;
if (coalesced_frames != 1) {
dev_err(rcb_common->dsaf_dev->dev,
"error: not support tx coalesce_frames setting!\n");
return -EINVAL;
}
reg = RCB_CFG_PKTLINE_REG + (port_idx + HNS_RCB_TX_PKTLINE_OFFSET) * 4;
dsaf_write_dev(rcb_common, reg, coalesced_frames);
return 0;
}
Commit Message: net: hns: fix ethtool_get_strings overflow in hns driver
hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated
is not enough for ethtool_get_strings(), which will cause random memory
corruption.
When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the
the following can be observed without this patch:
[ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80
[ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070.
[ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70)
[ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk
[ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k
[ 43.115218] Next obj: start=ffff801fb0b69098, len=80
[ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b.
[ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38)
[ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_
[ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai
Signed-off-by: Timmy Li <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: scoped_ptr<cc::CompositorFrame> SynchronousCompositorImpl::DemandDrawHw(
gfx::Size surface_size,
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
DCHECK(CalledOnValidThread());
DCHECK(output_surface_);
DCHECK(begin_frame_source_);
scoped_ptr<cc::CompositorFrame> frame =
output_surface_->DemandDrawHw(surface_size,
transform,
viewport,
clip,
viewport_rect_for_tile_priority,
transform_for_tile_priority);
if (frame.get())
UpdateFrameMetaData(frame->metadata);
return frame.Pass();
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void adev_close_input_stream(struct audio_hw_device *dev,
struct audio_stream_in *stream)
{
struct audio_device *adev = (struct audio_device *)dev;
struct stream_in *in = (struct stream_in*)stream;
ALOGV("%s", __func__);
/* prevent concurrent out_set_parameters, or out_write from standby */
pthread_mutex_lock(&adev->lock_inputs);
in_standby_l(in);
pthread_mutex_destroy(&in->lock);
pthread_mutex_destroy(&in->pre_lock);
free(in->proc_buf_out);
#ifdef PREPROCESSING_ENABLED
int i;
for (i=0; i<in->num_preprocessors; i++) {
free(in->preprocessors[i].channel_configs);
}
if (in->read_buf) {
free(in->read_buf);
}
if (in->proc_buf_in) {
free(in->proc_buf_in);
}
if (in->resampler) {
release_resampler(in->resampler);
}
#endif
free(stream);
pthread_mutex_unlock(&adev->lock_inputs);
return;
}
Commit Message: Fix audio record pre-processing
proc_buf_out consistently initialized.
intermediate scratch buffers consistently initialized.
prevent read failure from overwriting memory.
Test: POC, CTS, camera record
Bug: 62873231
Change-Id: Ie26e12a419a5819c1c5c3a0bcf1876d6d7aca686
(cherry picked from commit 6d7b330c27efba944817e647955da48e54fd74eb)
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int rpc_type_of_NPPVariable(int variable)
{
int type;
switch (variable) {
case NPPVpluginNameString:
case NPPVpluginDescriptionString:
case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000
type = RPC_TYPE_STRING;
break;
case NPPVpluginWindowSize:
case NPPVpluginTimerInterval:
type = RPC_TYPE_INT32;
break;
case NPPVpluginNeedsXEmbed:
case NPPVpluginWindowBool:
case NPPVpluginTransparentBool:
case NPPVjavascriptPushCallerBool:
case NPPVpluginKeepLibraryInMemory:
type = RPC_TYPE_BOOLEAN;
break;
case NPPVpluginScriptableNPObject:
type = RPC_TYPE_NP_OBJECT;
break;
default:
type = RPC_ERROR_GENERIC;
break;
}
return type;
}
Commit Message: Support all the new variables added
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct vqp_common_header_t *vqp_common_header;
const struct vqp_obj_tlv_t *vqp_obj_tlv;
const u_char *tptr;
uint16_t vqp_obj_len;
uint32_t vqp_obj_type;
int tlen;
uint8_t nitems;
tptr=pptr;
tlen = len;
vqp_common_header = (const struct vqp_common_header_t *)pptr;
ND_TCHECK(*vqp_common_header);
/*
* Sanity checking of the header.
*/
if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) {
ND_PRINT((ndo, "VQP version %u packet not supported",
VQP_EXTRACT_VERSION(vqp_common_header->version)));
return;
}
/* in non-verbose mode just lets print the basic Message Type */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "VQPv%u %s Message, error-code %s (%u), length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
nitems = vqp_common_header->nitems;
ND_PRINT((ndo, "\n\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
EXTRACT_32BITS(&vqp_common_header->sequence),
nitems,
len));
/* skip VQP Common header */
tptr+=sizeof(const struct vqp_common_header_t);
tlen-=sizeof(const struct vqp_common_header_t);
while (nitems > 0 && tlen > 0) {
vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr;
vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type);
vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length);
tptr+=sizeof(struct vqp_obj_tlv_t);
tlen-=sizeof(struct vqp_obj_tlv_t);
ND_PRINT((ndo, "\n\t %s Object (0x%08x), length %u, value: ",
tok2str(vqp_obj_values, "Unknown", vqp_obj_type),
vqp_obj_type, vqp_obj_len));
/* basic sanity check */
if (vqp_obj_type == 0 || vqp_obj_len ==0) {
return;
}
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, vqp_obj_len);
switch(vqp_obj_type) {
case VQP_OBJ_IP_ADDRESS:
ND_PRINT((ndo, "%s (0x%08x)", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr)));
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_PORT_NAME:
case VQP_OBJ_VLAN_NAME:
case VQP_OBJ_VTP_DOMAIN:
case VQP_OBJ_ETHERNET_PKT:
safeputs(ndo, tptr, vqp_obj_len);
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_MAC_ADDRESS:
case VQP_OBJ_MAC_NULL:
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr)));
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tptr, "\n\t ", vqp_obj_len);
break;
}
tptr += vqp_obj_len;
tlen -= vqp_obj_len;
nitems--;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|VQP]"));
}
Commit Message: CVE-2017-13045/VQP: add some bounds checks
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: void DownloadInsertFilesErrorCheckErrors(size_t count,
FileErrorInjectInfo* info) {
DownloadFilesCheckErrorsSetup();
scoped_refptr<content::TestFileErrorInjector> injector(
content::TestFileErrorInjector::Create(
DownloadManagerForBrowser(browser())));
for (size_t i = 0; i < count; ++i) {
DownloadInsertFilesErrorCheckErrorsLoopBody(injector, info[i], i);
}
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: unset_and_free_gvalue (gpointer val)
{
g_value_unset (val);
g_free (val);
}
Commit Message:
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name)
{
int i,n=0,len,nid, first, use_bn;
BIGNUM *bl;
unsigned long l;
const unsigned char *p;
char tbuf[DECIMAL_SIZE(i)+DECIMAL_SIZE(l)+2];
if ((a == NULL) || (a->data == NULL)) {
buf[0]='\0';
return(0);
}
if (!no_name && (nid=OBJ_obj2nid(a)) != NID_undef)
{
s=OBJ_nid2ln(nid);
if (s == NULL)
s=OBJ_nid2sn(nid);
if (s)
{
if (buf)
BUF_strlcpy(buf,s,buf_len);
n=strlen(s);
return n;
}
}
len=a->length;
p=a->data;
first = 1;
bl = NULL;
while (len > 0)
{
l=0;
use_bn = 0;
for (;;)
{
unsigned char c = *p++;
len--;
if ((len == 0) && (c & 0x80))
goto err;
if (use_bn)
{
if (!BN_add_word(bl, c & 0x7f))
goto err;
}
else
l |= c & 0x7f;
if (!(c & 0x80))
break;
if (!use_bn && (l > (ULONG_MAX >> 7L)))
{
if (!bl && !(bl = BN_new()))
goto err;
if (!BN_set_word(bl, l))
goto err;
use_bn = 1;
}
if (use_bn)
{
if (!BN_lshift(bl, bl, 7))
goto err;
}
else
l<<=7L;
}
if (first)
{
first = 0;
if (l >= 80)
{
i = 2;
if (use_bn)
{
if (!BN_sub_word(bl, 80))
goto err;
}
else
l -= 80;
}
else
{
i=(int)(l/40);
i=(int)(l/40);
l-=(long)(i*40);
}
if (buf && (buf_len > 0))
{
*buf++ = i + '0';
buf_len--;
}
n++;
if (use_bn)
{
char *bndec;
bndec = BN_bn2dec(bl);
if (!bndec)
goto err;
i = strlen(bndec);
if (buf)
i = strlen(bndec);
if (buf)
{
if (buf_len > 0)
{
*buf++ = '.';
buf_len--;
}
BUF_strlcpy(buf,bndec,buf_len);
buf_len = 0;
}
else
{
buf+=i;
buf_len-=i;
}
}
n++;
n += i;
OPENSSL_free(bndec);
}
else
{
BIO_snprintf(tbuf,sizeof tbuf,".%lu",l);
i=strlen(tbuf);
if (buf && (buf_len > 0))
{
BUF_strlcpy(buf,tbuf,buf_len);
if (i > buf_len)
{
buf += buf_len;
buf_len = 0;
}
else
{
buf+=i;
buf_len-=i;
}
}
n+=i;
l=0;
}
}
if (bl)
BN_free(bl);
return n;
err:
if (bl)
BN_free(bl);
return -1;
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool HTMLMediaElement::IsMediaDataCORSSameOrigin(
const SecurityOrigin* origin) const {
if (GetWebMediaPlayer() &&
GetWebMediaPlayer()->DidGetOpaqueResponseFromServiceWorker()) {
return false;
}
if (!HasSingleSecurityOrigin())
return false;
return (GetWebMediaPlayer() &&
GetWebMediaPlayer()->DidPassCORSAccessCheck()) ||
origin->CanReadContent(currentSrc());
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn,
PNG_CONST png_byte bit_depthIn, PNG_CONST int palette_numberIn,
PNG_CONST int interlace_typeIn,
PNG_CONST double file_gammaIn, PNG_CONST double screen_gammaIn,
PNG_CONST png_byte sbitIn, PNG_CONST int threshold_testIn,
PNG_CONST char *name,
PNG_CONST int use_input_precisionIn, PNG_CONST int scale16In,
PNG_CONST int expand16In, PNG_CONST int do_backgroundIn,
PNG_CONST png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
{
gamma_display d;
context(&pmIn->this, fault);
gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
palette_numberIn, interlace_typeIn, 0, 0, 0),
file_gammaIn, screen_gammaIn, sbitIn,
threshold_testIn, use_input_precisionIn, scale16In,
expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
Try
{
png_structp pp;
png_infop pi;
gama_modification gama_mod;
srgb_modification srgb_mod;
sbit_modification sbit_mod;
/* For the moment don't use the png_modifier support here. */
d.pm->encoding_counter = 0;
modifier_set_encoding(d.pm); /* Just resets everything */
d.pm->current_gamma = d.file_gamma;
/* Make an appropriate modifier to set the PNG file gamma to the
* given gamma value and the sBIT chunk to the given precision.
*/
d.pm->modifications = NULL;
gama_modification_init(&gama_mod, d.pm, d.file_gamma);
srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
if (d.sbit > 0)
sbit_modification_init(&sbit_mod, d.pm, d.sbit);
modification_reset(d.pm->modifications);
/* Get a png_struct for writing the image. */
pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
standard_palette_init(&d.this);
/* Introduce the correct read function. */
if (d.pm->this.progressive)
{
/* Share the row function with the standard implementation. */
png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
gamma_end);
/* Now feed data into the reader until we reach the end: */
modifier_progressive_read(d.pm, pp, pi);
}
else
{
/* modifier_read expects a png_modifier* */
png_set_read_fn(pp, d.pm, modifier_read);
/* Check the header values: */
png_read_info(pp, pi);
/* Process the 'info' requirements. Only one image is generated */
gamma_info_imp(&d, pp, pi);
sequential_row(&d.this, pp, pi, -1, 0);
if (!d.this.speed)
gamma_image_validate(&d, pp, pi);
else
d.this.ps->validated = 1;
}
modifier_reset(d.pm);
if (d.pm->log && !d.threshold_test && !d.this.speed)
fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
d.this.bit_depth, colour_types[d.this.colour_type], name,
d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
/* Log the summary values too. */
if (d.this.colour_type == 0 || d.this.colour_type == 4)
{
switch (d.this.bit_depth)
{
case 1:
break;
case 2:
if (d.maxerrout > d.pm->error_gray_2)
d.pm->error_gray_2 = d.maxerrout;
break;
case 4:
if (d.maxerrout > d.pm->error_gray_4)
d.pm->error_gray_4 = d.maxerrout;
break;
case 8:
if (d.maxerrout > d.pm->error_gray_8)
d.pm->error_gray_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_gray_16)
d.pm->error_gray_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 1)");
}
}
else if (d.this.colour_type == 2 || d.this.colour_type == 6)
{
switch (d.this.bit_depth)
{
case 8:
if (d.maxerrout > d.pm->error_color_8)
d.pm->error_color_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_color_16)
d.pm->error_color_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 2)");
}
}
else if (d.this.colour_type == 3)
{
if (d.maxerrout > d.pm->error_indexed)
d.pm->error_indexed = d.maxerrout;
}
}
Catch(fault)
modifier_reset(voidcast(png_modifier*,(void*)fault));
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int regset_tls_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct user_desc infobuf[GDT_ENTRY_TLS_ENTRIES];
const struct user_desc *info;
if (pos >= GDT_ENTRY_TLS_ENTRIES * sizeof(struct user_desc) ||
(pos % sizeof(struct user_desc)) != 0 ||
(count % sizeof(struct user_desc)) != 0)
return -EINVAL;
if (kbuf)
info = kbuf;
else if (__copy_from_user(infobuf, ubuf, count))
return -EFAULT;
else
info = infobuf;
set_tls_desc(target,
GDT_ENTRY_TLS_MIN + (pos / sizeof(struct user_desc)),
info, count / sizeof(struct user_desc));
return 0;
}
Commit Message: x86/tls: Validate TLS entries to protect espfix
Installing a 16-bit RW data segment into the GDT defeats espfix.
AFAICT this will not affect glibc, Wine, or dosemu at all.
Signed-off-by: Andy Lutomirski <[email protected]>
Acked-by: H. Peter Anvin <[email protected]>
Cc: [email protected]
Cc: Konrad Rzeszutek Wilk <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: [email protected] <[email protected]>
Cc: Willy Tarreau <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void webkit_web_view_real_redo(WebKitWebView* webView)
{
Frame* frame = core(webView)->focusController()->focusedOrMainFrame();
frame->editor()->command("Redo").execute();
}
Commit Message: 2011-06-02 Joone Hur <[email protected]>
Reviewed by Martin Robinson.
[GTK] Only load dictionaries if spell check is enabled
https://bugs.webkit.org/show_bug.cgi?id=32879
We don't need to call enchant if enable-spell-checking is false.
* webkit/webkitwebview.cpp:
(webkit_web_view_update_settings): Skip loading dictionaries when enable-spell-checking is false.
(webkit_web_view_settings_notify): Ditto.
git-svn-id: svn://svn.chromium.org/blink/trunk@87925 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int key_seal(struct trusted_key_payload *p,
struct trusted_key_options *o)
{
struct tpm_buf *tb;
int ret;
tb = kzalloc(sizeof *tb, GFP_KERNEL);
if (!tb)
return -ENOMEM;
/* include migratable flag at end of sealed key */
p->key[p->key_len] = p->migratable;
ret = tpm_seal(tb, o->keytype, o->keyhandle, o->keyauth,
p->key, p->key_len + 1, p->blob, &p->blob_len,
o->blobauth, o->pcrinfo, o->pcrinfo_len);
if (ret < 0)
pr_info("trusted_key: srkseal failed (%d)\n", ret);
kfree(tb);
return ret;
}
Commit Message: KEYS: Fix handling of stored error in a negatively instantiated user key
If a user key gets negatively instantiated, an error code is cached in the
payload area. A negatively instantiated key may be then be positively
instantiated by updating it with valid data. However, the ->update key
type method must be aware that the error code may be there.
The following may be used to trigger the bug in the user key type:
keyctl request2 user user "" @u
keyctl add user user "a" @u
which manifests itself as:
BUG: unable to handle kernel paging request at 00000000ffffff8a
IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
PGD 7cc30067 PUD 0
Oops: 0002 [#1] SMP
Modules linked in:
CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000
RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280
[<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246
RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001
RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82
RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000
R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82
R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700
FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0
Stack:
ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82
ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5
ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620
Call Trace:
[<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136
[<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129
[< inline >] __key_update security/keys/key.c:730
[<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908
[< inline >] SYSC_add_key security/keys/keyctl.c:125
[<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60
[<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185
Note the error code (-ENOKEY) in EDX.
A similar bug can be tripped by:
keyctl request2 trusted user "" @u
keyctl add trusted user "a" @u
This should also affect encrypted keys - but that has to be correctly
parameterised or it will fail with EINVAL before getting to the bit that
will crashes.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: David Howells <[email protected]>
Acked-by: Mimi Zohar <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Subsets and Splits