instruction
stringclasses 1
value | input
stringlengths 90
5.47k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return -ENOMEM;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum = 0;
}
err = skb_append_datato_frags(sk,skb, getfrag, from,
(length - transhdrlen));
if (!err) {
struct frag_hdr fhdr;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
__skb_queue_tail(&sk->sk_write_queue, skb);
return 0;
}
/* There is not enough support do UPD LSO,
* so follow normal path
*/
kfree_skb(skb);
return err;
}
Commit Message: ipv6: make fragment identifications less predictable
IPv6 fragment identification generation is way beyond what we use for
IPv4 : It uses a single generator. Its not scalable and allows DOS
attacks.
Now inetpeer is IPv6 aware, we can use it to provide a more secure and
scalable frag ident generator (per destination, instead of system wide)
This patch :
1) defines a new secure_ipv6_id() helper
2) extends inet_getid() to provide 32bit results
3) extends ipv6_select_ident() with a new dest parameter
Reported-by: Fernando Gont <fernando@gont.com.ar>
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID:
|
static inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags,
struct rt6_info *rt)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return -ENOMEM;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum = 0;
}
err = skb_append_datato_frags(sk,skb, getfrag, from,
(length - transhdrlen));
if (!err) {
struct frag_hdr fhdr;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr, rt);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
__skb_queue_tail(&sk->sk_write_queue, skb);
return 0;
}
/* There is not enough support do UPD LSO,
* so follow normal path
*/
kfree_skb(skb);
return err;
}
| 165,853
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool AXLayoutObject::isSelected() const {
if (!getLayoutObject() || !getNode())
return false;
const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
if (equalIgnoringCase(ariaSelected, "true"))
return true;
AXObject* focusedObject = axObjectCache().focusedObject();
if (ariaRoleAttribute() == ListBoxOptionRole && focusedObject &&
focusedObject->activeDescendant() == this) {
return true;
}
if (isTabItem() && isTabItemSelected())
return true;
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXLayoutObject::isSelected() const {
if (!getLayoutObject() || !getNode())
return false;
const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
if (equalIgnoringASCIICase(ariaSelected, "true"))
return true;
AXObject* focusedObject = axObjectCache().focusedObject();
if (ariaRoleAttribute() == ListBoxOptionRole && focusedObject &&
focusedObject->activeDescendant() == this) {
return true;
}
if (isTabItem() && isTabItemSelected())
return true;
return false;
}
| 171,905
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t MyOpusExtractor::readNextPacket(MediaBuffer **out) {
if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) {
MediaBuffer *mBuf;
uint32_t numSamples = 0;
uint64_t curGranulePosition = 0;
while (true) {
status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false);
if (err != OK && err != ERROR_END_OF_STREAM) {
return err;
}
if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) {
break;
}
curGranulePosition = mCurrentPage.mGranulePosition;
numSamples += getNumSamplesInPacket(mBuf);
mBuf->release();
mBuf = NULL;
}
if (curGranulePosition > numSamples) {
mStartGranulePosition = curGranulePosition - numSamples;
} else {
mStartGranulePosition = 0;
}
seekToOffset(0);
}
status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false);
if (err != OK) {
return err;
}
int32_t currentPageSamples;
if ((*out)->meta_data()->findInt32(kKeyValidSamples, ¤tPageSamples)) {
if (mOffset == mFirstDataOffset) {
currentPageSamples -= mStartGranulePosition;
(*out)->meta_data()->setInt32(kKeyValidSamples, currentPageSamples);
}
mCurGranulePosition = mCurrentPage.mGranulePosition - currentPageSamples;
}
int64_t timeUs = getTimeUsOfGranule(mCurGranulePosition);
(*out)->meta_data()->setInt64(kKeyTime, timeUs);
uint32_t frames = getNumSamplesInPacket(*out);
mCurGranulePosition += frames;
return OK;
}
Commit Message: Fix memory leak in OggExtractor
Test: added a temporal log and run poc
Bug: 63581671
Change-Id: I436a08e54d5e831f9fbdb33c26d15397ce1fbeba
(cherry picked from commit 63079e7c8e12cda4eb124fbe565213d30b9ea34c)
CWE ID: CWE-772
|
status_t MyOpusExtractor::readNextPacket(MediaBuffer **out) {
if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) {
MediaBuffer *mBuf;
uint32_t numSamples = 0;
uint64_t curGranulePosition = 0;
while (true) {
status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false);
if (err != OK && err != ERROR_END_OF_STREAM) {
return err;
}
if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) {
if (mBuf != NULL) {
mBuf->release();
mBuf = NULL;
}
break;
}
curGranulePosition = mCurrentPage.mGranulePosition;
numSamples += getNumSamplesInPacket(mBuf);
mBuf->release();
mBuf = NULL;
}
if (curGranulePosition > numSamples) {
mStartGranulePosition = curGranulePosition - numSamples;
} else {
mStartGranulePosition = 0;
}
seekToOffset(0);
}
status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false);
if (err != OK) {
return err;
}
int32_t currentPageSamples;
if ((*out)->meta_data()->findInt32(kKeyValidSamples, ¤tPageSamples)) {
if (mOffset == mFirstDataOffset) {
currentPageSamples -= mStartGranulePosition;
(*out)->meta_data()->setInt32(kKeyValidSamples, currentPageSamples);
}
mCurGranulePosition = mCurrentPage.mGranulePosition - currentPageSamples;
}
int64_t timeUs = getTimeUsOfGranule(mCurGranulePosition);
(*out)->meta_data()->setInt64(kKeyTime, timeUs);
uint32_t frames = getNumSamplesInPacket(*out);
mCurGranulePosition += frames;
return OK;
}
| 173,976
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ManifestManager::FetchManifest() {
manifest_url_ = render_frame()->GetWebFrame()->GetDocument().ManifestURL();
if (manifest_url_.is_empty()) {
ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_EMPTY_URL);
ResolveCallbacks(ResolveStateFailure);
return;
}
fetcher_.reset(new ManifestFetcher(manifest_url_));
fetcher_->Start(
render_frame()->GetWebFrame(),
render_frame()->GetWebFrame()->GetDocument().ManifestUseCredentials(),
base::Bind(&ManifestManager::OnManifestFetchComplete,
base::Unretained(this),
render_frame()->GetWebFrame()->GetDocument().Url()));
}
Commit Message: Fail the web app manifest fetch if the document is sandboxed.
This ensures that sandboxed pages are regarded as non-PWAs, and that
other features in the browser process which trust the web manifest do
not receive the manifest at all if the document itself cannot access the
manifest.
BUG=771709
Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4
Reviewed-on: https://chromium-review.googlesource.com/866529
Commit-Queue: Dominick Ng <dominickn@chromium.org>
Reviewed-by: Mounir Lamouri <mlamouri@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531121}
CWE ID:
|
void ManifestManager::FetchManifest() {
if (!CanFetchManifest(render_frame())) {
ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_FROM_UNIQUE_ORIGIN);
ResolveCallbacks(ResolveStateFailure);
return;
}
manifest_url_ = render_frame()->GetWebFrame()->GetDocument().ManifestURL();
if (manifest_url_.is_empty()) {
ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_EMPTY_URL);
ResolveCallbacks(ResolveStateFailure);
return;
}
fetcher_.reset(new ManifestFetcher(manifest_url_));
fetcher_->Start(
render_frame()->GetWebFrame(),
render_frame()->GetWebFrame()->GetDocument().ManifestUseCredentials(),
base::Bind(&ManifestManager::OnManifestFetchComplete,
base::Unretained(this),
render_frame()->GetWebFrame()->GetDocument().Url()));
}
| 172,921
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ResourceDispatcherHostImpl::AcceptAuthRequest(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) {
if (delegate_ && !delegate_->AcceptAuthRequest(loader->request(), auth_info))
return false;
if (!auth_info->is_proxy) {
HttpAuthResourceType resource_type =
HttpAuthResourceTypeOf(loader->request());
UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthResource",
resource_type,
HTTP_AUTH_RESOURCE_LAST);
if (resource_type == HTTP_AUTH_RESOURCE_BLOCKED_CROSS)
return false;
}
return true;
}
Commit Message: Revert cross-origin auth prompt blocking.
BUG=174129
Review URL: https://chromiumcodereview.appspot.com/12183030
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181113 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool ResourceDispatcherHostImpl::AcceptAuthRequest(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) {
if (delegate_ && !delegate_->AcceptAuthRequest(loader->request(), auth_info))
return false;
if (!auth_info->is_proxy) {
HttpAuthResourceType resource_type =
HttpAuthResourceTypeOf(loader->request());
UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthResource",
resource_type,
HTTP_AUTH_RESOURCE_LAST);
// TODO(tsepez): Return false on HTTP_AUTH_RESOURCE_BLOCKED_CROSS.
// The code once did this, but was changed due to http://crbug.com/174129.
// http://crbug.com/174179 has been filed to track this issue.
}
return true;
}
| 171,439
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DocumentLoader::DetachFromFrame() {
DCHECK(frame_);
fetcher_->StopFetching();
if (frame_ && !SentDidFinishLoad())
LoadFailed(ResourceError::CancelledError(Url()));
fetcher_->ClearContext();
if (!frame_)
return;
application_cache_host_->DetachFromDocumentLoader();
application_cache_host_.Clear();
service_worker_network_provider_ = nullptr;
WeakIdentifierMap<DocumentLoader>::NotifyObjectDestroyed(this);
ClearResource();
frame_ = nullptr;
}
Commit Message: Fix detach with open()ed document leaving parent loading indefinitely
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Bug: 803416
Test: fast/loader/document-open-iframe-then-detach.html
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Reviewed-on: https://chromium-review.googlesource.com/887298
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Nate Chapin <japhet@chromium.org>
Cr-Commit-Position: refs/heads/master@{#532967}
CWE ID: CWE-362
|
void DocumentLoader::DetachFromFrame() {
void DocumentLoader::StopLoading() {
fetcher_->StopFetching();
if (frame_ && !SentDidFinishLoad())
LoadFailed(ResourceError::CancelledError(Url()));
}
void DocumentLoader::DetachFromFrame() {
DCHECK(frame_);
StopLoading();
fetcher_->ClearContext();
if (!frame_)
return;
application_cache_host_->DetachFromDocumentLoader();
application_cache_host_.Clear();
service_worker_network_provider_ = nullptr;
WeakIdentifierMap<DocumentLoader>::NotifyObjectDestroyed(this);
ClearResource();
frame_ = nullptr;
}
| 171,851
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
{
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
l_strnstart(netdissect_options *ndo, const char *tstr1, u_int tl1,
const char *str2, u_int l2)
{
if (!ND_TTEST2(*str2, tl1)) {
/*
* We don't have tl1 bytes worth of captured data
* for the string, so we can't check for this
* string.
*/
return 0;
}
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
| 167,885
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
assert(0);
return NULL;
}
Commit Message: Fix seven bugs discovered and fixed by ForAllSecure:
CVE-2019-13217: heap buffer overflow in start_decoder()
CVE-2019-13218: stack buffer overflow in compute_codewords()
CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()
CVE-2019-13220: out-of-range read in draw_line()
CVE-2019-13221: issue with large 1D codebooks in lookup1_values()
CVE-2019-13222: unchecked NULL returned by get_window()
CVE-2019-13223: division by zero in predict_point()
CWE ID: CWE-20
|
static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
return NULL;
}
| 169,615
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
| 167,201
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415
|
static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
| 167,119
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int vmxnet3_post_load(void *opaque, int version_id)
{
VMXNET3State *s = opaque;
PCIDevice *d = PCI_DEVICE(s);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
if (s->msix_used) {
if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
VMW_WRPRN("Failed to re-use MSI-X vectors");
msix_uninit(d, &s->msix_bar, &s->msix_bar);
s->msix_used = false;
return -1;
}
}
return 0;
}
Commit Message:
CWE ID: CWE-20
|
static int vmxnet3_post_load(void *opaque, int version_id)
{
VMXNET3State *s = opaque;
PCIDevice *d = PCI_DEVICE(s);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
if (s->msix_used) {
if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
VMW_WRPRN("Failed to re-use MSI-X vectors");
msix_uninit(d, &s->msix_bar, &s->msix_bar);
s->msix_used = false;
return -1;
}
}
vmxnet3_validate_interrupts(s);
return 0;
}
| 165,354
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void parse_input(h2o_http2_conn_t *conn)
{
size_t http2_max_concurrent_requests_per_connection = conn->super.ctx->globalconf->http2.max_concurrent_requests_per_connection;
int perform_early_exit = 0;
if (conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed != http2_max_concurrent_requests_per_connection)
perform_early_exit = 1;
/* handle the input */
while (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && conn->sock->input->size != 0) {
if (perform_early_exit == 1 &&
conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed == http2_max_concurrent_requests_per_connection)
goto EarlyExit;
/* process a frame */
const char *err_desc = NULL;
ssize_t ret = conn->_read_expect(conn, (uint8_t *)conn->sock->input->bytes, conn->sock->input->size, &err_desc);
if (ret == H2O_HTTP2_ERROR_INCOMPLETE) {
break;
} else if (ret < 0) {
if (ret != H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY) {
enqueue_goaway(conn, (int)ret,
err_desc != NULL ? (h2o_iovec_t){(char *)err_desc, strlen(err_desc)} : (h2o_iovec_t){});
}
close_connection(conn);
return;
}
/* advance to the next frame */
h2o_buffer_consume(&conn->sock->input, ret);
}
if (!h2o_socket_is_reading(conn->sock))
h2o_socket_read_start(conn->sock, on_read);
return;
EarlyExit:
if (h2o_socket_is_reading(conn->sock))
h2o_socket_read_stop(conn->sock);
}
Commit Message: h2: use after free on premature connection close #920
lib/http2/connection.c:on_read() calls parse_input(), which might free
`conn`. It does so in particular if the connection preface isn't
the expected one in expect_preface(). `conn` is then used after the free
in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`.
We fix this by adding a return value to close_connection that returns a
negative value if `conn` has been free'd and can't be used anymore.
Credits for finding the bug to Tim Newsham.
CWE ID:
|
static void parse_input(h2o_http2_conn_t *conn)
static int parse_input(h2o_http2_conn_t *conn)
{
size_t http2_max_concurrent_requests_per_connection = conn->super.ctx->globalconf->http2.max_concurrent_requests_per_connection;
int perform_early_exit = 0;
if (conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed != http2_max_concurrent_requests_per_connection)
perform_early_exit = 1;
/* handle the input */
while (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && conn->sock->input->size != 0) {
if (perform_early_exit == 1 &&
conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed == http2_max_concurrent_requests_per_connection)
goto EarlyExit;
/* process a frame */
const char *err_desc = NULL;
ssize_t ret = conn->_read_expect(conn, (uint8_t *)conn->sock->input->bytes, conn->sock->input->size, &err_desc);
if (ret == H2O_HTTP2_ERROR_INCOMPLETE) {
break;
} else if (ret < 0) {
if (ret != H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY) {
enqueue_goaway(conn, (int)ret,
err_desc != NULL ? (h2o_iovec_t){(char *)err_desc, strlen(err_desc)} : (h2o_iovec_t){});
}
return close_connection(conn);
}
/* advance to the next frame */
h2o_buffer_consume(&conn->sock->input, ret);
}
if (!h2o_socket_is_reading(conn->sock))
h2o_socket_read_start(conn->sock, on_read);
return 0;
EarlyExit:
if (h2o_socket_is_reading(conn->sock))
h2o_socket_read_stop(conn->sock);
return 0;
}
| 167,227
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool new_idmap_permitted(struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
*/
if (ns_capable(ns->parent, cap_setid))
return true;
return false;
}
Commit Message: userns: Don't let unprivileged users trick privileged users into setting the id_map
When we require privilege for setting /proc/<pid>/uid_map or
/proc/<pid>/gid_map no longer allow an unprivileged user to
open the file and pass it to a privileged program to write
to the file.
Instead when privilege is required require both the opener and the
writer to have the necessary capabilities.
I have tested this code and verified that setting /proc/<pid>/uid_map
fails when an unprivileged user opens the file and a privielged user
attempts to set the mapping, that unprivileged users can still map
their own id, and that a privileged users can still setup an arbitrary
mapping.
Reported-by: Andy Lutomirski <luto@amacapital.net>
Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
Signed-off-by: Andy Lutomirski <luto@amacapital.net>
CWE ID: CWE-264
|
static bool new_idmap_permitted(struct user_namespace *ns, int cap_setid,
static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
| 166,092
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if (colors.a[code] && image->matte == MagickFalse)
/* Correct matte */
image->matte = MagickTrue;
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 8);
return MagickTrue;
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20
|
static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if (colors.a[code] && image->matte == MagickFalse)
/* Correct matte */
image->matte = MagickTrue;
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
return(SkipDXTMipmaps(image,dds_info,8,exception));
}
| 168,899
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int empty_write_end(struct page *page, unsigned from,
unsigned to, int mode)
{
struct inode *inode = page->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct buffer_head *bh;
unsigned offset, blksize = 1 << inode->i_blkbits;
pgoff_t end_index = i_size_read(inode) >> PAGE_CACHE_SHIFT;
zero_user(page, from, to-from);
mark_page_accessed(page);
if (page->index < end_index || !(mode & FALLOC_FL_KEEP_SIZE)) {
if (!gfs2_is_writeback(ip))
gfs2_page_add_databufs(ip, page, from, to);
block_commit_write(page, from, to);
return 0;
}
offset = 0;
bh = page_buffers(page);
while (offset < to) {
if (offset >= from) {
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
clear_buffer_new(bh);
write_dirty_buffer(bh, WRITE);
}
offset += blksize;
bh = bh->b_this_page;
}
offset = 0;
bh = page_buffers(page);
while (offset < to) {
if (offset >= from) {
wait_on_buffer(bh);
if (!buffer_uptodate(bh))
return -EIO;
}
offset += blksize;
bh = bh->b_this_page;
}
return 0;
}
Commit Message: GFS2: rewrite fallocate code to write blocks directly
GFS2's fallocate code currently goes through the page cache. Since it's only
writing to the end of the file or to holes in it, it doesn't need to, and it
was causing issues on low memory environments. This patch pulls in some of
Steve's block allocation work, and uses it to simply allocate the blocks for
the file, and zero them out at allocation time. It provides a slight
performance increase, and it dramatically simplifies the code.
Signed-off-by: Benjamin Marzinski <bmarzins@redhat.com>
Signed-off-by: Steven Whitehouse <swhiteho@redhat.com>
CWE ID: CWE-119
|
static int empty_write_end(struct page *page, unsigned from,
| 166,211
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: cf2_initGlobalRegionBuffer( CFF_Decoder* decoder,
CF2_UInt idx,
CF2_Buffer buf )
{
FT_ASSERT( decoder && decoder->globals );
FT_ZERO( buf );
idx += decoder->globals_bias;
if ( idx >= decoder->num_globals )
return TRUE; /* error */
buf->start =
buf->ptr = decoder->globals[idx];
buf->end = decoder->globals[idx + 1];
}
Commit Message:
CWE ID: CWE-20
|
cf2_initGlobalRegionBuffer( CFF_Decoder* decoder,
CF2_UInt idx,
CF2_Buffer buf )
{
FT_ASSERT( decoder );
FT_ZERO( buf );
idx += decoder->globals_bias;
if ( idx >= decoder->num_globals )
return TRUE; /* error */
FT_ASSERT( decoder->globals );
buf->start =
buf->ptr = decoder->globals[idx];
buf->end = decoder->globals[idx + 1];
}
| 165,221
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BackendImpl::BackendImpl(
const base::FilePath& path,
uint32_t mask,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(mask),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(kMask),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <mmenke@chromium.org>
Commit-Queue: Maks Orlovich <morlovich@chromium.org>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20
|
BackendImpl::BackendImpl(
const base::FilePath& path,
uint32_t mask,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(mask),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(kMask),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
consider_evicting_at_op_end_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
| 172,697
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void *btif_hh_poll_event_thread(void *arg)
{
btif_hh_device_t *p_dev = arg;
APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd);
struct pollfd pfds[1];
int ret;
pfds[0].fd = p_dev->fd;
pfds[0].events = POLLIN;
uhid_set_non_blocking(p_dev->fd);
while(p_dev->hh_keep_polling){
ret = poll(pfds, 1, 50);
if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno));
break;
}
if (pfds[0].revents & POLLIN) {
APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN");
ret = uhid_event(p_dev);
if (ret){
break;
}
}
}
p_dev->hh_poll_thread_id = -1;
return 0;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static void *btif_hh_poll_event_thread(void *arg)
{
btif_hh_device_t *p_dev = arg;
APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd);
struct pollfd pfds[1];
int ret;
pfds[0].fd = p_dev->fd;
pfds[0].events = POLLIN;
uhid_set_non_blocking(p_dev->fd);
while(p_dev->hh_keep_polling){
ret = TEMP_FAILURE_RETRY(poll(pfds, 1, 50));
if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno));
break;
}
if (pfds[0].revents & POLLIN) {
APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN");
ret = uhid_event(p_dev);
if (ret){
break;
}
}
}
p_dev->hh_poll_thread_id = -1;
return 0;
}
| 173,431
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: store_pool_delete(png_store *ps, store_pool *pool)
{
if (pool->list != NULL)
{
fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
++ps->nerrors;
do
{
store_memory *next = pool->list;
pool->list = next->next;
next->next = NULL;
fprintf(stderr, "\t%lu bytes @ %p\n",
(unsigned long)next->size, (PNG_CONST void*)(next+1));
/* The NULL means this will always return, even if the memory is
* corrupted.
*/
store_memory_free(NULL, pool, next);
}
while (pool->list != NULL);
}
/* And reset the other fields too for the next time. */
if (pool->max > pool->max_max) pool->max_max = pool->max;
pool->max = 0;
if (pool->current != 0) /* unexpected internal error */
fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
ps->test, pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
pool->current = 0;
if (pool->limit > pool->max_limit)
pool->max_limit = pool->limit;
pool->limit = 0;
if (pool->total > pool->max_total)
pool->max_total = pool->total;
pool->total = 0;
/* Get a new mark too. */
store_pool_mark(pool->mark);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
store_pool_delete(png_store *ps, store_pool *pool)
{
if (pool->list != NULL)
{
fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
++ps->nerrors;
do
{
store_memory *next = pool->list;
pool->list = next->next;
next->next = NULL;
fprintf(stderr, "\t%lu bytes @ %p\n",
(unsigned long)next->size, (const void*)(next+1));
/* The NULL means this will always return, even if the memory is
* corrupted.
*/
store_memory_free(NULL, pool, next);
}
while (pool->list != NULL);
}
/* And reset the other fields too for the next time. */
if (pool->max > pool->max_max) pool->max_max = pool->max;
pool->max = 0;
if (pool->current != 0) /* unexpected internal error */
fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
ps->test, pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
pool->current = 0;
if (pool->limit > pool->max_limit)
pool->max_limit = pool->limit;
pool->limit = 0;
if (pool->total > pool->max_total)
pool->max_total = pool->total;
pool->total = 0;
/* Get a new mark too. */
store_pool_mark(pool->mark);
}
| 173,707
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void oinf_entry_dump(GF_OperatingPointsInformation *ptr, FILE * trace)
{
u32 i, count;
if (!ptr) {
fprintf(trace, "<OperatingPointsInformation scalability_mask=\"Multiview|Spatial scalability|Auxilary|unknown\" num_profile_tier_level=\"\" num_operating_points=\"\" dependency_layers=\"\">\n");
fprintf(trace, " <ProfileTierLevel general_profile_space=\"\" general_tier_flag=\"\" general_profile_idc=\"\" general_profile_compatibility_flags=\"\" general_constraint_indicator_flags=\"\" />\n");
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"\" max_temporal_id=\"\" layer_count=\"\" minPicWidth=\"\" minPicHeight=\"\" maxPicWidth=\"\" maxPicHeight=\"\" maxChromaFormat=\"\" maxBitDepth=\"\" frame_rate_info_flag=\"\" bit_rate_info_flag=\"\" avgFrameRate=\"\" constantFrameRate=\"\" maxBitRate=\"\" avgBitRate=\"\"/>\n");
fprintf(trace, "<Layer dependent_layerID=\"\" num_layers_dependent_on=\"\" dependent_on_layerID=\"\" dimension_identifier=\"\"/>\n");
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
fprintf(trace, "<OperatingPointsInformation");
fprintf(trace, " scalability_mask=\"%u (", ptr->scalability_mask);
switch (ptr->scalability_mask) {
case 2:
fprintf(trace, "Multiview");
break;
case 4:
fprintf(trace, "Spatial scalability");
break;
case 8:
fprintf(trace, "Auxilary");
break;
default:
fprintf(trace, "unknown");
}
fprintf(trace, ")\" num_profile_tier_level=\"%u\"", gf_list_count(ptr->profile_tier_levels) );
fprintf(trace, " num_operating_points=\"%u\" dependency_layers=\"%u\"", gf_list_count(ptr->operating_points), gf_list_count(ptr->dependency_layers));
fprintf(trace, ">\n");
count=gf_list_count(ptr->profile_tier_levels);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i);
fprintf(trace, " <ProfileTierLevel general_profile_space=\"%u\" general_tier_flag=\"%u\" general_profile_idc=\"%u\" general_profile_compatibility_flags=\"%X\" general_constraint_indicator_flags=\""LLX"\" />\n", ptl->general_profile_space, ptl->general_tier_flag, ptl->general_profile_idc, ptl->general_profile_compatibility_flags, ptl->general_constraint_indicator_flags);
}
count=gf_list_count(ptr->operating_points);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"%u\"", op->output_layer_set_idx);
fprintf(trace, " max_temporal_id=\"%u\" layer_count=\"%u\"", op->max_temporal_id, op->layer_count);
fprintf(trace, " minPicWidth=\"%u\" minPicHeight=\"%u\"", op->minPicWidth, op->minPicHeight);
fprintf(trace, " maxPicWidth=\"%u\" maxPicHeight=\"%u\"", op->maxPicWidth, op->maxPicHeight);
fprintf(trace, " maxChromaFormat=\"%u\" maxBitDepth=\"%u\"", op->maxChromaFormat, op->maxBitDepth);
fprintf(trace, " frame_rate_info_flag=\"%u\" bit_rate_info_flag=\"%u\"", op->frame_rate_info_flag, op->bit_rate_info_flag);
if (op->frame_rate_info_flag)
fprintf(trace, " avgFrameRate=\"%u\" constantFrameRate=\"%u\"", op->avgFrameRate, op->constantFrameRate);
if (op->bit_rate_info_flag)
fprintf(trace, " maxBitRate=\"%u\" avgBitRate=\"%u\"", op->maxBitRate, op->avgBitRate);
fprintf(trace, "/>\n");
}
count=gf_list_count(ptr->dependency_layers);
for (i = 0; i < count; i++) {
u32 j;
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);
fprintf(trace, "<Layer dependent_layerID=\"%u\" num_layers_dependent_on=\"%u\"", dep->dependent_layerID, dep->num_layers_dependent_on);
if (dep->num_layers_dependent_on) {
fprintf(trace, " dependent_on_layerID=\"");
for (j = 0; j < dep->num_layers_dependent_on; j++)
fprintf(trace, "%d ", dep->dependent_on_layerID[j]);
fprintf(trace, "\"");
}
fprintf(trace, " dimension_identifier=\"");
for (j = 0; j < 16; j++)
if (ptr->scalability_mask & (1 << j))
fprintf(trace, "%d ", dep->dimension_identifier[j]);
fprintf(trace, "\"/>\n");
}
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
|
static void oinf_entry_dump(GF_OperatingPointsInformation *ptr, FILE * trace)
{
u32 i, count;
if (!ptr) {
fprintf(trace, "<OperatingPointsInformation scalability_mask=\"Multiview|Spatial scalability|Auxilary|unknown\" num_profile_tier_level=\"\" num_operating_points=\"\" dependency_layers=\"\">\n");
fprintf(trace, " <ProfileTierLevel general_profile_space=\"\" general_tier_flag=\"\" general_profile_idc=\"\" general_profile_compatibility_flags=\"\" general_constraint_indicator_flags=\"\" />\n");
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"\" max_temporal_id=\"\" layer_count=\"\" minPicWidth=\"\" minPicHeight=\"\" maxPicWidth=\"\" maxPicHeight=\"\" maxChromaFormat=\"\" maxBitDepth=\"\" frame_rate_info_flag=\"\" bit_rate_info_flag=\"\" avgFrameRate=\"\" constantFrameRate=\"\" maxBitRate=\"\" avgBitRate=\"\"/>\n");
fprintf(trace, "<Layer dependent_layerID=\"\" num_layers_dependent_on=\"\" dependent_on_layerID=\"\" dimension_identifier=\"\"/>\n");
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
fprintf(trace, "<OperatingPointsInformation");
fprintf(trace, " scalability_mask=\"%u (", ptr->scalability_mask);
switch (ptr->scalability_mask) {
case 2:
fprintf(trace, "Multiview");
break;
case 4:
fprintf(trace, "Spatial scalability");
break;
case 8:
fprintf(trace, "Auxilary");
break;
default:
fprintf(trace, "unknown");
}
fprintf(trace, ")\" num_profile_tier_level=\"%u\"", gf_list_count(ptr->profile_tier_levels) );
fprintf(trace, " num_operating_points=\"%u\" dependency_layers=\"%u\"", gf_list_count(ptr->operating_points), gf_list_count(ptr->dependency_layers));
fprintf(trace, ">\n");
count=gf_list_count(ptr->profile_tier_levels);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i);
fprintf(trace, " <ProfileTierLevel general_profile_space=\"%u\" general_tier_flag=\"%u\" general_profile_idc=\"%u\" general_profile_compatibility_flags=\"%X\" general_constraint_indicator_flags=\""LLX"\" />\n", ptl->general_profile_space, ptl->general_tier_flag, ptl->general_profile_idc, ptl->general_profile_compatibility_flags, ptl->general_constraint_indicator_flags);
}
count=gf_list_count(ptr->operating_points);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"%u\"", op->output_layer_set_idx);
fprintf(trace, " max_temporal_id=\"%u\" layer_count=\"%u\"", op->max_temporal_id, op->layer_count);
fprintf(trace, " minPicWidth=\"%u\" minPicHeight=\"%u\"", op->minPicWidth, op->minPicHeight);
fprintf(trace, " maxPicWidth=\"%u\" maxPicHeight=\"%u\"", op->maxPicWidth, op->maxPicHeight);
fprintf(trace, " maxChromaFormat=\"%u\" maxBitDepth=\"%u\"", op->maxChromaFormat, op->maxBitDepth);
fprintf(trace, " frame_rate_info_flag=\"%u\" bit_rate_info_flag=\"%u\"", op->frame_rate_info_flag, op->bit_rate_info_flag);
if (op->frame_rate_info_flag)
fprintf(trace, " avgFrameRate=\"%u\" constantFrameRate=\"%u\"", op->avgFrameRate, op->constantFrameRate);
if (op->bit_rate_info_flag)
fprintf(trace, " maxBitRate=\"%u\" avgBitRate=\"%u\"", op->maxBitRate, op->avgBitRate);
fprintf(trace, "/>\n");
}
count=gf_list_count(ptr->dependency_layers);
for (i = 0; i < count; i++) {
u32 j;
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);
fprintf(trace, "<Layer dependent_layerID=\"%u\" num_layers_dependent_on=\"%u\"", dep->dependent_layerID, dep->num_layers_dependent_on);
if (dep->num_layers_dependent_on) {
fprintf(trace, " dependent_on_layerID=\"");
for (j = 0; j < dep->num_layers_dependent_on; j++)
fprintf(trace, "%d ", dep->dependent_on_layerID[j]);
fprintf(trace, "\"");
}
fprintf(trace, " dimension_identifier=\"");
for (j = 0; j < 16; j++)
if (ptr->scalability_mask & (1 << j))
fprintf(trace, "%d ", dep->dimension_identifier[j]);
fprintf(trace, "\"/>\n");
}
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
| 169,170
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool AddPolicyForGPU(CommandLine* cmd_line, sandbox::TargetPolicy* policy) {
#if !defined(NACL_WIN64) // We don't need this code on win nacl64.
if (base::win::GetVersion() > base::win::VERSION_SERVER_2003) {
if (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
gfx::kGLImplementationDesktopName) {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_LIMITED);
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
} else {
if (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
gfx::kGLImplementationSwiftShaderName ||
cmd_line->HasSwitch(switches::kReduceGpuSandbox)) {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_LIMITED);
policy->SetJobLevel(sandbox::JOB_LIMITED_USER,
JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
JOB_OBJECT_UILIMIT_DESKTOP |
JOB_OBJECT_UILIMIT_EXITWINDOWS |
JOB_OBJECT_UILIMIT_DISPLAYSETTINGS);
} else {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_RESTRICTED);
policy->SetJobLevel(sandbox::JOB_LOCKDOWN,
JOB_OBJECT_UILIMIT_HANDLES);
}
policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
}
} else {
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
sandbox::USER_LIMITED);
}
sandbox::ResultCode result = policy->AddRule(
sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
L"\\\\.\\pipe\\chrome.gpu.*");
if (result != sandbox::SBOX_ALL_OK)
return false;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
sandbox::TargetPolicy::HANDLES_DUP_ANY,
L"Section");
if (result != sandbox::SBOX_ALL_OK)
return false;
AddGenericDllEvictionPolicy(policy);
#endif
return true;
}
Commit Message: Prevent sandboxed processes from opening each other
TBR=brettw
BUG=117627
BUG=119150
TEST=sbox_validation_tests
Review URL: https://chromiumcodereview.appspot.com/9716027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
bool AddPolicyForGPU(CommandLine* cmd_line, sandbox::TargetPolicy* policy) {
#if !defined(NACL_WIN64) // We don't need this code on win nacl64.
if (base::win::GetVersion() > base::win::VERSION_SERVER_2003) {
if (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
gfx::kGLImplementationDesktopName) {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_LIMITED);
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
} else {
if (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
gfx::kGLImplementationSwiftShaderName ||
cmd_line->HasSwitch(switches::kReduceGpuSandbox)) {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_LIMITED);
policy->SetJobLevel(sandbox::JOB_LIMITED_USER,
JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
JOB_OBJECT_UILIMIT_DESKTOP |
JOB_OBJECT_UILIMIT_EXITWINDOWS |
JOB_OBJECT_UILIMIT_DISPLAYSETTINGS);
} else {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_RESTRICTED);
policy->SetJobLevel(sandbox::JOB_LOCKDOWN,
JOB_OBJECT_UILIMIT_HANDLES);
// This is a trick to keep the GPU out of low-integrity processes. It
// starts at low-integrity for UIPI to work, then drops below
// low-integrity after warm-up.
policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
}
policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
}
} else {
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
sandbox::USER_LIMITED);
}
sandbox::ResultCode result = policy->AddRule(
sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
L"\\\\.\\pipe\\chrome.gpu.*");
if (result != sandbox::SBOX_ALL_OK)
return false;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
sandbox::TargetPolicy::HANDLES_DUP_ANY,
L"Section");
if (result != sandbox::SBOX_ALL_OK)
return false;
AddGenericDllEvictionPolicy(policy);
#endif
return true;
}
| 170,911
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static UINT dvcman_receive_channel_data(drdynvcPlugin* drdynvc,
IWTSVirtualChannelManager* pChannelMgr,
UINT32 ChannelId, wStream* data)
{
UINT status = CHANNEL_RC_OK;
DVCMAN_CHANNEL* channel;
size_t dataSize = Stream_GetRemainingLength(data);
channel = (DVCMAN_CHANNEL*) dvcman_find_channel_by_id(pChannelMgr, ChannelId);
if (!channel)
{
/* Windows 8.1 tries to open channels not created.
* Ignore cases like this. */
WLog_Print(drdynvc->log, WLOG_ERROR, "ChannelId %"PRIu32" not found!", ChannelId);
return CHANNEL_RC_OK;
}
if (channel->dvc_data)
{
/* Fragmented data */
if (Stream_GetPosition(channel->dvc_data) + dataSize > (UINT32) Stream_Capacity(
channel->dvc_data))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "data exceeding declared length!");
Stream_Release(channel->dvc_data);
channel->dvc_data = NULL;
return ERROR_INVALID_DATA;
}
Stream_Write(channel->dvc_data, Stream_Pointer(data), dataSize);
if (Stream_GetPosition(channel->dvc_data) >= channel->dvc_data_length)
{
Stream_SealLength(channel->dvc_data);
Stream_SetPosition(channel->dvc_data, 0);
status = channel->channel_callback->OnDataReceived(channel->channel_callback,
channel->dvc_data);
Stream_Release(channel->dvc_data);
channel->dvc_data = NULL;
}
}
else
{
status = channel->channel_callback->OnDataReceived(channel->channel_callback,
data);
}
return status;
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID:
|
static UINT dvcman_receive_channel_data(drdynvcPlugin* drdynvc,
IWTSVirtualChannelManager* pChannelMgr,
UINT32 ChannelId, wStream* data)
{
UINT status = CHANNEL_RC_OK;
DVCMAN_CHANNEL* channel;
size_t dataSize = Stream_GetRemainingLength(data);
channel = (DVCMAN_CHANNEL*) dvcman_find_channel_by_id(pChannelMgr, ChannelId);
if (!channel)
{
/* Windows 8.1 tries to open channels not created.
* Ignore cases like this. */
WLog_Print(drdynvc->log, WLOG_ERROR, "ChannelId %"PRIu32" not found!", ChannelId);
return CHANNEL_RC_OK;
}
if (channel->dvc_data)
{
/* Fragmented data */
if (Stream_GetPosition(channel->dvc_data) + dataSize > Stream_Capacity(channel->dvc_data))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "data exceeding declared length!");
Stream_Release(channel->dvc_data);
channel->dvc_data = NULL;
return ERROR_INVALID_DATA;
}
Stream_Copy(data, channel->dvc_data, dataSize);
if (Stream_GetPosition(channel->dvc_data) >= channel->dvc_data_length)
{
Stream_SealLength(channel->dvc_data);
Stream_SetPosition(channel->dvc_data, 0);
status = channel->channel_callback->OnDataReceived(channel->channel_callback,
channel->dvc_data);
Stream_Release(channel->dvc_data);
channel->dvc_data = NULL;
}
}
else
{
status = channel->channel_callback->OnDataReceived(channel->channel_callback,
data);
}
return status;
}
| 168,940
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int ssd0323_load(QEMUFile *f, void *opaque, int version_id)
{
SSISlave *ss = SSI_SLAVE(opaque);
ssd0323_state *s = (ssd0323_state *)opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->cmd_len = qemu_get_be32(f);
s->cmd = qemu_get_be32(f);
for (i = 0; i < 8; i++)
s->cmd_data[i] = qemu_get_be32(f);
s->row = qemu_get_be32(f);
s->row_start = qemu_get_be32(f);
s->row_end = qemu_get_be32(f);
s->col = qemu_get_be32(f);
s->col_start = qemu_get_be32(f);
s->col_end = qemu_get_be32(f);
s->redraw = qemu_get_be32(f);
s->remap = qemu_get_be32(f);
s->mode = qemu_get_be32(f);
qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer));
ss->cs = qemu_get_be32(f);
}
Commit Message:
CWE ID: CWE-119
|
static int ssd0323_load(QEMUFile *f, void *opaque, int version_id)
{
SSISlave *ss = SSI_SLAVE(opaque);
ssd0323_state *s = (ssd0323_state *)opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->cmd_len = qemu_get_be32(f);
if (s->cmd_len < 0 || s->cmd_len > ARRAY_SIZE(s->cmd_data)) {
return -EINVAL;
}
s->cmd = qemu_get_be32(f);
for (i = 0; i < 8; i++)
s->cmd_data[i] = qemu_get_be32(f);
s->row = qemu_get_be32(f);
if (s->row < 0 || s->row >= 80) {
return -EINVAL;
}
s->row_start = qemu_get_be32(f);
if (s->row_start < 0 || s->row_start >= 80) {
return -EINVAL;
}
s->row_end = qemu_get_be32(f);
if (s->row_end < 0 || s->row_end >= 80) {
return -EINVAL;
}
s->col = qemu_get_be32(f);
if (s->col < 0 || s->col >= 64) {
return -EINVAL;
}
s->col_start = qemu_get_be32(f);
if (s->col_start < 0 || s->col_start >= 64) {
return -EINVAL;
}
s->col_end = qemu_get_be32(f);
if (s->col_end < 0 || s->col_end >= 64) {
return -EINVAL;
}
s->redraw = qemu_get_be32(f);
s->remap = qemu_get_be32(f);
s->mode = qemu_get_be32(f);
if (s->mode != SSD0323_CMD && s->mode != SSD0323_DATA) {
return -EINVAL;
}
qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer));
ss->cs = qemu_get_be32(f);
}
| 165,357
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir,
const FilePath& text) {
FilePath old_cur_directory;
if (!base_dir.empty()) {
file_util::GetCurrentDirectory(&old_cur_directory);
file_util::SetCurrentDirectory(base_dir);
}
FilePath::StringType trimmed;
PrepareStringForFileOps(text, &trimmed);
bool is_file = true;
FilePath full_path;
if (!ValidPathForFile(trimmed, &full_path)) {
#if defined(OS_WIN)
std::wstring unescaped = UTF8ToWide(UnescapeURLComponent(
WideToUTF8(trimmed),
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS));
#elif defined(OS_POSIX)
std::string unescaped = UnescapeURLComponent(
trimmed,
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);
#endif
if (!ValidPathForFile(unescaped, &full_path))
is_file = false;
}
if (!base_dir.empty())
file_util::SetCurrentDirectory(old_cur_directory);
if (is_file) {
GURL file_url = net::FilePathToFileURL(full_path);
if (file_url.is_valid())
return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL,
NULL, NULL)));
}
#if defined(OS_WIN)
std::string text_utf8 = WideToUTF8(text.value());
#elif defined(OS_POSIX)
std::string text_utf8 = text.value();
#endif
return FixupURL(text_utf8, std::string());
}
Commit Message: Be a little more careful whether something is an URL or a file path.
BUG=72492
Review URL: http://codereview.chromium.org/7572046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95731 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir,
const FilePath& text) {
FilePath old_cur_directory;
if (!base_dir.empty()) {
file_util::GetCurrentDirectory(&old_cur_directory);
file_util::SetCurrentDirectory(base_dir);
}
FilePath::StringType trimmed;
PrepareStringForFileOps(text, &trimmed);
bool is_file = true;
// Avoid recognizing definite non-file URLs as file paths.
GURL gurl(trimmed);
if (gurl.is_valid() && gurl.IsStandard())
is_file = false;
FilePath full_path;
if (is_file && !ValidPathForFile(trimmed, &full_path)) {
#if defined(OS_WIN)
std::wstring unescaped = UTF8ToWide(UnescapeURLComponent(
WideToUTF8(trimmed),
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS));
#elif defined(OS_POSIX)
std::string unescaped = UnescapeURLComponent(
trimmed,
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);
#endif
if (!ValidPathForFile(unescaped, &full_path))
is_file = false;
}
if (!base_dir.empty())
file_util::SetCurrentDirectory(old_cur_directory);
if (is_file) {
GURL file_url = net::FilePathToFileURL(full_path);
if (file_url.is_valid())
return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL,
NULL, NULL)));
}
#if defined(OS_WIN)
std::string text_utf8 = WideToUTF8(text.value());
#elif defined(OS_POSIX)
std::string text_utf8 = text.value();
#endif
return FixupURL(text_utf8, std::string());
}
| 170,364
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x00) { // Display ID
status = ParseDisplay(pReader, pos, size);
if (status < 0) // error
return status;
} else if (id == 0x1654) { // StringUID ID
status = UnserializeString(pReader, pos, size, m_string_uid);
if (status < 0) // error
return status;
} else if (id == 0x33C4) { // UID ID
long long val;
status = UnserializeInt(pReader, pos, size, val);
if (status < 0) // error
return status;
m_uid = static_cast<unsigned long long>(val);
} else if (id == 0x11) { // TimeStart ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_start_timecode = val;
} else if (id == 0x12) { // TimeEnd ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_stop_timecode = val;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x00) { // Display ID
status = ParseDisplay(pReader, pos, size);
if (status < 0) // error
return status;
} else if (id == 0x1654) { // StringUID ID
status = UnserializeString(pReader, pos, size, m_string_uid);
if (status < 0) // error
return status;
} else if (id == 0x33C4) { // UID ID
long long val;
status = UnserializeInt(pReader, pos, size, val);
if (status < 0) // error
return status;
m_uid = static_cast<unsigned long long>(val);
} else if (id == 0x11) { // TimeStart ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_start_timecode = val;
} else if (id == 0x12) { // TimeEnd ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_stop_timecode = val;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,840
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void _out_verify(conn_t out, nad_t nad) {
int attr, ns;
jid_t from, to;
conn_t in;
char *rkey;
int valid;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db verify packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db verify packet");
jid_free(from);
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "id", NULL);
if(attr < 0) {
log_debug(ZONE, "missing id on db verify packet");
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* get the incoming conn */
in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr));
if(in == NULL) {
log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
attr = nad_find_attr(nad, 0, -1, "type", "valid");
if(attr >= 0) {
xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID);
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : "");
valid = 1;
} else {
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey);
valid = 0;
}
free(rkey);
nad_free(nad);
/* decrement outstanding verify counter */
--out->verify;
/* let them know what happened */
nad = nad_new();
ns = nad_add_namespace(nad, uri_DIALBACK, "db");
nad_append_elem(nad, ns, "result", 0);
nad_append_attr(nad, -1, "to", from->domain);
nad_append_attr(nad, -1, "from", to->domain);
nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid");
/* off it goes */
sx_nad_write(in->s, nad);
/* if invalid, close the stream */
if (!valid) {
/* generate stream error */
sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the incoming stream */
sx_close(in->s);
}
jid_free(from);
jid_free(to);
}
Commit Message: Fixed possibility of Unsolicited Dialback Attacks
CWE ID: CWE-20
|
static void _out_verify(conn_t out, nad_t nad) {
int attr, ns;
jid_t from, to;
conn_t in;
char *rkey;
int valid;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db verify packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db verify packet");
jid_free(from);
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "id", NULL);
if(attr < 0) {
log_debug(ZONE, "missing id on db verify packet");
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* get the incoming conn */
in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr));
if(in == NULL) {
log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
attr = nad_find_attr(nad, 0, -1, "type", "valid");
if(attr >= 0 && xhash_get(in->states, rkey) == (void*) conn_INPROGRESS) {
xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID);
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : "");
valid = 1;
} else {
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey);
valid = 0;
}
free(rkey);
nad_free(nad);
/* decrement outstanding verify counter */
--out->verify;
/* let them know what happened */
nad = nad_new();
ns = nad_add_namespace(nad, uri_DIALBACK, "db");
nad_append_elem(nad, ns, "result", 0);
nad_append_attr(nad, -1, "to", from->domain);
nad_append_attr(nad, -1, "from", to->domain);
nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid");
/* off it goes */
sx_nad_write(in->s, nad);
/* if invalid, close the stream */
if (!valid) {
/* generate stream error */
sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the incoming stream */
sx_close(in->s);
}
jid_free(from);
jid_free(to);
}
| 165,577
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: speech_synthesizer_(NULL),
paused_(false) {
CoCreateInstance(
CLSID_SpVoice,
NULL,
CLSCTX_SERVER,
IID_ISpVoice,
reinterpret_cast<void**>(&speech_synthesizer_));
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: speech_synthesizer_(NULL),
paused_(false) {
CoCreateInstance(
CLSID_SpVoice,
NULL,
CLSCTX_SERVER,
IID_ISpVoice,
reinterpret_cast<void**>(&speech_synthesizer_));
if (speech_synthesizer_) {
ULONGLONG event_mask =
SPFEI(SPEI_START_INPUT_STREAM) |
SPFEI(SPEI_TTS_BOOKMARK) |
SPFEI(SPEI_WORD_BOUNDARY) |
SPFEI(SPEI_SENTENCE_BOUNDARY) |
SPFEI(SPEI_END_INPUT_STREAM);
speech_synthesizer_->SetInterest(event_mask, event_mask);
speech_synthesizer_->SetNotifyCallbackFunction(
ExtensionTtsPlatformImplWin::SpeechEventCallback, 0, 0);
}
}
| 170,401
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: explicit SyncInternal(const std::string& name)
: name_(name),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
enable_sync_tabs_for_other_clients_(false),
registrar_(NULL),
change_delegate_(NULL),
initialized_(false),
testing_mode_(NON_TEST),
observing_ip_address_changes_(false),
traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord),
encryptor_(NULL),
unrecoverable_error_handler_(NULL),
report_unrecoverable_error_function_(NULL),
created_on_loop_(MessageLoop::current()),
nigori_overwrite_count_(0) {
for (int i = syncable::FIRST_REAL_MODEL_TYPE;
i < syncable::MODEL_TYPE_COUNT; ++i) {
notification_info_map_.insert(
std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo()));
}
BindJsMessageHandler(
"getNotificationState",
&SyncManager::SyncInternal::GetNotificationState);
BindJsMessageHandler(
"getNotificationInfo",
&SyncManager::SyncInternal::GetNotificationInfo);
BindJsMessageHandler(
"getRootNodeDetails",
&SyncManager::SyncInternal::GetRootNodeDetails);
BindJsMessageHandler(
"getNodeSummariesById",
&SyncManager::SyncInternal::GetNodeSummariesById);
BindJsMessageHandler(
"getNodeDetailsById",
&SyncManager::SyncInternal::GetNodeDetailsById);
BindJsMessageHandler(
"getAllNodes",
&SyncManager::SyncInternal::GetAllNodes);
BindJsMessageHandler(
"getChildNodeIds",
&SyncManager::SyncInternal::GetChildNodeIds);
BindJsMessageHandler(
"getClientServerTraffic",
&SyncManager::SyncInternal::GetClientServerTraffic);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
|
explicit SyncInternal(const std::string& name)
: name_(name),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
registrar_(NULL),
change_delegate_(NULL),
initialized_(false),
testing_mode_(NON_TEST),
observing_ip_address_changes_(false),
traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord),
encryptor_(NULL),
unrecoverable_error_handler_(NULL),
report_unrecoverable_error_function_(NULL),
created_on_loop_(MessageLoop::current()),
nigori_overwrite_count_(0) {
for (int i = syncable::FIRST_REAL_MODEL_TYPE;
i < syncable::MODEL_TYPE_COUNT; ++i) {
notification_info_map_.insert(
std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo()));
}
BindJsMessageHandler(
"getNotificationState",
&SyncManager::SyncInternal::GetNotificationState);
BindJsMessageHandler(
"getNotificationInfo",
&SyncManager::SyncInternal::GetNotificationInfo);
BindJsMessageHandler(
"getRootNodeDetails",
&SyncManager::SyncInternal::GetRootNodeDetails);
BindJsMessageHandler(
"getNodeSummariesById",
&SyncManager::SyncInternal::GetNodeSummariesById);
BindJsMessageHandler(
"getNodeDetailsById",
&SyncManager::SyncInternal::GetNodeDetailsById);
BindJsMessageHandler(
"getAllNodes",
&SyncManager::SyncInternal::GetAllNodes);
BindJsMessageHandler(
"getChildNodeIds",
&SyncManager::SyncInternal::GetChildNodeIds);
BindJsMessageHandler(
"getClientServerTraffic",
&SyncManager::SyncInternal::GetClientServerTraffic);
}
| 170,797
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
} else {
URI_CHAR * afterKey;
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
afterKey = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
write += (afterKey - write);
if (value != NULL) {
URI_CHAR * afterValue;
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
afterValue = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
write += (afterValue - write);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
}
Commit Message: UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex
Reported by Google Autofuzz team
CWE ID: CWE-787
|
int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
} else {
URI_CHAR * afterKey;
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
afterKey = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
write += (afterKey - write);
if (value != NULL) {
URI_CHAR * afterValue;
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
afterValue = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
write += (afterValue - write);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
}
| 168,976
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RegisterProperties(IBusPropList* ibus_prop_list) {
DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
RegisterProperties(NULL);
return;
}
}
register_ime_properties_(language_library_, prop_list);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void RegisterProperties(IBusPropList* ibus_prop_list) {
void DoRegisterProperties(IBusPropList* ibus_prop_list) {
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
DoRegisterProperties(NULL);
return;
}
}
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
| 170,544
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher(
const GURL& url) {
std::unique_ptr<net::URLFetcher> fetcher =
net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
fetcher->SetRequestContext(helper_->request_context());
fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
fetcher->SetAutomaticallyRetryOnNetworkChanges(1);
return fetcher;
}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
CWE ID: CWE-190
|
GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher(
const GURL& url) {
std::unique_ptr<net::URLFetcher> fetcher =
net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
fetcher->SetRequestContext(helper_->request_context());
fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
data_use_measurement::DataUseUserData::AttachToFetcher(
fetcher.get(), data_use_measurement::DataUseUserData::SIGNIN);
fetcher->SetAutomaticallyRetryOnNetworkChanges(1);
return fetcher;
}
| 172,019
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: chunk_type_valid(png_uint_32 c)
/* Bit whacking approach to chunk name validation that is intended to avoid
* branches. The cost is that it uses a lot of 32-bit constants, which might
* be bad on some architectures.
*/
{
png_uint_32 t;
/* Remove bit 5 from all but the reserved byte; this means every
* 8-bit unit must be in the range 65-90 to be valid. So bit 5
* must be zero, bit 6 must be set and bit 7 zero.
*/
c &= ~PNG_U32(32,32,0,32);
t = (c & ~0x1f1f1f1f) ^ 0x40404040;
/* Subtract 65 for each 8 bit quantity, this must not overflow
* and each byte must then be in the range 0-25.
*/
c -= PNG_U32(65,65,65,65);
t |=c ;
/* Subtract 26, handling the overflow which should set the top
* three bits of each byte.
*/
c -= PNG_U32(25,25,25,26);
t |= ~c;
return (t & 0xe0e0e0e0) == 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
chunk_type_valid(png_uint_32 c)
/* Bit whacking approach to chunk name validation that is intended to avoid
* branches. The cost is that it uses a lot of 32-bit constants, which might
* be bad on some architectures.
*/
{
png_uint_32 t;
/* Remove bit 5 from all but the reserved byte; this means every
* 8-bit unit must be in the range 65-90 to be valid. So bit 5
* must be zero, bit 6 must be set and bit 7 zero.
*/
c &= ~PNG_U32(32,32,0,32);
t = (c & ~0x1f1f1f1f) ^ 0x40404040;
/* Subtract 65 for each 8-bit quantity, this must not overflow
* and each byte must then be in the range 0-25.
*/
c -= PNG_U32(65,65,65,65);
t |=c ;
/* Subtract 26, handling the overflow which should set the top
* three bits of each byte.
*/
c -= PNG_U32(25,25,25,26);
t |= ~c;
return (t & 0xe0e0e0e0) == 0;
}
| 173,730
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag)
{
QString ret;
QString tag;
int i = data->openHtmlTags.count() - 1;
for ( ; i >= 0 ; --i)
{
tag = data->openHtmlTags.at(i);
ret += QLatin1String("</") + tag + QLatin1Char('>');
if (tag == _tag)
{
data->openHtmlTags.removeAt(i);
break;
}
}
ret += openTags(data, i);
return ret;
}
Commit Message:
CWE ID:
|
QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag)
{
QString ret;
QString tag;
int i = data->openHtmlTags.count() - 1;
for ( ; i >= 0 ; --i)
{
tag = data->openHtmlTags.at(i);
ret += QLatin1String("</") + tag + QLatin1Char('>');
if (tag == _tag)
{
data->openHtmlTags.removeAt(i);
break;
}
}
if (i > -1)
ret += openTags(data, i);
return ret;
}
| 164,648
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
Commit Message: userns: Check uid_map's opener's fsuid, not the current fsuid
Signed-off-by: Andy Lutomirski <luto@amacapital.net>
CWE ID: CWE-264
|
static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, file->f_cred->fsuid))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, file->f_cred->fsgid))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
| 169,895
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat)
l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
| 167,892
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer,
raptor_option option)
{
int result = -1;
switch(option) {
case RAPTOR_OPTION_WRITER_AUTO_INDENT:
result = TURTLE_WRITER_AUTO_INDENT(turtle_writer);
break;
case RAPTOR_OPTION_WRITER_INDENT_WIDTH:
result = turtle_writer->indent;
break;
/* writer options */
case RAPTOR_OPTION_WRITER_AUTO_EMPTY:
case RAPTOR_OPTION_WRITER_XML_VERSION:
case RAPTOR_OPTION_WRITER_XML_DECLARATION:
/* parser options */
case RAPTOR_OPTION_SCANNING:
case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES:
case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES:
case RAPTOR_OPTION_ALLOW_BAGID:
case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST:
case RAPTOR_OPTION_NORMALIZE_LANGUAGE:
case RAPTOR_OPTION_NON_NFC_FATAL:
case RAPTOR_OPTION_WARN_OTHER_PARSETYPES:
case RAPTOR_OPTION_CHECK_RDF_ID:
case RAPTOR_OPTION_HTML_TAG_SOUP:
case RAPTOR_OPTION_MICROFORMATS:
case RAPTOR_OPTION_HTML_LINK:
case RAPTOR_OPTION_WWW_TIMEOUT:
case RAPTOR_OPTION_STRICT:
/* Shared */
case RAPTOR_OPTION_NO_NET:
case RAPTOR_OPTION_NO_FILE:
/* XML writer options */
case RAPTOR_OPTION_RELATIVE_URIS:
/* DOT serializer options */
case RAPTOR_OPTION_RESOURCE_BORDER:
case RAPTOR_OPTION_LITERAL_BORDER:
case RAPTOR_OPTION_BNODE_BORDER:
case RAPTOR_OPTION_RESOURCE_FILL:
case RAPTOR_OPTION_LITERAL_FILL:
case RAPTOR_OPTION_BNODE_FILL:
/* JSON serializer options */
case RAPTOR_OPTION_JSON_CALLBACK:
case RAPTOR_OPTION_JSON_EXTRA_DATA:
case RAPTOR_OPTION_RSS_TRIPLES:
case RAPTOR_OPTION_ATOM_ENTRY_URI:
case RAPTOR_OPTION_PREFIX_ELEMENTS:
/* Turtle serializer option */
case RAPTOR_OPTION_WRITE_BASE_URI:
/* WWW option */
case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL:
case RAPTOR_OPTION_WWW_HTTP_USER_AGENT:
case RAPTOR_OPTION_WWW_CERT_FILENAME:
case RAPTOR_OPTION_WWW_CERT_TYPE:
case RAPTOR_OPTION_WWW_CERT_PASSPHRASE:
case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER:
case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST:
default:
break;
}
return result;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200
|
raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer,
raptor_option option)
{
int result = -1;
switch(option) {
case RAPTOR_OPTION_WRITER_AUTO_INDENT:
result = TURTLE_WRITER_AUTO_INDENT(turtle_writer);
break;
case RAPTOR_OPTION_WRITER_INDENT_WIDTH:
result = turtle_writer->indent;
break;
/* writer options */
case RAPTOR_OPTION_WRITER_AUTO_EMPTY:
case RAPTOR_OPTION_WRITER_XML_VERSION:
case RAPTOR_OPTION_WRITER_XML_DECLARATION:
/* parser options */
case RAPTOR_OPTION_SCANNING:
case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES:
case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES:
case RAPTOR_OPTION_ALLOW_BAGID:
case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST:
case RAPTOR_OPTION_NORMALIZE_LANGUAGE:
case RAPTOR_OPTION_NON_NFC_FATAL:
case RAPTOR_OPTION_WARN_OTHER_PARSETYPES:
case RAPTOR_OPTION_CHECK_RDF_ID:
case RAPTOR_OPTION_HTML_TAG_SOUP:
case RAPTOR_OPTION_MICROFORMATS:
case RAPTOR_OPTION_HTML_LINK:
case RAPTOR_OPTION_WWW_TIMEOUT:
case RAPTOR_OPTION_STRICT:
/* Shared */
case RAPTOR_OPTION_NO_NET:
case RAPTOR_OPTION_NO_FILE:
case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES:
/* XML writer options */
case RAPTOR_OPTION_RELATIVE_URIS:
/* DOT serializer options */
case RAPTOR_OPTION_RESOURCE_BORDER:
case RAPTOR_OPTION_LITERAL_BORDER:
case RAPTOR_OPTION_BNODE_BORDER:
case RAPTOR_OPTION_RESOURCE_FILL:
case RAPTOR_OPTION_LITERAL_FILL:
case RAPTOR_OPTION_BNODE_FILL:
/* JSON serializer options */
case RAPTOR_OPTION_JSON_CALLBACK:
case RAPTOR_OPTION_JSON_EXTRA_DATA:
case RAPTOR_OPTION_RSS_TRIPLES:
case RAPTOR_OPTION_ATOM_ENTRY_URI:
case RAPTOR_OPTION_PREFIX_ELEMENTS:
/* Turtle serializer option */
case RAPTOR_OPTION_WRITE_BASE_URI:
/* WWW option */
case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL:
case RAPTOR_OPTION_WWW_HTTP_USER_AGENT:
case RAPTOR_OPTION_WWW_CERT_FILENAME:
case RAPTOR_OPTION_WWW_CERT_TYPE:
case RAPTOR_OPTION_WWW_CERT_PASSPHRASE:
case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER:
case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST:
default:
break;
}
return result;
}
| 165,662
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void tokenadd(struct jv_parser* p, char c) {
assert(p->tokenpos <= p->tokenlen);
if (p->tokenpos == p->tokenlen) {
p->tokenlen = p->tokenlen*2 + 256;
p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen);
}
assert(p->tokenpos < p->tokenlen);
p->tokenbuf[p->tokenpos++] = c;
}
Commit Message: Heap buffer overflow in tokenadd() (fix #105)
This was an off-by one: the NUL terminator byte was not allocated on
resize. This was triggered by JSON-encoded numbers longer than 256
bytes.
CWE ID: CWE-119
|
static void tokenadd(struct jv_parser* p, char c) {
assert(p->tokenpos <= p->tokenlen);
if (p->tokenpos >= (p->tokenlen - 1)) {
p->tokenlen = p->tokenlen*2 + 256;
p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen);
}
assert(p->tokenpos < p->tokenlen);
p->tokenbuf[p->tokenpos++] = c;
}
| 167,477
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: kex_input_newkeys(int type, u_int32_t seq, void *ctxt)
{
struct ssh *ssh = ctxt;
struct kex *kex = ssh->kex;
int r;
debug("SSH2_MSG_NEWKEYS received");
ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
if ((r = sshpkt_get_end(ssh)) != 0)
return r;
kex->done = 1;
sshbuf_reset(kex->peer);
/* sshbuf_reset(kex->my); */
kex->name = NULL;
return 0;
}
Commit Message:
CWE ID: CWE-476
|
kex_input_newkeys(int type, u_int32_t seq, void *ctxt)
{
struct ssh *ssh = ctxt;
struct kex *kex = ssh->kex;
int r;
debug("SSH2_MSG_NEWKEYS received");
ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
if ((r = sshpkt_get_end(ssh)) != 0)
return r;
if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0)
return r;
kex->done = 1;
sshbuf_reset(kex->peer);
/* sshbuf_reset(kex->my); */
kex->name = NULL;
return 0;
}
| 165,483
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics(
const page_load_metrics::PageLoadExtraInfo& info,
base::TimeTicks app_background_time) {
ukm::builders::PageLoad builder(info.source_id);
base::Optional<base::TimeDelta> foreground_duration =
page_load_metrics::GetInitialForegroundDuration(info,
app_background_time);
if (foreground_duration) {
builder.SetPageTiming_ForegroundDuration(
foreground_duration.value().InMilliseconds());
}
metrics::SystemProfileProto::Network::EffectiveConnectionType
proto_effective_connection_type =
metrics::ConvertEffectiveConnectionType(effective_connection_type_);
if (proto_effective_connection_type !=
metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
builder.SetNet_EffectiveConnectionType2_OnNavigationStart(
static_cast<int64_t>(proto_effective_connection_type));
}
if (http_response_code_) {
builder.SetNet_HttpResponseCode(
static_cast<int64_t>(http_response_code_.value()));
}
if (http_rtt_estimate_) {
builder.SetNet_HttpRttEstimate_OnNavigationStart(
static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds()));
}
if (transport_rtt_estimate_) {
builder.SetNet_TransportRttEstimate_OnNavigationStart(
static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds()));
}
if (downstream_kbps_estimate_) {
builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart(
static_cast<int64_t>(downstream_kbps_estimate_.value()));
}
builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_));
builder.SetNavigation_PageEndReason(
static_cast<int64_t>(info.page_end_reason));
if (info.did_commit && was_cached_) {
builder.SetWasCached(1);
}
builder.Record(ukm::UkmRecorder::Get());
}
Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation.
Also refactor UkmPageLoadMetricsObserver to use this new boolean to
report the user initiated metric in RecordPageLoadExtraInfoMetrics, so
that it works correctly in the case when the page load failed.
Bug: 925104
Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff
Reviewed-on: https://chromium-review.googlesource.com/c/1450460
Commit-Queue: Annie Sullivan <sullivan@chromium.org>
Reviewed-by: Bryan McQuade <bmcquade@chromium.org>
Cr-Commit-Position: refs/heads/master@{#630870}
CWE ID: CWE-79
|
void UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics(
const page_load_metrics::PageLoadExtraInfo& info,
base::TimeTicks app_background_time) {
ukm::builders::PageLoad builder(info.source_id);
base::Optional<base::TimeDelta> foreground_duration =
page_load_metrics::GetInitialForegroundDuration(info,
app_background_time);
if (foreground_duration) {
builder.SetPageTiming_ForegroundDuration(
foreground_duration.value().InMilliseconds());
}
bool is_user_initiated_navigation =
// All browser initiated page loads are user-initiated.
info.user_initiated_info.browser_initiated ||
// Renderer-initiated navigations are user-initiated if there is an
// associated input event.
info.user_initiated_info.user_input_event;
builder.SetExperimental_Navigation_UserInitiated(
is_user_initiated_navigation);
metrics::SystemProfileProto::Network::EffectiveConnectionType
proto_effective_connection_type =
metrics::ConvertEffectiveConnectionType(effective_connection_type_);
if (proto_effective_connection_type !=
metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
builder.SetNet_EffectiveConnectionType2_OnNavigationStart(
static_cast<int64_t>(proto_effective_connection_type));
}
if (http_response_code_) {
builder.SetNet_HttpResponseCode(
static_cast<int64_t>(http_response_code_.value()));
}
if (http_rtt_estimate_) {
builder.SetNet_HttpRttEstimate_OnNavigationStart(
static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds()));
}
if (transport_rtt_estimate_) {
builder.SetNet_TransportRttEstimate_OnNavigationStart(
static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds()));
}
if (downstream_kbps_estimate_) {
builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart(
static_cast<int64_t>(downstream_kbps_estimate_.value()));
}
builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_));
builder.SetNavigation_PageEndReason(
static_cast<int64_t>(info.page_end_reason));
if (info.did_commit && was_cached_) {
builder.SetWasCached(1);
}
builder.Record(ukm::UkmRecorder::Get());
}
| 172,496
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void opl3_panning(int dev, int voice, int value)
{
devc->voc[voice].panning = value;
}
Commit Message: sound/oss/opl3: validate voice and channel indexes
User-controllable indexes for voice and channel values may cause reading
and writing beyond the bounds of their respective arrays, leading to
potentially exploitable memory corruption. Validate these indexes.
Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com>
Cc: stable@kernel.org
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID: CWE-119
|
static void opl3_panning(int dev, int voice, int value)
{
if (voice < 0 || voice >= devc->nr_voice)
return;
devc->voc[voice].panning = value;
}
| 165,890
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
const struct xfrm_link *link;
int type, err;
#ifdef CONFIG_COMPAT
if (in_compat_syscall())
return -EOPNOTSUPP;
#endif
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!netlink_net_capable(skb, CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs,
link->nla_max ? : XFRMA_MAX,
link->nla_pol ? : xfrma_policy, extack);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
Commit Message: ipsec: Fix aborted xfrm policy dump crash
An independent security researcher, Mohamed Ghannam, has reported
this vulnerability to Beyond Security's SecuriTeam Secure Disclosure
program.
The xfrm_dump_policy_done function expects xfrm_dump_policy to
have been called at least once or it will crash. This can be
triggered if a dump fails because the target socket's receive
buffer is full.
This patch fixes it by using the cb->start mechanism to ensure that
the initialisation is always done regardless of the buffer situation.
Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list")
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com>
CWE ID: CWE-416
|
static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
const struct xfrm_link *link;
int type, err;
#ifdef CONFIG_COMPAT
if (in_compat_syscall())
return -EOPNOTSUPP;
#endif
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!netlink_net_capable(skb, CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.start = link->start,
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs,
link->nla_max ? : XFRMA_MAX,
link->nla_pol ? : xfrma_policy, extack);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
| 167,664
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, mode_t openflags, struct nfs4_state **res)
{
struct nfs4_state *newstate;
int ret;
opendata->o_arg.open_flags = openflags;
memset(&opendata->o_res, 0, sizeof(opendata->o_res));
memset(&opendata->c_res, 0, sizeof(opendata->c_res));
nfs4_init_opendata_res(opendata);
ret = _nfs4_proc_open(opendata);
if (ret != 0)
return ret;
newstate = nfs4_opendata_to_nfs4_state(opendata);
if (IS_ERR(newstate))
return PTR_ERR(newstate);
nfs4_close_state(&opendata->path, newstate, openflags);
*res = newstate;
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, mode_t openflags, struct nfs4_state **res)
static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, fmode_t fmode, struct nfs4_state **res)
{
struct nfs4_state *newstate;
int ret;
opendata->o_arg.open_flags = 0;
opendata->o_arg.fmode = fmode;
memset(&opendata->o_res, 0, sizeof(opendata->o_res));
memset(&opendata->c_res, 0, sizeof(opendata->c_res));
nfs4_init_opendata_res(opendata);
ret = _nfs4_proc_open(opendata);
if (ret != 0)
return ret;
newstate = nfs4_opendata_to_nfs4_state(opendata);
if (IS_ERR(newstate))
return PTR_ERR(newstate);
nfs4_close_state(&opendata->path, newstate, fmode);
*res = newstate;
return 0;
}
| 165,696
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: IDAT_list_extend(struct IDAT_list *tail)
{
/* Use the previous cached value if available. */
struct IDAT_list *next = tail->next;
if (next == NULL)
{
/* Insert a new, malloc'ed, block of IDAT information buffers, this
* one twice as large as the previous one:
*/
unsigned int length = 2 * tail->length;
if (length < tail->length) /* arithmetic overflow */
length = tail->length;
next = png_voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length)));
CLEAR(*next);
/* The caller must handle this: */
if (next == NULL)
return NULL;
next->next = NULL;
next->length = length;
tail->next = next;
}
return next;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
IDAT_list_extend(struct IDAT_list *tail)
{
/* Use the previous cached value if available. */
struct IDAT_list *next = tail->next;
if (next == NULL)
{
/* Insert a new, malloc'ed, block of IDAT information buffers, this
* one twice as large as the previous one:
*/
unsigned int length = 2 * tail->length;
if (length < tail->length) /* arithmetic overflow */
length = tail->length;
next = voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length)));
CLEAR(*next);
/* The caller must handle this: */
if (next == NULL)
return NULL;
next->next = NULL;
next->length = length;
tail->next = next;
}
return next;
}
| 173,728
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval;
zval tmp;
int compiler_result;
zend_bool original_in_compilation = CG(in_compilation);
if (source_string->value.str.len==0) {
efree(op_array);
return NULL;
}
CG(in_compilation) = 1;
tmp = *source_string;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
source_string = &tmp;
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) {
efree(op_array);
retval = NULL;
} else {
zend_bool orig_interactive = CG(interactive);
CG(interactive) = 0;
init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(interactive) = orig_interactive;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
BEGIN(ST_IN_SCRIPTING);
compiler_result = zendparse(TSRMLS_C);
if (SCNG(script_filtered)) {
efree(SCNG(script_filtered));
SCNG(script_filtered) = NULL;
}
if (compiler_result==1) {
CG(active_op_array) = original_active_op_array;
CG(unclean_shutdown)=1;
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
retval = NULL;
} else {
zend_do_return(NULL, 0 TSRMLS_CC);
CG(active_op_array) = original_active_op_array;
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
retval = op_array;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
zval_dtor(&tmp);
CG(in_compilation) = original_in_compilation;
return retval;
}
Commit Message: fix bug #64660 - yyparse can return 2, not only 1
CWE ID: CWE-20
|
zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval;
zval tmp;
int compiler_result;
zend_bool original_in_compilation = CG(in_compilation);
if (source_string->value.str.len==0) {
efree(op_array);
return NULL;
}
CG(in_compilation) = 1;
tmp = *source_string;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
source_string = &tmp;
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) {
efree(op_array);
retval = NULL;
} else {
zend_bool orig_interactive = CG(interactive);
CG(interactive) = 0;
init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(interactive) = orig_interactive;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
BEGIN(ST_IN_SCRIPTING);
compiler_result = zendparse(TSRMLS_C);
if (SCNG(script_filtered)) {
efree(SCNG(script_filtered));
SCNG(script_filtered) = NULL;
}
if (compiler_result != 0) {
CG(active_op_array) = original_active_op_array;
CG(unclean_shutdown)=1;
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
retval = NULL;
} else {
zend_do_return(NULL, 0 TSRMLS_CC);
CG(active_op_array) = original_active_op_array;
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
retval = op_array;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
zval_dtor(&tmp);
CG(in_compilation) = original_in_compilation;
return retval;
}
| 166,024
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: hook_print (struct t_weechat_plugin *plugin, struct t_gui_buffer *buffer,
const char *tags, const char *message, int strip_colors,
t_hook_callback_print *callback, void *callback_data)
{
struct t_hook *new_hook;
struct t_hook_print *new_hook_print;
if (!callback)
return NULL;
new_hook = malloc (sizeof (*new_hook));
if (!new_hook)
return NULL;
new_hook_print = malloc (sizeof (*new_hook_print));
if (!new_hook_print)
{
rc = (int) (HOOK_CONNECT(ptr_hook, gnutls_cb))
(ptr_hook->callback_data, tls_session, req_ca, nreq,
pk_algos, pk_algos_len, answer);
break;
}
ptr_hook = ptr_hook->next_hook;
new_hook->hook_data = new_hook_print;
new_hook_print->callback = callback;
new_hook_print->buffer = buffer;
if (tags)
{
new_hook_print->tags_array = string_split (tags, ",", 0, 0,
&new_hook_print->tags_count);
}
else
{
new_hook_print->tags_count = 0;
new_hook_print->tags_array = NULL;
}
new_hook_print->message = (message) ? strdup (message) : NULL;
new_hook_print->strip_colors = strip_colors;
hook_add_to_list (new_hook);
return new_hook;
}
Commit Message:
CWE ID: CWE-20
|
hook_print (struct t_weechat_plugin *plugin, struct t_gui_buffer *buffer,
const char *tags, const char *message, int strip_colors,
t_hook_callback_print *callback, void *callback_data)
{
struct t_hook *new_hook;
struct t_hook_print *new_hook_print;
if (!callback)
return NULL;
new_hook = malloc (sizeof (*new_hook));
if (!new_hook)
return NULL;
new_hook_print = malloc (sizeof (*new_hook_print));
if (!new_hook_print)
{
rc = (int) (HOOK_CONNECT(ptr_hook, gnutls_cb))
(ptr_hook->callback_data, tls_session, req_ca, nreq,
pk_algos, pk_algos_len, answer,
WEECHAT_HOOK_CONNECT_GNUTLS_CB_SET_CERT);
break;
}
ptr_hook = ptr_hook->next_hook;
new_hook->hook_data = new_hook_print;
new_hook_print->callback = callback;
new_hook_print->buffer = buffer;
if (tags)
{
new_hook_print->tags_array = string_split (tags, ",", 0, 0,
&new_hook_print->tags_count);
}
else
{
new_hook_print->tags_count = 0;
new_hook_print->tags_array = NULL;
}
new_hook_print->message = (message) ? strdup (message) : NULL;
new_hook_print->strip_colors = strip_colors;
hook_add_to_list (new_hook);
return new_hook;
}
| 164,711
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PageRequestSummary::UpdateOrAddToOrigins(
const GURL& url,
const content::mojom::CommonNetworkInfoPtr& network_info) {
GURL origin = url.GetOrigin();
if (!origin.is_valid())
return;
auto it = origins.find(origin);
if (it == origins.end()) {
OriginRequestSummary summary;
summary.origin = origin;
summary.first_occurrence = origins.size();
it = origins.insert({origin, summary}).first;
}
it->second.always_access_network |= network_info->always_access_network;
it->second.accessed_network |= network_info->network_accessed;
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
void PageRequestSummary::UpdateOrAddToOrigins(
const url::Origin& origin,
const content::mojom::CommonNetworkInfoPtr& network_info) {
if (origin.opaque())
return;
auto it = origins.find(origin);
if (it == origins.end()) {
OriginRequestSummary summary;
summary.origin = origin;
summary.first_occurrence = origins.size();
it = origins.insert({origin, summary}).first;
}
it->second.always_access_network |= network_info->always_access_network;
it->second.accessed_network |= network_info->network_accessed;
}
| 172,368
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
Commit Message:
CWE ID: CWE-119
|
static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc0(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
| 164,908
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context,
MIMETypeCheck mime_type_check) const {
if (ErrorOccurred())
return false;
KURL sheet_url = GetResponse().Url();
if (sheet_url.IsLocalFile()) {
if (parser_context) {
parser_context->Count(WebFeature::kLocalCSSFile);
}
String extension;
int last_dot = sheet_url.LastPathComponent().ReverseFind('.');
if (last_dot != -1)
extension = sheet_url.LastPathComponent().Substring(last_dot + 1);
if (!EqualIgnoringASCIICase(
MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) {
if (parser_context) {
parser_context->CountDeprecation(
WebFeature::kLocalCSSFileExtensionRejected);
}
if (RuntimeEnabledFeatures::RequireCSSExtensionForFileEnabled()) {
return false;
}
}
}
if (mime_type_check == MIMETypeCheck::kLax)
return true;
AtomicString content_type = HttpContentType();
return content_type.IsEmpty() ||
DeprecatedEqualIgnoringCase(content_type, "text/css") ||
DeprecatedEqualIgnoringCase(content_type,
"application/x-unknown-content-type");
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <mkwst@chromium.org>
Reviewed-by: Camille Lamy <clamy@chromium.org>
Commit-Queue: Dave Tapuska <dtapuska@chromium.org>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254
|
bool CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context,
MIMETypeCheck mime_type_check) const {
if (ErrorOccurred())
return false;
KURL sheet_url = GetResponse().Url();
if (sheet_url.IsLocalFile()) {
if (parser_context) {
parser_context->Count(WebFeature::kLocalCSSFile);
}
String extension;
int last_dot = sheet_url.LastPathComponent().ReverseFind('.');
if (last_dot != -1)
extension = sheet_url.LastPathComponent().Substring(last_dot + 1);
if (!EqualIgnoringASCIICase(
MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) {
if (parser_context) {
parser_context->CountDeprecation(
WebFeature::kLocalCSSFileExtensionRejected);
}
return false;
}
}
if (mime_type_check == MIMETypeCheck::kLax)
return true;
AtomicString content_type = HttpContentType();
return content_type.IsEmpty() ||
DeprecatedEqualIgnoringCase(content_type, "text/css") ||
DeprecatedEqualIgnoringCase(content_type,
"application/x-unknown-content-type");
}
| 173,186
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: kdc_process_for_user(kdc_realm_t *kdc_active_realm,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_pa_for_user *for_user;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_for_user(&req_data, &for_user);
if (code)
return code;
code = verify_for_user_checksum(kdc_context, tgs_session, for_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_for_user(kdc_context, for_user);
return code;
}
*s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user));
if (*s4u_x509_user == NULL) {
krb5_free_pa_for_user(kdc_context, for_user);
return ENOMEM;
}
(*s4u_x509_user)->user_id.user = for_user->user;
for_user->user = NULL;
krb5_free_pa_for_user(kdc_context, for_user);
return 0;
}
Commit Message: Prevent KDC unset status assertion failures
Assign status values if S4U2Self padata fails to decode, if an
S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request
uses an evidence ticket which does not match the canonicalized request
server principal name. Reported by Samuel Cabrero.
If a status value is not assigned during KDC processing, default to
"UNKNOWN_REASON" rather than failing an assertion. This change will
prevent future denial of service bugs due to similar mistakes, and
will allow us to omit assigning status values for unlikely errors such
as small memory allocation failures.
CVE-2017-11368:
In MIT krb5 1.7 and later, an authenticated attacker can cause an
assertion failure in krb5kdc by sending an invalid S4U2Self or
S4U2Proxy request.
CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C
ticket: 8599 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-617
|
kdc_process_for_user(kdc_realm_t *kdc_active_realm,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_pa_for_user *for_user;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_for_user(&req_data, &for_user);
if (code) {
*status = "DECODE_PA_FOR_USER";
return code;
}
code = verify_for_user_checksum(kdc_context, tgs_session, for_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_for_user(kdc_context, for_user);
return code;
}
*s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user));
if (*s4u_x509_user == NULL) {
krb5_free_pa_for_user(kdc_context, for_user);
return ENOMEM;
}
(*s4u_x509_user)->user_id.user = for_user->user;
for_user->user = NULL;
krb5_free_pa_for_user(kdc_context, for_user);
return 0;
}
| 168,041
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BufferMeta(size_t size)
: mSize(size),
mIsBackup(false) {
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
|
BufferMeta(size_t size)
BufferMeta(size_t size, OMX_U32 portIndex)
: mSize(size),
mIsBackup(false),
mPortIndex(portIndex) {
}
| 173,522
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static __u8 *pl_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 60 && rdesc[39] == 0x2a && rdesc[40] == 0xf5 &&
rdesc[41] == 0x00 && rdesc[59] == 0x26 &&
rdesc[60] == 0xf9 && rdesc[61] == 0x00) {
hid_info(hdev, "fixing up Petalynx Maxter Remote report descriptor\n");
rdesc[60] = 0xfa;
rdesc[40] = 0xfa;
}
return rdesc;
}
Commit Message: HID: fix a couple of off-by-ones
There are a few very theoretical off-by-one bugs in report descriptor size
checking when performing a pre-parsing fixup. Fix those.
Cc: stable@vger.kernel.org
Reported-by: Ben Hawkes <hawkes@google.com>
Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID: CWE-119
|
static __u8 *pl_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 62 && rdesc[39] == 0x2a && rdesc[40] == 0xf5 &&
rdesc[41] == 0x00 && rdesc[59] == 0x26 &&
rdesc[60] == 0xf9 && rdesc[61] == 0x00) {
hid_info(hdev, "fixing up Petalynx Maxter Remote report descriptor\n");
rdesc[60] = 0xfa;
rdesc[40] = 0xfa;
}
return rdesc;
}
| 166,374
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void NetworkHandler::GetAllCookies(
std::unique_ptr<GetAllCookiesCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
scoped_refptr<CookieRetriever> retriever =
new CookieRetriever(std::move(callback));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&CookieRetriever::RetrieveAllCookiesOnIO, retriever,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext())));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void NetworkHandler::GetAllCookies(
std::unique_ptr<GetAllCookiesCallback> callback) {
if (!storage_partition_) {
callback->sendFailure(Response::InternalError());
return;
}
scoped_refptr<CookieRetriever> retriever =
new CookieRetriever(std::move(callback));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&CookieRetriever::RetrieveAllCookiesOnIO, retriever,
base::Unretained(storage_partition_->GetURLRequestContext())));
}
| 172,756
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: 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
|
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*>(interstitial_page_->GetMainFrame())
->GetRenderWidgetHost()
->SetPageFocus(true);
} else {
GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
}
}
| 172,333
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
{
uint32_t old_val;
trace_esp_mem_readb(saddr, s->rregs[saddr]);
switch (saddr) {
case ESP_FIFO:
if (s->ti_size > 0) {
s->ti_size--;
if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) {
/* Data out. */
qemu_log_mask(LOG_UNIMP,
"esp: PIO data read not implemented\n");
s->rregs[ESP_FIFO] = 0;
} else {
s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++];
}
esp_raise_irq(s);
}
if (s->ti_size == 0) {
s->ti_rptr = 0;
s->ti_wptr = 0;
}
s->ti_wptr = 0;
}
break;
case ESP_RINTR:
/* Clear sequence step, interrupt register and all status bits
except TC */
old_val = s->rregs[ESP_RINTR];
s->rregs[ESP_RINTR] = 0;
s->rregs[ESP_RSTAT] &= ~STAT_TC;
s->rregs[ESP_RSEQ] = SEQ_CD;
esp_lower_irq(s);
return old_val;
case ESP_TCHI:
/* Return the unique id if the value has never been written */
if (!s->tchi_written) {
return s->chip_id;
}
default:
break;
}
Commit Message:
CWE ID: CWE-20
|
uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
{
uint32_t old_val;
trace_esp_mem_readb(saddr, s->rregs[saddr]);
switch (saddr) {
case ESP_FIFO:
if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) {
/* Data out. */
qemu_log_mask(LOG_UNIMP, "esp: PIO data read not implemented\n");
s->rregs[ESP_FIFO] = 0;
esp_raise_irq(s);
} else if (s->ti_rptr < s->ti_wptr) {
s->ti_size--;
s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++];
esp_raise_irq(s);
}
if (s->ti_rptr == s->ti_wptr) {
s->ti_rptr = 0;
s->ti_wptr = 0;
}
s->ti_wptr = 0;
}
break;
case ESP_RINTR:
/* Clear sequence step, interrupt register and all status bits
except TC */
old_val = s->rregs[ESP_RINTR];
s->rregs[ESP_RINTR] = 0;
s->rregs[ESP_RSTAT] &= ~STAT_TC;
s->rregs[ESP_RSEQ] = SEQ_CD;
esp_lower_irq(s);
return old_val;
case ESP_TCHI:
/* Return the unique id if the value has never been written */
if (!s->tchi_written) {
return s->chip_id;
}
default:
break;
}
| 165,012
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(locale_get_display_name)
{
get_icu_disp_value_src_php( DISP_NAME , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
PHP_FUNCTION(locale_get_display_name)
PHP_FUNCTION(locale_get_display_name)
{
get_icu_disp_value_src_php( DISP_NAME , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,185
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool config_save(const config_t *config, const char *filename) {
assert(config != NULL);
assert(filename != NULL);
assert(*filename != '\0');
char *temp_filename = osi_calloc(strlen(filename) + 5);
if (!temp_filename) {
LOG_ERROR("%s unable to allocate memory for filename.", __func__);
return false;
}
strcpy(temp_filename, filename);
strcat(temp_filename, ".new");
FILE *fp = fopen(temp_filename, "wt");
if (!fp) {
LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) {
const section_t *section = (const section_t *)list_node(node);
fprintf(fp, "[%s]\n", section->name);
for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) {
const entry_t *entry = (const entry_t *)list_node(enode);
fprintf(fp, "%s = %s\n", entry->key, entry->value);
}
if (list_next(node) != list_end(config->sections))
fputc('\n', fp);
}
fflush(fp);
fclose(fp);
if (chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) {
LOG_ERROR("%s unable to change file permissions '%s': %s", __func__, filename, strerror(errno));
goto error;
}
if (rename(temp_filename, filename) == -1) {
LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno));
goto error;
}
osi_free(temp_filename);
return true;
error:;
unlink(temp_filename);
osi_free(temp_filename);
return false;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
bool config_save(const config_t *config, const char *filename) {
assert(config != NULL);
assert(filename != NULL);
assert(*filename != '\0');
// Steps to ensure content of config file gets to disk:
//
// 1) Open and write to temp file (e.g. bt_config.conf.new).
// 2) Sync the temp file to disk with fsync().
// 3) Rename temp file to actual config file (e.g. bt_config.conf).
// This ensures atomic update.
// 4) Sync directory that has the conf file with fsync().
// This ensures directory entries are up-to-date.
int dir_fd = -1;
FILE *fp = NULL;
// Build temp config file based on config file (e.g. bt_config.conf.new).
static const char *temp_file_ext = ".new";
const int filename_len = strlen(filename);
const int temp_filename_len = filename_len + strlen(temp_file_ext) + 1;
char *temp_filename = osi_calloc(temp_filename_len);
snprintf(temp_filename, temp_filename_len, "%s%s", filename, temp_file_ext);
// Extract directory from file path (e.g. /data/misc/bluedroid).
char *temp_dirname = osi_strdup(filename);
const char *directoryname = dirname(temp_dirname);
if (!directoryname) {
LOG_ERROR("%s error extracting directory from '%s': %s", __func__, filename, strerror(errno));
goto error;
}
dir_fd = TEMP_FAILURE_RETRY(open(directoryname, O_RDONLY));
if (dir_fd < 0) {
LOG_ERROR("%s unable to open dir '%s': %s", __func__, directoryname, strerror(errno));
goto error;
}
fp = fopen(temp_filename, "wt");
if (!fp) {
LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) {
const section_t *section = (const section_t *)list_node(node);
if (fprintf(fp, "[%s]\n", section->name) < 0) {
LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) {
const entry_t *entry = (const entry_t *)list_node(enode);
if (fprintf(fp, "%s = %s\n", entry->key, entry->value) < 0) {
LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
}
if (list_next(node) != list_end(config->sections)) {
if (fputc('\n', fp) == EOF) {
LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
}
}
// Sync written temp file out to disk. fsync() is blocking until data makes it to disk.
if (fsync(fileno(fp)) < 0) {
LOG_WARN("%s unable to fsync file '%s': %s", __func__, temp_filename, strerror(errno));
}
if (fclose(fp) == EOF) {
LOG_ERROR("%s unable to close file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
fp = NULL;
if (chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) {
LOG_ERROR("%s unable to change file permissions '%s': %s", __func__, filename, strerror(errno));
goto error;
}
// Rename written temp file to the actual config file.
if (rename(temp_filename, filename) == -1) {
LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno));
goto error;
}
// This should ensure the directory is updated as well.
if (fsync(dir_fd) < 0) {
LOG_WARN("%s unable to fsync dir '%s': %s", __func__, directoryname, strerror(errno));
}
if (close(dir_fd) < 0) {
LOG_ERROR("%s unable to close dir '%s': %s", __func__, directoryname, strerror(errno));
goto error;
}
osi_free(temp_filename);
osi_free(temp_dirname);
return true;
error:
// This indicates there is a write issue. Unlink as partial data is not acceptable.
unlink(temp_filename);
if (fp)
fclose(fp);
if (dir_fd != -1)
close(dir_fd);
osi_free(temp_filename);
osi_free(temp_dirname);
return false;
}
| 173,479
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GpuMessageFilter::EstablishChannelCallback(
IPC::Message* reply,
const IPC::ChannelHandle& channel,
base::ProcessHandle gpu_process_for_browser,
const content::GPUInfo& gpu_info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
base::ProcessHandle renderer_process_for_gpu;
if (gpu_process_for_browser != 0) {
#if defined(OS_WIN)
DuplicateHandle(base::GetCurrentProcessHandle(),
peer_handle(),
gpu_process_for_browser,
&renderer_process_for_gpu,
PROCESS_DUP_HANDLE,
FALSE,
0);
#else
renderer_process_for_gpu = peer_handle();
#endif
} else {
renderer_process_for_gpu = 0;
}
GpuHostMsg_EstablishGpuChannel::WriteReplyParams(
reply, render_process_id_, channel, renderer_process_for_gpu, gpu_info);
Send(reply);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void GpuMessageFilter::EstablishChannelCallback(
IPC::Message* reply,
const IPC::ChannelHandle& channel,
const content::GPUInfo& gpu_info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
GpuHostMsg_EstablishGpuChannel::WriteReplyParams(
reply, render_process_id_, channel, gpu_info);
Send(reply);
}
| 170,925
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: _XcursorThemeInherits (const char *full)
{
char line[8192];
char *result = NULL;
FILE *f;
if (!full)
return NULL;
f = fopen (full, "r");
if (f)
{
while (fgets (line, sizeof (line), f))
{
if (!strncmp (line, "Inherits", 8))
{
char *l = line + 8;
char *r;
while (*l == ' ') l++;
if (*l != '=') continue;
l++;
while (*l == ' ') l++;
result = malloc (strlen (l));
if (result)
{
r = result;
while (*l)
{
while (XcursorSep(*l) || XcursorWhite (*l)) l++;
if (!*l)
break;
if (r != result)
*r++ = ':';
while (*l && !XcursorWhite(*l) &&
!XcursorSep(*l))
*r++ = *l++;
}
*r++ = '\0';
}
break;
}
}
fclose (f);
}
return result;
}
Commit Message:
CWE ID: CWE-119
|
_XcursorThemeInherits (const char *full)
{
char line[8192];
char *result = NULL;
FILE *f;
if (!full)
return NULL;
f = fopen (full, "r");
if (f)
{
while (fgets (line, sizeof (line), f))
{
if (!strncmp (line, "Inherits", 8))
{
char *l = line + 8;
char *r;
while (*l == ' ') l++;
if (*l != '=') continue;
l++;
while (*l == ' ') l++;
result = malloc (strlen (l) + 1);
if (result)
{
r = result;
while (*l)
{
while (XcursorSep(*l) || XcursorWhite (*l)) l++;
if (!*l)
break;
if (r != result)
*r++ = ':';
while (*l && !XcursorWhite(*l) &&
!XcursorSep(*l))
*r++ = *l++;
}
*r++ = '\0';
}
break;
}
}
fclose (f);
}
return result;
}
| 165,507
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
png_byte bit_depth, png_uint_32 x, store_palette palette)
{
PNG_CONST png_byte sample_depth = (png_byte)(colour_type ==
PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
PNG_CONST unsigned int max = (1U<<sample_depth)-1;
/* Initially just set everything to the same number and the alpha to opaque.
* Note that this currently assumes a simple palette where entry x has colour
* rgb(x,x,x)!
*/
this->palette_index = this->red = this->green = this->blue =
sample(row, colour_type, bit_depth, x, 0);
this->alpha = max;
this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
sample_depth;
/* Then override as appropriate: */
if (colour_type == 3) /* palette */
{
/* This permits the caller to default to the sample value. */
if (palette != 0)
{
PNG_CONST unsigned int i = this->palette_index;
this->red = palette[i].red;
this->green = palette[i].green;
this->blue = palette[i].blue;
this->alpha = palette[i].alpha;
}
}
else /* not palette */
{
unsigned int i = 0;
if (colour_type & 2)
{
this->green = sample(row, colour_type, bit_depth, x, 1);
this->blue = sample(row, colour_type, bit_depth, x, 2);
i = 2;
}
if (colour_type & 4)
this->alpha = sample(row, colour_type, bit_depth, x, ++i);
}
/* Calculate the scaled values, these are simply the values divided by
* 'max' and the error is initialized to the double precision epsilon value
* from the header file.
*/
image_pixel_setf(this, max);
/* Store the input information for use in the transforms - these will
* modify the information.
*/
this->colour_type = colour_type;
this->bit_depth = bit_depth;
this->sample_depth = sample_depth;
this->have_tRNS = 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
png_byte bit_depth, png_uint_32 x, store_palette palette,
const image_pixel *format /*from pngvalid transform of input*/)
{
const png_byte sample_depth = (png_byte)(colour_type ==
PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
const unsigned int max = (1U<<sample_depth)-1;
const int swap16 = (format != 0 && format->swap16);
const int littleendian = (format != 0 && format->littleendian);
const int sig_bits = (format != 0 && format->sig_bits);
/* Initially just set everything to the same number and the alpha to opaque.
* Note that this currently assumes a simple palette where entry x has colour
* rgb(x,x,x)!
*/
this->palette_index = this->red = this->green = this->blue =
sample(row, colour_type, bit_depth, x, 0, swap16, littleendian);
this->alpha = max;
this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
sample_depth;
/* Then override as appropriate: */
if (colour_type == 3) /* palette */
{
/* This permits the caller to default to the sample value. */
if (palette != 0)
{
const unsigned int i = this->palette_index;
this->red = palette[i].red;
this->green = palette[i].green;
this->blue = palette[i].blue;
this->alpha = palette[i].alpha;
}
}
else /* not palette */
{
unsigned int i = 0;
if ((colour_type & 4) != 0 && format != 0 && format->alpha_first)
{
this->alpha = this->red;
/* This handles the gray case for 'AG' pixels */
this->palette_index = this->red = this->green = this->blue =
sample(row, colour_type, bit_depth, x, 1, swap16, littleendian);
i = 1;
}
if (colour_type & 2)
{
/* Green is second for both BGR and RGB: */
this->green = sample(row, colour_type, bit_depth, x, ++i, swap16,
littleendian);
if (format != 0 && format->swap_rgb) /* BGR */
this->red = sample(row, colour_type, bit_depth, x, ++i, swap16,
littleendian);
else
this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16,
littleendian);
}
else /* grayscale */ if (format != 0 && format->mono_inverted)
this->red = this->green = this->blue = this->red ^ max;
if ((colour_type & 4) != 0) /* alpha */
{
if (format == 0 || !format->alpha_first)
this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16,
littleendian);
if (format != 0 && format->alpha_inverted)
this->alpha ^= max;
}
}
/* Calculate the scaled values, these are simply the values divided by
* 'max' and the error is initialized to the double precision epsilon value
* from the header file.
*/
image_pixel_setf(this,
sig_bits ? (1U << format->red_sBIT)-1 : max,
sig_bits ? (1U << format->green_sBIT)-1 : max,
sig_bits ? (1U << format->blue_sBIT)-1 : max,
sig_bits ? (1U << format->alpha_sBIT)-1 : max);
/* Store the input information for use in the transforms - these will
* modify the information.
*/
this->colour_type = colour_type;
this->bit_depth = bit_depth;
this->sample_depth = sample_depth;
this->have_tRNS = 0;
this->swap_rgb = 0;
this->alpha_first = 0;
this->alpha_inverted = 0;
this->mono_inverted = 0;
this->swap16 = 0;
this->littleendian = 0;
this->sig_bits = 0;
}
| 173,617
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t MediaPlayer::setDataSource(
const sp<IMediaHTTPService> &httpService,
const char *url, const KeyedVector<String8, String8> *headers)
{
ALOGV("setDataSource(%s)", url);
status_t err = BAD_VALUE;
if (url != NULL) {
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(httpService, url, headers))) {
player.clear();
}
err = attachNewPlayer(player);
}
}
return err;
}
Commit Message: Don't use sp<>&
because they may end up pointing to NULL after a NULL check was performed.
Bug: 28166152
Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe
CWE ID: CWE-476
|
status_t MediaPlayer::setDataSource(
const sp<IMediaHTTPService> &httpService,
const char *url, const KeyedVector<String8, String8> *headers)
{
ALOGV("setDataSource(%s)", url);
status_t err = BAD_VALUE;
if (url != NULL) {
const sp<IMediaPlayerService> service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(httpService, url, headers))) {
player.clear();
}
err = attachNewPlayer(player);
}
}
return err;
}
| 173,537
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CreatePrintSettingsDictionary(DictionaryValue* dict) {
dict->SetBoolean(printing::kSettingLandscape, false);
dict->SetBoolean(printing::kSettingCollate, false);
dict->SetInteger(printing::kSettingColor, printing::GRAY);
dict->SetBoolean(printing::kSettingPrintToPDF, true);
dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX);
dict->SetInteger(printing::kSettingCopies, 1);
dict->SetString(printing::kSettingDeviceName, "dummy");
dict->SetString(printing::kPreviewUIAddr, "0xb33fbeef");
dict->SetInteger(printing::kPreviewRequestID, 12345);
dict->SetBoolean(printing::kIsFirstRequest, true);
dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS);
dict->SetBoolean(printing::kSettingPreviewModifiable, false);
dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false);
dict->SetBoolean(printing::kSettingGenerateDraftData, true);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void CreatePrintSettingsDictionary(DictionaryValue* dict) {
dict->SetBoolean(printing::kSettingLandscape, false);
dict->SetBoolean(printing::kSettingCollate, false);
dict->SetInteger(printing::kSettingColor, printing::GRAY);
dict->SetBoolean(printing::kSettingPrintToPDF, true);
dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX);
dict->SetInteger(printing::kSettingCopies, 1);
dict->SetString(printing::kSettingDeviceName, "dummy");
dict->SetInteger(printing::kPreviewUIID, 4);
dict->SetInteger(printing::kPreviewRequestID, 12345);
dict->SetBoolean(printing::kIsFirstRequest, true);
dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS);
dict->SetBoolean(printing::kSettingPreviewModifiable, false);
dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false);
dict->SetBoolean(printing::kSettingGenerateDraftData, true);
}
| 170,858
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t MediaHTTP::connect(
const char *uri,
const KeyedVector<String8, String8> *headers,
off64_t /* offset */) {
if (mInitCheck != OK) {
return mInitCheck;
}
KeyedVector<String8, String8> extHeaders;
if (headers != NULL) {
extHeaders = *headers;
}
if (extHeaders.indexOfKey(String8("User-Agent")) < 0) {
extHeaders.add(String8("User-Agent"), String8(MakeUserAgent().c_str()));
}
bool success = mHTTPConnection->connect(uri, &extHeaders);
mLastHeaders = extHeaders;
mLastURI = uri;
mCachedSizeValid = false;
if (success) {
AString sanitized = uriDebugString(uri);
mName = String8::format("MediaHTTP(%s)", sanitized.c_str());
}
return success ? OK : UNKNOWN_ERROR;
}
Commit Message: Fix free-after-use for MediaHTTP
fix free-after-use when we reconnect to an HTTP media source.
Change-Id: I96da5a79f5382409a545f8b4e22a24523f287464
Tests: compilation and eyeballs
Bug: 31373622
(cherry picked from commit dd81e1592ffa77812998b05761eb840b70fed121)
CWE ID: CWE-119
|
status_t MediaHTTP::connect(
const char *uri,
const KeyedVector<String8, String8> *headers,
off64_t /* offset */) {
if (mInitCheck != OK) {
return mInitCheck;
}
KeyedVector<String8, String8> extHeaders;
if (headers != NULL) {
extHeaders = *headers;
}
if (extHeaders.indexOfKey(String8("User-Agent")) < 0) {
extHeaders.add(String8("User-Agent"), String8(MakeUserAgent().c_str()));
}
mLastURI = uri;
// reconnect() calls with uri == old mLastURI.c_str(), which gets zapped
// as part of the above assignment. Ensure no accidental later use.
uri = NULL;
bool success = mHTTPConnection->connect(mLastURI.c_str(), &extHeaders);
mLastHeaders = extHeaders;
mCachedSizeValid = false;
if (success) {
AString sanitized = uriDebugString(mLastURI);
mName = String8::format("MediaHTTP(%s)", sanitized.c_str());
}
return success ? OK : UNKNOWN_ERROR;
}
| 173,386
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void WriteFromUrlOperation::Download(const base::Closure& continuation) {
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
if (IsCancelled()) {
return;
}
download_continuation_ = continuation;
SetStage(image_writer_api::STAGE_DOWNLOAD);
url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this);
url_fetcher_->SetRequestContext(request_context_);
url_fetcher_->SaveResponseToFileAtPath(
image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE));
AddCleanUpFunction(
base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this));
url_fetcher_->Start();
}
Commit Message: Network traffic annotation added to extensions::image_writer::WriteFromUrlOperation.
Network traffic annotation is added to network request of extensions::image_writer::WriteFromUrlOperation.
BUG=656607
Review-Url: https://codereview.chromium.org/2691963002
Cr-Commit-Position: refs/heads/master@{#451456}
CWE ID:
|
void WriteFromUrlOperation::Download(const base::Closure& continuation) {
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
if (IsCancelled()) {
return;
}
download_continuation_ = continuation;
SetStage(image_writer_api::STAGE_DOWNLOAD);
// Create traffic annotation tag.
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("cros_recovery_image_download", R"(
semantics {
sender: "Chrome OS Recovery Utility"
description:
"The Google Chrome OS recovery utility downloads the recovery "
"image from Google Download Server."
trigger:
"User uses the Chrome OS Recovery Utility app/extension, selects "
"a Chrome OS recovery image, and clicks the Create button to write "
"the image to a USB or SD card."
data:
"URL of the image file to be downloaded. No other data or user "
"identifier is sent."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: true
cookies_store: "user"
setting:
"This feature cannot be disabled by settings, it can only be used "
"by whitelisted apps/extension."
policy_exception_justification:
"Not implemented, considered not useful."
})");
url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this,
traffic_annotation);
url_fetcher_->SetRequestContext(request_context_);
url_fetcher_->SaveResponseToFileAtPath(
image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE));
AddCleanUpFunction(
base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this));
url_fetcher_->Start();
}
| 171,962
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int sanity_check_ckpt(struct f2fs_sb_info *sbi)
{
unsigned int total, fsmeta;
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
unsigned int ovp_segments, reserved_segments;
total = le32_to_cpu(raw_super->segment_count);
fsmeta = le32_to_cpu(raw_super->segment_count_ckpt);
fsmeta += le32_to_cpu(raw_super->segment_count_sit);
fsmeta += le32_to_cpu(raw_super->segment_count_nat);
fsmeta += le32_to_cpu(ckpt->rsvd_segment_count);
fsmeta += le32_to_cpu(raw_super->segment_count_ssa);
if (unlikely(fsmeta >= total))
return 1;
ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
if (unlikely(fsmeta < F2FS_MIN_SEGMENTS ||
ovp_segments == 0 || reserved_segments == 0)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Wrong layout: check mkfs.f2fs version");
return 1;
}
if (unlikely(f2fs_cp_error(sbi))) {
f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck");
return 1;
}
return 0;
}
Commit Message: f2fs: sanity check checkpoint segno and blkoff
Make sure segno and blkoff read from raw image are valid.
Cc: stable@vger.kernel.org
Signed-off-by: Jin Qian <jinqian@google.com>
[Jaegeuk Kim: adjust minor coding style]
Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>
CWE ID: CWE-129
|
int sanity_check_ckpt(struct f2fs_sb_info *sbi)
{
unsigned int total, fsmeta;
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
unsigned int ovp_segments, reserved_segments;
unsigned int main_segs, blocks_per_seg;
int i;
total = le32_to_cpu(raw_super->segment_count);
fsmeta = le32_to_cpu(raw_super->segment_count_ckpt);
fsmeta += le32_to_cpu(raw_super->segment_count_sit);
fsmeta += le32_to_cpu(raw_super->segment_count_nat);
fsmeta += le32_to_cpu(ckpt->rsvd_segment_count);
fsmeta += le32_to_cpu(raw_super->segment_count_ssa);
if (unlikely(fsmeta >= total))
return 1;
ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
if (unlikely(fsmeta < F2FS_MIN_SEGMENTS ||
ovp_segments == 0 || reserved_segments == 0)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Wrong layout: check mkfs.f2fs version");
return 1;
}
main_segs = le32_to_cpu(raw_super->segment_count_main);
blocks_per_seg = sbi->blocks_per_seg;
for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) {
if (le32_to_cpu(ckpt->cur_node_segno[i]) >= main_segs ||
le16_to_cpu(ckpt->cur_node_blkoff[i]) >= blocks_per_seg)
return 1;
}
for (i = 0; i < NR_CURSEG_DATA_TYPE; i++) {
if (le32_to_cpu(ckpt->cur_data_segno[i]) >= main_segs ||
le16_to_cpu(ckpt->cur_data_blkoff[i]) >= blocks_per_seg)
return 1;
}
if (unlikely(f2fs_cp_error(sbi))) {
f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck");
return 1;
}
return 0;
}
| 168,064
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
int len;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
imapc->mailbox = curl_easy_unescape(data, path, 0, &len);
if(!imapc->mailbox)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
Commit Message: URL sanitize: reject URLs containing bad data
Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a
decoded manner now use the new Curl_urldecode() function to reject URLs
with embedded control codes (anything that is or decodes to a byte value
less than 32).
URLs containing such codes could easily otherwise be used to do harm and
allow users to do unintended actions with otherwise innocent tools and
applications. Like for example using a URL like
pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get
a mail and instead this would delete one.
This flaw is considered a security vulnerability: CVE-2012-0036
Security advisory at: http://curl.haxx.se/docs/adv_20120124.html
Reported by: Dan Fandrich
CWE ID: CWE-89
|
static CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
return Curl_urldecode(data, path, 0, &imapc->mailbox, NULL, TRUE);
}
| 165,666
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void coroutine_fn v9fs_link(void *opaque)
{
V9fsPDU *pdu = opaque;
int32_t dfid, oldfid;
V9fsFidState *dfidp, *oldfidp;
V9fsString name;
size_t offset = 7;
int err = 0;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
if (name_is_illegal(name.data)) {
err = -ENOENT;
goto out_nofid;
}
if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
err = -EEXIST;
goto out_nofid;
}
dfidp = get_fid(pdu, dfid);
if (dfidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
oldfidp = get_fid(pdu, oldfid);
if (oldfidp == NULL) {
err = -ENOENT;
goto out;
}
err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
if (!err) {
err = offset;
}
out:
put_fid(pdu, dfidp);
out_nofid:
pdu_complete(pdu, err);
}
Commit Message:
CWE ID: CWE-399
|
static void coroutine_fn v9fs_link(void *opaque)
{
V9fsPDU *pdu = opaque;
int32_t dfid, oldfid;
V9fsFidState *dfidp, *oldfidp;
V9fsString name;
size_t offset = 7;
int err = 0;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
if (name_is_illegal(name.data)) {
err = -ENOENT;
goto out_nofid;
}
if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
err = -EEXIST;
goto out_nofid;
}
dfidp = get_fid(pdu, dfid);
if (dfidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
oldfidp = get_fid(pdu, oldfid);
if (oldfidp == NULL) {
err = -ENOENT;
goto out;
}
err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
if (!err) {
err = offset;
}
put_fid(pdu, oldfidp);
out:
put_fid(pdu, dfidp);
out_nofid:
pdu_complete(pdu, err);
}
| 164,907
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long mkvparser::UnserializeFloat(
IMkvReader* pReader,
long long pos,
long long size_,
double& result)
{
assert(pReader);
assert(pos >= 0);
if ((size_ != 4) && (size_ != 8))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) //error
return status;
if (size == 4)
{
union
{
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;)
{
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
}
else
{
assert(size == 8);
union
{
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;)
{
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long mkvparser::UnserializeFloat(
{
signed char b;
const long status = pReader->Read(pos, 1, (unsigned char*)&b);
if (status < 0)
return status;
result = b;
++pos;
}
for (long i = 1; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return 0; // success
}
| 174,447
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) {
unsigned int sad = 0;
const uint8_t* const reference = GetReference(block_idx);
for (int h = 0; h < height_; ++h) {
for (int w = 0; w < width_; ++w) {
sad += abs(source_data_[h * source_stride_ + w]
- reference[h * reference_stride_ + w]);
}
if (sad > max_sad) {
break;
}
}
return sad;
}
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
|
unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) {
unsigned int ReferenceSAD(int block_idx) {
unsigned int sad = 0;
const uint8_t *const reference8 = GetReference(block_idx);
const uint8_t *const source8 = source_data_;
#if CONFIG_VP9_HIGHBITDEPTH
const uint16_t *const reference16 =
CONVERT_TO_SHORTPTR(GetReference(block_idx));
const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_);
#endif // CONFIG_VP9_HIGHBITDEPTH
for (int h = 0; h < height_; ++h) {
for (int w = 0; w < width_; ++w) {
if (!use_high_bit_depth_) {
sad += abs(source8[h * source_stride_ + w] -
reference8[h * reference_stride_ + w]);
#if CONFIG_VP9_HIGHBITDEPTH
} else {
sad += abs(source16[h * source_stride_ + w] -
reference16[h * reference_stride_ + w]);
#endif // CONFIG_VP9_HIGHBITDEPTH
}
}
}
return sad;
}
| 174,574
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void command_port_read_callback(struct urb *urb)
{
struct usb_serial_port *command_port = urb->context;
struct whiteheat_command_private *command_info;
int status = urb->status;
unsigned char *data = urb->transfer_buffer;
int result;
command_info = usb_get_serial_port_data(command_port);
if (!command_info) {
dev_dbg(&urb->dev->dev, "%s - command_info is NULL, exiting.\n", __func__);
return;
}
if (status) {
dev_dbg(&urb->dev->dev, "%s - nonzero urb status: %d\n", __func__, status);
if (status != -ENOENT)
command_info->command_finished = WHITEHEAT_CMD_FAILURE;
wake_up(&command_info->wait_command);
return;
}
usb_serial_debug_data(&command_port->dev, __func__, urb->actual_length, data);
if (data[0] == WHITEHEAT_CMD_COMPLETE) {
command_info->command_finished = WHITEHEAT_CMD_COMPLETE;
wake_up(&command_info->wait_command);
} else if (data[0] == WHITEHEAT_CMD_FAILURE) {
command_info->command_finished = WHITEHEAT_CMD_FAILURE;
wake_up(&command_info->wait_command);
} else if (data[0] == WHITEHEAT_EVENT) {
/* These are unsolicited reports from the firmware, hence no
waiting command to wakeup */
dev_dbg(&urb->dev->dev, "%s - event received\n", __func__);
} else if (data[0] == WHITEHEAT_GET_DTR_RTS) {
memcpy(command_info->result_buffer, &data[1],
urb->actual_length - 1);
command_info->command_finished = WHITEHEAT_CMD_COMPLETE;
wake_up(&command_info->wait_command);
} else
dev_dbg(&urb->dev->dev, "%s - bad reply from firmware\n", __func__);
/* Continue trying to always read */
result = usb_submit_urb(command_port->read_urb, GFP_ATOMIC);
if (result)
dev_dbg(&urb->dev->dev, "%s - failed resubmitting read urb, error %d\n",
__func__, result);
}
Commit Message: USB: whiteheat: Added bounds checking for bulk command response
This patch fixes a potential security issue in the whiteheat USB driver
which might allow a local attacker to cause kernel memory corrpution. This
is due to an unchecked memcpy into a fixed size buffer (of 64 bytes). On
EHCI and XHCI busses it's possible to craft responses greater than 64
bytes leading a buffer overflow.
Signed-off-by: James Forshaw <forshaw@google.com>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID: CWE-119
|
static void command_port_read_callback(struct urb *urb)
{
struct usb_serial_port *command_port = urb->context;
struct whiteheat_command_private *command_info;
int status = urb->status;
unsigned char *data = urb->transfer_buffer;
int result;
command_info = usb_get_serial_port_data(command_port);
if (!command_info) {
dev_dbg(&urb->dev->dev, "%s - command_info is NULL, exiting.\n", __func__);
return;
}
if (!urb->actual_length) {
dev_dbg(&urb->dev->dev, "%s - empty response, exiting.\n", __func__);
return;
}
if (status) {
dev_dbg(&urb->dev->dev, "%s - nonzero urb status: %d\n", __func__, status);
if (status != -ENOENT)
command_info->command_finished = WHITEHEAT_CMD_FAILURE;
wake_up(&command_info->wait_command);
return;
}
usb_serial_debug_data(&command_port->dev, __func__, urb->actual_length, data);
if (data[0] == WHITEHEAT_CMD_COMPLETE) {
command_info->command_finished = WHITEHEAT_CMD_COMPLETE;
wake_up(&command_info->wait_command);
} else if (data[0] == WHITEHEAT_CMD_FAILURE) {
command_info->command_finished = WHITEHEAT_CMD_FAILURE;
wake_up(&command_info->wait_command);
} else if (data[0] == WHITEHEAT_EVENT) {
/* These are unsolicited reports from the firmware, hence no
waiting command to wakeup */
dev_dbg(&urb->dev->dev, "%s - event received\n", __func__);
} else if ((data[0] == WHITEHEAT_GET_DTR_RTS) &&
(urb->actual_length - 1 <= sizeof(command_info->result_buffer))) {
memcpy(command_info->result_buffer, &data[1],
urb->actual_length - 1);
command_info->command_finished = WHITEHEAT_CMD_COMPLETE;
wake_up(&command_info->wait_command);
} else
dev_dbg(&urb->dev->dev, "%s - bad reply from firmware\n", __func__);
/* Continue trying to always read */
result = usb_submit_urb(command_port->read_urb, GFP_ATOMIC);
if (result)
dev_dbg(&urb->dev->dev, "%s - failed resubmitting read urb, error %d\n",
__func__, result);
}
| 166,369
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CreatePersistentMemoryAllocator() {
GlobalHistogramAllocator::GetCreateHistogramResultHistogram();
GlobalHistogramAllocator::CreateWithLocalMemory(
kAllocatorMemorySize, 0, "SparseHistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <bcwhite@chromium.org>
Reviewed-by: Alexei Svitkine <asvitkine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264
|
void CreatePersistentMemoryAllocator() {
GlobalHistogramAllocator::CreateWithLocalMemory(
kAllocatorMemorySize, 0, "SparseHistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
| 172,138
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void MaybeCreateIBus() {
if (ibus_) {
return;
}
ibus_init();
ibus_ = ibus_bus_new();
if (!ibus_) {
LOG(ERROR) << "ibus_bus_new() failed";
return;
}
ConnectIBusSignals();
ibus_bus_set_watch_dbus_signal(ibus_, TRUE);
ibus_bus_set_watch_ibus_signal(ibus_, TRUE);
if (ibus_bus_is_connected(ibus_)) {
LOG(INFO) << "IBus connection is ready.";
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void MaybeCreateIBus() {
if (ibus_) {
return;
}
ibus_init();
ibus_ = ibus_bus_new();
if (!ibus_) {
LOG(ERROR) << "ibus_bus_new() failed";
return;
}
ConnectIBusSignals();
ibus_bus_set_watch_dbus_signal(ibus_, TRUE);
ibus_bus_set_watch_ibus_signal(ibus_, TRUE);
if (ibus_bus_is_connected(ibus_)) {
VLOG(1) << "IBus connection is ready.";
}
}
| 170,541
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: gfx::Size ShellWindowFrameView::GetMinimumSize() {
gfx::Size min_size = frame_->client_view()->GetMinimumSize();
gfx::Rect client_bounds = GetBoundsForClientView();
min_size.Enlarge(0, client_bounds.y());
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
if (header_width > min_size.width())
min_size.set_width(header_width);
return min_size;
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
R=ben@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
|
gfx::Size ShellWindowFrameView::GetMinimumSize() {
gfx::Size min_size = frame_->client_view()->GetMinimumSize();
if (is_frameless_)
return min_size;
gfx::Rect client_bounds = GetBoundsForClientView();
min_size.Enlarge(0, client_bounds.y());
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
if (header_width > min_size.width())
min_size.set_width(header_width);
return min_size;
}
| 170,713
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int DefragMfIpv6Test(void)
{
int retval = 0;
int ip_id = 9;
Packet *p = NULL;
DefragInit();
Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8);
Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8);
Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8);
if (p1 == NULL || p2 == NULL || p3 == NULL) {
goto end;
}
p = Defrag(NULL, NULL, p1, NULL);
if (p != NULL) {
goto end;
}
p = Defrag(NULL, NULL, p2, NULL);
if (p != NULL) {
goto end;
}
/* This should return a packet as MF=0. */
p = Defrag(NULL, NULL, p3, NULL);
if (p == NULL) {
goto end;
}
/* For IPv6 the expected length is just the length of the payload
* of 2 fragments, so 16. */
if (IPV6_GET_PLEN(p) != 16) {
goto end;
}
retval = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
if (p2 != NULL) {
SCFree(p2);
}
if (p3 != NULL) {
SCFree(p3);
}
if (p != NULL) {
SCFree(p);
}
DefragDestroy();
return retval;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358
|
static int DefragMfIpv6Test(void)
{
int retval = 0;
int ip_id = 9;
Packet *p = NULL;
DefragInit();
Packet *p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 2, 1, 'C', 8);
Packet *p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 0, 1, 'A', 8);
Packet *p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 1, 0, 'B', 8);
if (p1 == NULL || p2 == NULL || p3 == NULL) {
goto end;
}
p = Defrag(NULL, NULL, p1, NULL);
if (p != NULL) {
goto end;
}
p = Defrag(NULL, NULL, p2, NULL);
if (p != NULL) {
goto end;
}
/* This should return a packet as MF=0. */
p = Defrag(NULL, NULL, p3, NULL);
if (p == NULL) {
goto end;
}
/* For IPv6 the expected length is just the length of the payload
* of 2 fragments, so 16. */
if (IPV6_GET_PLEN(p) != 16) {
goto end;
}
retval = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
if (p2 != NULL) {
SCFree(p2);
}
if (p3 != NULL) {
SCFree(p3);
}
if (p != NULL) {
SCFree(p);
}
DefragDestroy();
return retval;
}
| 168,300
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void EnterpriseEnrollmentScreen::OnAuthCancelled() {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentCancelled,
policy::kMetricEnrollmentSize);
auth_fetcher_.reset();
registrar_.reset();
g_browser_process->browser_policy_connector()->DeviceStopAutoRetry();
get_screen_observer()->OnExit(
ScreenObserver::ENTERPRISE_ENROLLMENT_CANCELLED);
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void EnterpriseEnrollmentScreen::OnAuthCancelled() {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentCancelled,
policy::kMetricEnrollmentSize);
auth_fetcher_.reset();
registrar_.reset();
g_browser_process->browser_policy_connector()->ResetDevicePolicy();
get_screen_observer()->OnExit(
ScreenObserver::ENTERPRISE_ENROLLMENT_CANCELLED);
}
| 170,276
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: append_utf8_value (const unsigned char *value, size_t length,
struct stringbuf *sb)
{
unsigned char tmp[6];
const unsigned char *s;
size_t n;
int i, nmore;
if (length && (*value == ' ' || *value == '#'))
{
tmp[0] = '\\';
tmp[1] = *value;
put_stringbuf_mem (sb, tmp, 2);
value++;
length--;
}
if (length && value[length-1] == ' ')
{
tmp[0] = '\\';
tmp[1] = ' ';
put_stringbuf_mem (sb, tmp, 2);
length--;
}
/* FIXME: check that the invalid encoding handling is correct */
for (s=value, n=0;;)
{
for (value = s; n < length && !(*s & 0x80); n++, s++)
for (value = s; n < length && !(*s & 0x80); n++, s++)
;
append_quoted (sb, value, s-value, 0);
if (n==length)
return; /* ready */
assert ((*s & 0x80));
if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */
nmore = 1;
else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */
nmore = 2;
else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */
nmore = 3;
else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */
nmore = 4;
else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */
nmore = 5;
else /* invalid encoding */
nmore = 5; /* we will reduce the check length anyway */
if (n+nmore > length)
nmore = length - n; /* oops, encoding to short */
tmp[0] = *s++; n++;
for (i=1; i <= nmore; i++)
{
if ( (*s & 0xc0) != 0x80)
break; /* invalid encoding - stop */
tmp[i] = *s++;
n++;
}
put_stringbuf_mem (sb, tmp, i);
}
}
Commit Message:
CWE ID: CWE-119
|
append_utf8_value (const unsigned char *value, size_t length,
struct stringbuf *sb)
{
unsigned char tmp[6];
const unsigned char *s;
size_t n;
int i, nmore;
if (length && (*value == ' ' || *value == '#'))
{
tmp[0] = '\\';
tmp[1] = *value;
put_stringbuf_mem (sb, tmp, 2);
value++;
length--;
}
if (length && value[length-1] == ' ')
{
tmp[0] = '\\';
tmp[1] = ' ';
put_stringbuf_mem (sb, tmp, 2);
length--;
}
for (s=value, n=0;;)
{
for (value = s; n < length && !(*s & 0x80); n++, s++)
for (value = s; n < length && !(*s & 0x80); n++, s++)
;
append_quoted (sb, value, s-value, 0);
if (n==length)
return; /* ready */
if (!(*s & 0x80))
nmore = 0; /* Not expected here: high bit not set. */
else if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */
nmore = 1;
else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */
nmore = 2;
else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */
nmore = 3;
else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */
nmore = 4;
else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */
nmore = 5;
else /* Invalid encoding */
nmore = 0;
if (!nmore)
{
/* Encoding error: We quote the bad byte. */
snprintf (tmp, sizeof tmp, "\\%02X", *s);
put_stringbuf_mem (sb, tmp, 3);
s++; n++;
}
else
{
if (n+nmore > length)
nmore = length - n; /* Oops, encoding to short */
tmp[0] = *s++; n++;
for (i=1; i <= nmore; i++)
{
if ( (*s & 0xc0) != 0x80)
break; /* Invalid encoding - let the next cycle detect this. */
tmp[i] = *s++;
n++;
}
put_stringbuf_mem (sb, tmp, i);
}
}
}
| 165,050
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: standard_row_validate(standard_display *dp, png_const_structp pp,
int iImage, int iDisplay, png_uint_32 y)
{
int where;
png_byte std[STANDARD_ROWMAX];
/* The row must be pre-initialized to the magic number here for the size
* tests to pass:
*/
memset(std, 178, sizeof std);
standard_row(pp, std, dp->id, y);
/* At the end both the 'row' and 'display' arrays should end up identical.
* In earlier passes 'row' will be partially filled in, with only the pixels
* that have been read so far, but 'display' will have those pixels
* replicated to fill the unread pixels while reading an interlaced image.
#if PNG_LIBPNG_VER < 10506
* The side effect inside the libpng sequential reader is that the 'row'
* array retains the correct values for unwritten pixels within the row
* bytes, while the 'display' array gets bits off the end of the image (in
* the last byte) trashed. Unfortunately in the progressive reader the
* row bytes are always trashed, so we always do a pixel_cmp here even though
* a memcmp of all cbRow bytes will succeed for the sequential reader.
#endif
*/
if (iImage >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iImage, y)[where-1]);
png_error(pp, msg);
}
#if PNG_LIBPNG_VER < 10506
/* In this case use pixel_cmp because we need to compare a partial
* byte at the end of the row if the row is not an exact multiple
* of 8 bits wide. (This is fixed in libpng-1.5.6 and pixel_cmp is
* changed to match!)
*/
#endif
if (iDisplay >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
png_error(pp, msg);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
standard_row_validate(standard_display *dp, png_const_structp pp,
int iImage, int iDisplay, png_uint_32 y)
{
int where;
png_byte std[STANDARD_ROWMAX];
/* The row must be pre-initialized to the magic number here for the size
* tests to pass:
*/
memset(std, 178, sizeof std);
standard_row(pp, std, dp->id, y);
/* At the end both the 'row' and 'display' arrays should end up identical.
* In earlier passes 'row' will be partially filled in, with only the pixels
* that have been read so far, but 'display' will have those pixels
* replicated to fill the unread pixels while reading an interlaced image.
*/
if (iImage >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iImage, y)[where-1]);
png_error(pp, msg);
}
if (iDisplay >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
png_error(pp, msg);
}
}
| 173,701
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
quic::QuicSession* session)
: quic::QuicStream(id, session, /*is_static=*/false, quic::BIDIRECTIONAL) {}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <shampson@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
|
P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
| 172,263
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static uint32_t readU32(const uint8_t* data, size_t offset) {
return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
}
Commit Message: Avoid integer overflows in parsing fonts
A malformed TTF can cause size calculations to overflow. This patch
checks the maximum reasonable value so that the total size fits in 32
bits. It also adds some explicit casting to avoid possible technical
undefined behavior when parsing sized unsigned values.
Bug: 25645298
Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616
(cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274)
CWE ID: CWE-19
|
static uint32_t readU32(const uint8_t* data, size_t offset) {
return ((uint32_t)data[offset]) << 24 | ((uint32_t)data[offset + 1]) << 16 |
((uint32_t)data[offset + 2]) << 8 | ((uint32_t)data[offset + 3]);
}
| 173,967
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual const ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual const ImePropertyList& current_ime_properties() const {
virtual const input_method::ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
| 170,511
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static enum AVPixelFormat h263_get_format(AVCodecContext *avctx)
{
/* MPEG-4 Studio Profile only, not supported by hardware */
if (avctx->bits_per_raw_sample > 8) {
av_assert1(avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);
return avctx->pix_fmt;
}
if (avctx->codec->id == AV_CODEC_ID_MSS2)
return AV_PIX_FMT_YUV420P;
if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {
if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)
avctx->color_range = AVCOL_RANGE_MPEG;
return AV_PIX_FMT_GRAY8;
}
return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);
}
Commit Message: avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile
The profile field is changed by code inside and outside the decoder,
its not a reliable indicator of the internal codec state.
Maintaining it consistency with studio_profile is messy.
Its easier to just avoid it and use only studio_profile
Fixes: assertion failure
Fixes: ffmpeg_crash_9.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-617
|
static enum AVPixelFormat h263_get_format(AVCodecContext *avctx)
{
MpegEncContext *s = avctx->priv_data;
/* MPEG-4 Studio Profile only, not supported by hardware */
if (avctx->bits_per_raw_sample > 8) {
av_assert1(s->studio_profile);
return avctx->pix_fmt;
}
if (avctx->codec->id == AV_CODEC_ID_MSS2)
return AV_PIX_FMT_YUV420P;
if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {
if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)
avctx->color_range = AVCOL_RANGE_MPEG;
return AV_PIX_FMT_GRAY8;
}
return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);
}
| 169,156
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos,
long long size_, double& result) {
assert(pReader);
assert(pos >= 0);
if ((size_ != 4) && (size_ != 8))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) // error
return status;
if (size == 4) {
union {
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;) {
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
} else {
assert(size == 8);
union {
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;) {
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos,
long UnserializeFloat(IMkvReader* pReader, long long pos, long long size_,
double& result) {
if (!pReader || pos < 0 || ((size_ != 4) && (size_ != 8)))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) // error
return status;
if (size == 4) {
union {
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;) {
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
} else {
union {
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;) {
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
if (std::isinf(result) || std::isnan(result))
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,865
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TestResultCallback()
: callback_(base::Bind(&TestResultCallback::SetResult,
base::Unretained(this))) {}
Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback
Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback
migration, as they are copied and passed to others.
This CL updates them to pass new callbacks for each use to avoid the
copy of callbacks.
Bug: 714018
Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0
Reviewed-on: https://chromium-review.googlesource.com/527549
Reviewed-by: Ken Rockot <rockot@chromium.org>
Commit-Queue: Taiju Tsuiki <tzik@chromium.org>
Cr-Commit-Position: refs/heads/master@{#478549}
CWE ID:
|
TestResultCallback()
| 171,977
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ChromeContentRendererClient::RenderThreadStarted() {
chrome_observer_.reset(new ChromeRenderProcessObserver());
extension_dispatcher_.reset(new ExtensionDispatcher());
histogram_snapshots_.reset(new RendererHistogramSnapshots());
net_predictor_.reset(new RendererNetPredictor());
spellcheck_.reset(new SpellCheck());
visited_link_slave_.reset(new VisitedLinkSlave());
#if defined(ENABLE_SAFE_BROWSING)
phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create());
#endif
RenderThread* thread = RenderThread::current();
thread->AddFilter(new DevToolsAgentFilter());
thread->AddObserver(chrome_observer_.get());
thread->AddObserver(extension_dispatcher_.get());
thread->AddObserver(histogram_snapshots_.get());
#if defined(ENABLE_SAFE_BROWSING)
thread->AddObserver(phishing_classifier_.get());
#endif
thread->AddObserver(spellcheck_.get());
thread->AddObserver(visited_link_slave_.get());
thread->RegisterExtension(extensions_v8::ExternalExtension::Get());
thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get());
thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get());
v8::Extension* search_extension = extensions_v8::SearchExtension::Get();
if (search_extension)
thread->RegisterExtension(search_extension);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
thread->RegisterExtension(DomAutomationV8Extension::Get());
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableIPCFuzzing)) {
thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer());
}
WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme));
WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme);
WebString dev_tools_scheme(ASCIIToUTF16(chrome::kChromeDevToolsScheme));
WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dev_tools_scheme);
WebString internal_scheme(ASCIIToUTF16(chrome::kChromeInternalScheme));
WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(internal_scheme);
WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme));
WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme);
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void ChromeContentRendererClient::RenderThreadStarted() {
chrome_observer_.reset(new ChromeRenderProcessObserver());
extension_dispatcher_.reset(new ExtensionDispatcher());
histogram_snapshots_.reset(new RendererHistogramSnapshots());
net_predictor_.reset(new RendererNetPredictor());
spellcheck_.reset(new SpellCheck());
visited_link_slave_.reset(new VisitedLinkSlave());
#if defined(ENABLE_SAFE_BROWSING)
phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create());
#endif
RenderThread* thread = RenderThread::current();
thread->AddObserver(chrome_observer_.get());
thread->AddObserver(extension_dispatcher_.get());
thread->AddObserver(histogram_snapshots_.get());
#if defined(ENABLE_SAFE_BROWSING)
thread->AddObserver(phishing_classifier_.get());
#endif
thread->AddObserver(spellcheck_.get());
thread->AddObserver(visited_link_slave_.get());
thread->RegisterExtension(extensions_v8::ExternalExtension::Get());
thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get());
thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get());
v8::Extension* search_extension = extensions_v8::SearchExtension::Get();
if (search_extension)
thread->RegisterExtension(search_extension);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
thread->RegisterExtension(DomAutomationV8Extension::Get());
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableIPCFuzzing)) {
thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer());
}
WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme));
WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme);
WebString dev_tools_scheme(ASCIIToUTF16(chrome::kChromeDevToolsScheme));
WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dev_tools_scheme);
WebString internal_scheme(ASCIIToUTF16(chrome::kChromeInternalScheme));
WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(internal_scheme);
WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme));
WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme);
}
| 170,323
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
const base::FilePath& suggested_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
callback.Run(suggested_path,
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")),
content::DOWNLOAD_INTERRUPT_REASON_NONE);
}
Commit Message: Always mark content downloaded by devtools delegate as potentially dangerous
Bug: 805445
Change-Id: I7051f519205e178db57e23320ab979f8fa9ce38b
Reviewed-on: https://chromium-review.googlesource.com/894782
Commit-Queue: David Vallet <dvallet@chromium.org>
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#533215}
CWE ID:
|
void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
const base::FilePath& suggested_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
callback.Run(suggested_path,
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")),
content::DOWNLOAD_INTERRUPT_REASON_NONE);
}
| 173,170
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: AXObjectInclusion AXLayoutObject::defaultObjectInclusion(
IgnoredReasons* ignoredReasons) const {
if (!m_layoutObject) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotRendered));
return IgnoreObject;
}
if (m_layoutObject->style()->visibility() != EVisibility::kVisible) {
if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "false"))
return DefaultBehavior;
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotVisible));
return IgnoreObject;
}
return AXObject::defaultObjectInclusion(ignoredReasons);
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
AXObjectInclusion AXLayoutObject::defaultObjectInclusion(
IgnoredReasons* ignoredReasons) const {
if (!m_layoutObject) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotRendered));
return IgnoreObject;
}
if (m_layoutObject->style()->visibility() != EVisibility::kVisible) {
if (equalIgnoringASCIICase(getAttribute(aria_hiddenAttr), "false"))
return DefaultBehavior;
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotVisible));
return IgnoreObject;
}
return AXObject::defaultObjectInclusion(ignoredReasons);
}
| 171,903
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Plugin::Plugin(PP_Instance pp_instance)
: pp::InstancePrivate(pp_instance),
scriptable_plugin_(NULL),
argc_(-1),
argn_(NULL),
argv_(NULL),
main_subprocess_("main subprocess", NULL, NULL),
nacl_ready_state_(UNSENT),
nexe_error_reported_(false),
wrapper_factory_(NULL),
last_error_string_(""),
ppapi_proxy_(NULL),
enable_dev_interfaces_(false),
init_time_(0),
ready_time_(0),
nexe_size_(0),
time_of_last_progress_event_(0),
using_ipc_proxy_(false) {
PLUGIN_PRINTF(("Plugin::Plugin (this=%p, pp_instance=%"
NACL_PRId32")\n", static_cast<void*>(this), pp_instance));
callback_factory_.Initialize(this);
nexe_downloader_.Initialize(this);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
Plugin::Plugin(PP_Instance pp_instance)
: pp::InstancePrivate(pp_instance),
scriptable_plugin_(NULL),
argc_(-1),
argn_(NULL),
argv_(NULL),
main_subprocess_("main subprocess", NULL, NULL),
nacl_ready_state_(UNSENT),
nexe_error_reported_(false),
wrapper_factory_(NULL),
last_error_string_(""),
ppapi_proxy_(NULL),
enable_dev_interfaces_(false),
init_time_(0),
ready_time_(0),
nexe_size_(0),
time_of_last_progress_event_(0) {
PLUGIN_PRINTF(("Plugin::Plugin (this=%p, pp_instance=%"
NACL_PRId32")\n", static_cast<void*>(this), pp_instance));
callback_factory_.Initialize(this);
nexe_downloader_.Initialize(this);
}
| 170,744
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
enable_ipc_proxy_ = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClIPCProxy);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
}
| 170,724
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) {
scoped_refptr<CaptureData> data;
if (capturing_) {
InvalidRects rects;
helper_.SwapInvalidRects(rects);
VideoFrameBuffer& current_buffer = buffers_[current_buffer_];
current_buffer.Update();
bool flip = true; // GL capturers need flipping.
if (cgl_context_) {
if (pixel_buffer_object_.get() != 0) {
GlBlitFast(current_buffer);
} else {
GlBlitSlow(current_buffer);
}
} else {
CgBlit(current_buffer, rects);
flip = false;
}
DataPlanes planes;
planes.data[0] = current_buffer.ptr();
planes.strides[0] = current_buffer.bytes_per_row();
if (flip) {
planes.strides[0] = -planes.strides[0];
planes.data[0] +=
(current_buffer.size().height() - 1) * current_buffer.bytes_per_row();
}
data = new CaptureData(planes, gfx::Size(current_buffer.size()),
pixel_format());
data->mutable_dirty_rects() = rects;
current_buffer_ = (current_buffer_ + 1) % kNumBuffers;
helper_.set_size_most_recent(data->size());
}
callback->Run(data);
delete callback;
}
Commit Message: Workaround for bad driver issue with NVIDIA GeForce 7300 GT on Mac 10.5.
BUG=87283
TEST=Run on a machine with NVIDIA GeForce 7300 GT on Mac 10.5 immediately after booting.
Review URL: http://codereview.chromium.org/7373018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@92651 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) {
scoped_refptr<CaptureData> data;
if (capturing_) {
InvalidRects rects;
helper_.SwapInvalidRects(rects);
VideoFrameBuffer& current_buffer = buffers_[current_buffer_];
current_buffer.Update();
bool flip = true; // GL capturers need flipping.
if (cgl_context_) {
if (pixel_buffer_object_.get() != 0) {
GlBlitFast(current_buffer);
} else {
// See comment in scoped_pixel_buffer_object::Init about why the slow
// path is always used on 10.5.
GlBlitSlow(current_buffer);
}
} else {
CgBlit(current_buffer, rects);
flip = false;
}
DataPlanes planes;
planes.data[0] = current_buffer.ptr();
planes.strides[0] = current_buffer.bytes_per_row();
if (flip) {
planes.strides[0] = -planes.strides[0];
planes.data[0] +=
(current_buffer.size().height() - 1) * current_buffer.bytes_per_row();
}
data = new CaptureData(planes, gfx::Size(current_buffer.size()),
pixel_format());
data->mutable_dirty_rects() = rects;
current_buffer_ = (current_buffer_ + 1) % kNumBuffers;
helper_.set_size_most_recent(data->size());
}
callback->Run(data);
delete callback;
}
| 170,316
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: gplotRead(const char *filename)
{
char buf[L_BUF_SIZE];
char *rootname, *title, *xlabel, *ylabel, *ignores;
l_int32 outformat, ret, version, ignore;
FILE *fp;
GPLOT *gplot;
PROCNAME("gplotRead");
if (!filename)
return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL);
if ((fp = fopenReadStream(filename)) == NULL)
return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL);
ret = fscanf(fp, "Gplot Version %d\n", &version);
if (ret != 1) {
fclose(fp);
return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL);
}
if (version != GPLOT_VERSION_NUMBER) {
fclose(fp);
return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL);
}
ignore = fscanf(fp, "Rootname: %s\n", buf);
rootname = stringNew(buf);
ignore = fscanf(fp, "Output format: %d\n", &outformat);
ignores = fgets(buf, L_BUF_SIZE, fp); /* Title: ... */
title = stringNew(buf + 7);
title[strlen(title) - 1] = '\0';
ignores = fgets(buf, L_BUF_SIZE, fp); /* X axis label: ... */
xlabel = stringNew(buf + 14);
xlabel[strlen(xlabel) - 1] = '\0';
ignores = fgets(buf, L_BUF_SIZE, fp); /* Y axis label: ... */
ylabel = stringNew(buf + 14);
ylabel[strlen(ylabel) - 1] = '\0';
gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel);
LEPT_FREE(rootname);
LEPT_FREE(title);
LEPT_FREE(xlabel);
LEPT_FREE(ylabel);
if (!gplot) {
fclose(fp);
return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL);
}
sarrayDestroy(&gplot->cmddata);
sarrayDestroy(&gplot->datanames);
sarrayDestroy(&gplot->plotdata);
sarrayDestroy(&gplot->plottitles);
numaDestroy(&gplot->plotstyles);
ignore = fscanf(fp, "Commandfile name: %s\n", buf);
stringReplace(&gplot->cmdname, buf);
ignore = fscanf(fp, "\nCommandfile data:");
gplot->cmddata = sarrayReadStream(fp);
ignore = fscanf(fp, "\nDatafile names:");
gplot->datanames = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot data:");
gplot->plotdata = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot titles:");
gplot->plottitles = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot styles:");
gplot->plotstyles = numaReadStream(fp);
ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots);
ignore = fscanf(fp, "Output file name: %s\n", buf);
stringReplace(&gplot->outname, buf);
ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling);
fclose(fp);
return gplot;
}
Commit Message: Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().
CWE ID: CWE-119
|
gplotRead(const char *filename)
{
char buf[L_BUFSIZE];
char *rootname, *title, *xlabel, *ylabel, *ignores;
l_int32 outformat, ret, version, ignore;
FILE *fp;
GPLOT *gplot;
PROCNAME("gplotRead");
if (!filename)
return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL);
if ((fp = fopenReadStream(filename)) == NULL)
return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL);
ret = fscanf(fp, "Gplot Version %d\n", &version);
if (ret != 1) {
fclose(fp);
return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL);
}
if (version != GPLOT_VERSION_NUMBER) {
fclose(fp);
return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL);
}
ignore = fscanf(fp, "Rootname: %511s\n", buf); /* L_BUFSIZE - 1 */
rootname = stringNew(buf);
ignore = fscanf(fp, "Output format: %d\n", &outformat);
ignores = fgets(buf, L_BUFSIZE, fp); /* Title: ... */
title = stringNew(buf + 7);
title[strlen(title) - 1] = '\0';
ignores = fgets(buf, L_BUFSIZE, fp); /* X axis label: ... */
xlabel = stringNew(buf + 14);
xlabel[strlen(xlabel) - 1] = '\0';
ignores = fgets(buf, L_BUFSIZE, fp); /* Y axis label: ... */
ylabel = stringNew(buf + 14);
ylabel[strlen(ylabel) - 1] = '\0';
gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel);
LEPT_FREE(rootname);
LEPT_FREE(title);
LEPT_FREE(xlabel);
LEPT_FREE(ylabel);
if (!gplot) {
fclose(fp);
return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL);
}
sarrayDestroy(&gplot->cmddata);
sarrayDestroy(&gplot->datanames);
sarrayDestroy(&gplot->plotdata);
sarrayDestroy(&gplot->plottitles);
numaDestroy(&gplot->plotstyles);
ignore = fscanf(fp, "Commandfile name: %511s\n", buf); /* L_BUFSIZE - 1 */
stringReplace(&gplot->cmdname, buf);
ignore = fscanf(fp, "\nCommandfile data:");
gplot->cmddata = sarrayReadStream(fp);
ignore = fscanf(fp, "\nDatafile names:");
gplot->datanames = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot data:");
gplot->plotdata = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot titles:");
gplot->plottitles = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot styles:");
gplot->plotstyles = numaReadStream(fp);
ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots);
ignore = fscanf(fp, "Output file name: %511s\n", buf);
stringReplace(&gplot->outname, buf);
ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling);
fclose(fp);
return gplot;
}
| 169,327
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void XSSAuditor::Init(Document* document,
XSSAuditorDelegate* auditor_delegate) {
DCHECK(IsMainThread());
if (state_ != kUninitialized)
return;
state_ = kFilteringTokens;
if (Settings* settings = document->GetSettings())
is_enabled_ = settings->GetXSSAuditorEnabled();
if (!is_enabled_)
return;
document_url_ = document->Url().Copy();
if (!document->GetFrame()) {
is_enabled_ = false;
return;
}
if (document_url_.IsEmpty()) {
is_enabled_ = false;
return;
}
if (document_url_.ProtocolIsData()) {
is_enabled_ = false;
return;
}
if (document->Encoding().IsValid())
encoding_ = document->Encoding();
if (DocumentLoader* document_loader =
document->GetFrame()->Loader().GetDocumentLoader()) {
const AtomicString& header_value =
document_loader->GetResponse().HttpHeaderField(
HTTPNames::X_XSS_Protection);
String error_details;
unsigned error_position = 0;
String report_url;
KURL xss_protection_report_url;
ReflectedXSSDisposition xss_protection_header = ParseXSSProtectionHeader(
header_value, error_details, error_position, report_url);
if (xss_protection_header == kAllowReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled);
else if (xss_protection_header == kFilterReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter);
else if (xss_protection_header == kBlockReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock);
else if (xss_protection_header == kReflectedXSSInvalid)
UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid);
did_send_valid_xss_protection_header_ =
xss_protection_header != kReflectedXSSUnset &&
xss_protection_header != kReflectedXSSInvalid;
if ((xss_protection_header == kFilterReflectedXSS ||
xss_protection_header == kBlockReflectedXSS) &&
!report_url.IsEmpty()) {
xss_protection_report_url = document->CompleteURL(report_url);
if (MixedContentChecker::IsMixedContent(document->GetSecurityOrigin(),
xss_protection_report_url)) {
error_details = "insecure reporting URL for secure page";
xss_protection_header = kReflectedXSSInvalid;
xss_protection_report_url = KURL();
}
}
if (xss_protection_header == kReflectedXSSInvalid) {
document->AddConsoleMessage(ConsoleMessage::Create(
kSecurityMessageSource, kErrorMessageLevel,
"Error parsing header X-XSS-Protection: " + header_value + ": " +
error_details + " at character position " +
String::Format("%u", error_position) +
". The default protections will be applied."));
}
xss_protection_ = xss_protection_header;
if (xss_protection_ == kReflectedXSSInvalid ||
xss_protection_ == kReflectedXSSUnset) {
xss_protection_ = kBlockReflectedXSS;
}
if (auditor_delegate)
auditor_delegate->SetReportURL(xss_protection_report_url.Copy());
EncodedFormData* http_body = document_loader->GetRequest().HttpBody();
if (http_body && !http_body->IsEmpty())
http_body_as_string_ = http_body->FlattenToString();
}
SetEncoding(encoding_);
}
Commit Message: Restrict the xss audit report URL to same origin
BUG=441275
R=tsepez@chromium.org,mkwst@chromium.org
Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d
Reviewed-on: https://chromium-review.googlesource.com/768367
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#516666}
CWE ID: CWE-79
|
void XSSAuditor::Init(Document* document,
XSSAuditorDelegate* auditor_delegate) {
DCHECK(IsMainThread());
if (state_ != kUninitialized)
return;
state_ = kFilteringTokens;
if (Settings* settings = document->GetSettings())
is_enabled_ = settings->GetXSSAuditorEnabled();
if (!is_enabled_)
return;
document_url_ = document->Url().Copy();
if (!document->GetFrame()) {
is_enabled_ = false;
return;
}
if (document_url_.IsEmpty()) {
is_enabled_ = false;
return;
}
if (document_url_.ProtocolIsData()) {
is_enabled_ = false;
return;
}
if (document->Encoding().IsValid())
encoding_ = document->Encoding();
if (DocumentLoader* document_loader =
document->GetFrame()->Loader().GetDocumentLoader()) {
const AtomicString& header_value =
document_loader->GetResponse().HttpHeaderField(
HTTPNames::X_XSS_Protection);
String error_details;
unsigned error_position = 0;
String report_url;
KURL xss_protection_report_url;
ReflectedXSSDisposition xss_protection_header = ParseXSSProtectionHeader(
header_value, error_details, error_position, report_url);
if (xss_protection_header == kAllowReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled);
else if (xss_protection_header == kFilterReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter);
else if (xss_protection_header == kBlockReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock);
else if (xss_protection_header == kReflectedXSSInvalid)
UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid);
did_send_valid_xss_protection_header_ =
xss_protection_header != kReflectedXSSUnset &&
xss_protection_header != kReflectedXSSInvalid;
if ((xss_protection_header == kFilterReflectedXSS ||
xss_protection_header == kBlockReflectedXSS) &&
!report_url.IsEmpty()) {
xss_protection_report_url = document->CompleteURL(report_url);
if (!SecurityOrigin::Create(xss_protection_report_url)
->IsSameSchemeHostPort(document->GetSecurityOrigin())) {
error_details =
"reporting URL is not same scheme, host, and port as page";
xss_protection_header = kReflectedXSSInvalid;
xss_protection_report_url = KURL();
}
if (MixedContentChecker::IsMixedContent(document->GetSecurityOrigin(),
xss_protection_report_url)) {
error_details = "insecure reporting URL for secure page";
xss_protection_header = kReflectedXSSInvalid;
xss_protection_report_url = KURL();
}
}
if (xss_protection_header == kReflectedXSSInvalid) {
document->AddConsoleMessage(ConsoleMessage::Create(
kSecurityMessageSource, kErrorMessageLevel,
"Error parsing header X-XSS-Protection: " + header_value + ": " +
error_details + " at character position " +
String::Format("%u", error_position) +
". The default protections will be applied."));
}
xss_protection_ = xss_protection_header;
if (xss_protection_ == kReflectedXSSInvalid ||
xss_protection_ == kReflectedXSSUnset) {
xss_protection_ = kBlockReflectedXSS;
}
if (auditor_delegate)
auditor_delegate->SetReportURL(xss_protection_report_url.Copy());
EncodedFormData* http_body = document_loader->GetRequest().HttpBody();
if (http_body && !http_body->IsEmpty())
http_body_as_string_ = http_body->FlattenToString();
}
SetEncoding(encoding_);
}
| 172,693
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size)
{
static void *send_buf;
static size_t send_buf_size;
uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size;
if (send_buf_size < pkg_size) {
if (send_buf)
free(send_buf);
send_buf_size = pkg_size * 2;
send_buf = malloc(send_buf_size);
assert(send_buf != NULL);
}
memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE);
if (pkg->ext_size)
memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size);
if (pkg->body_size)
memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size);
pkg = send_buf;
pkg->magic = htole32(RPC_PKG_MAGIC);
pkg->command = htole32(pkg->command);
pkg->pkg_type = htole16(pkg->pkg_type);
pkg->result = htole32(pkg->result);
pkg->sequence = htole32(pkg->sequence);
pkg->req_id = htole64(pkg->req_id);
pkg->body_size = htole32(pkg->body_size);
pkg->ext_size = htole16(pkg->ext_size);
pkg->crc32 = 0;
pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size));
*data = send_buf;
*size = pkg_size;
return 0;
}
Commit Message: Merge pull request #131 from benjaminchodroff/master
fix memory corruption and other 32bit overflows
CWE ID: CWE-190
|
int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size)
{
static void *send_buf;
static size_t send_buf_size;
uint32_t pkg_size;
if (pkg->body_size > RPC_PKG_MAX_BODY_SIZE) {
return -1;
}
pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size;
if (send_buf_size < pkg_size) {
if (send_buf)
free(send_buf);
send_buf_size = pkg_size * 2;
send_buf = malloc(send_buf_size);
if (send_buf == NULL) {
return -1;
}
}
memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE);
if (pkg->ext_size)
memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size);
if (pkg->body_size)
memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size);
pkg = send_buf;
pkg->magic = htole32(RPC_PKG_MAGIC);
pkg->command = htole32(pkg->command);
pkg->pkg_type = htole16(pkg->pkg_type);
pkg->result = htole32(pkg->result);
pkg->sequence = htole32(pkg->sequence);
pkg->req_id = htole64(pkg->req_id);
pkg->body_size = htole32(pkg->body_size);
pkg->ext_size = htole16(pkg->ext_size);
pkg->crc32 = 0;
pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size));
*data = send_buf;
*size = pkg_size;
return 0;
}
| 169,017
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(mcrypt_module_is_block_mode)
{
MCRYPT_GET_MODE_DIR_ARGS(modes_dir)
if (mcrypt_module_is_block_mode(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_module_is_block_mode)
{
MCRYPT_GET_MODE_DIR_ARGS(modes_dir)
if (mcrypt_module_is_block_mode(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
| 167,098
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void _out_result(conn_t out, nad_t nad) {
int attr;
jid_t from, to;
char *rkey;
int rkeylen;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db result packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db result packet");
jid_free(from);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
rkeylen = strlen(rkey);
/* key is valid */
if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : "");
xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */
log_debug(ZONE, "%s valid, flushing queue", rkey);
/* flush the queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* invalid */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey);
/* close connection */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port);
/* report stream error */
sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the stream */
sx_close(out->s);
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
}
Commit Message: Fixed possibility of Unsolicited Dialback Attacks
CWE ID: CWE-20
|
static void _out_result(conn_t out, nad_t nad) {
int attr;
jid_t from, to;
char *rkey;
int rkeylen;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db result packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db result packet");
jid_free(from);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
rkeylen = strlen(rkey);
/* key is valid */
if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0 && xhash_get(out->states, rkey) == (void*) conn_INPROGRESS) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : "");
xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */
log_debug(ZONE, "%s valid, flushing queue", rkey);
/* flush the queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* invalid */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey);
/* close connection */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port);
/* report stream error */
sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the stream */
sx_close(out->s);
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
}
| 165,576
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool PPVarToNPVariant(PP_Var var, NPVariant* result) {
switch (var.type) {
case PP_VARTYPE_UNDEFINED:
VOID_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_NULL:
NULL_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_BOOL:
BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result);
break;
case PP_VARTYPE_INT32:
INT32_TO_NPVARIANT(var.value.as_int, *result);
break;
case PP_VARTYPE_DOUBLE:
DOUBLE_TO_NPVARIANT(var.value.as_double, *result);
break;
case PP_VARTYPE_STRING: {
scoped_refptr<StringVar> string(StringVar::FromPPVar(var));
if (!string) {
VOID_TO_NPVARIANT(*result);
return false;
}
const std::string& value = string->value();
STRINGN_TO_NPVARIANT(base::strdup(value.c_str()), value.size(), *result);
break;
}
case PP_VARTYPE_OBJECT: {
scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var));
if (!object) {
VOID_TO_NPVARIANT(*result);
return false;
}
OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()),
*result);
break;
}
case PP_VARTYPE_ARRAY:
case PP_VARTYPE_DICTIONARY:
VOID_TO_NPVARIANT(*result);
break;
}
return true;
}
Commit Message: Fix invalid read in ppapi code
BUG=77493
TEST=attached test
Review URL: http://codereview.chromium.org/6883059
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@82172 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
bool PPVarToNPVariant(PP_Var var, NPVariant* result) {
switch (var.type) {
case PP_VARTYPE_UNDEFINED:
VOID_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_NULL:
NULL_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_BOOL:
BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result);
break;
case PP_VARTYPE_INT32:
INT32_TO_NPVARIANT(var.value.as_int, *result);
break;
case PP_VARTYPE_DOUBLE:
DOUBLE_TO_NPVARIANT(var.value.as_double, *result);
break;
case PP_VARTYPE_STRING: {
scoped_refptr<StringVar> string(StringVar::FromPPVar(var));
if (!string) {
VOID_TO_NPVARIANT(*result);
return false;
}
const std::string& value = string->value();
char* c_string = static_cast<char*>(malloc(value.size()));
memcpy(c_string, value.data(), value.size());
STRINGN_TO_NPVARIANT(c_string, value.size(), *result);
break;
}
case PP_VARTYPE_OBJECT: {
scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var));
if (!object) {
VOID_TO_NPVARIANT(*result);
return false;
}
OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()),
*result);
break;
}
case PP_VARTYPE_ARRAY:
case PP_VARTYPE_DICTIONARY:
VOID_TO_NPVARIANT(*result);
break;
}
return true;
}
| 170,554
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void get_checksum2(char *buf, int32 len, char *sum)
{
md_context m;
switch (xfersum_type) {
case CSUM_MD5: {
uchar seedbuf[4];
md5_begin(&m);
if (proper_seed_order) {
if (checksum_seed) {
SIVALu(seedbuf, 0, checksum_seed);
md5_update(&m, seedbuf, 4);
}
md5_update(&m, (uchar *)buf, len);
} else {
md5_update(&m, (uchar *)buf, len);
if (checksum_seed) {
SIVALu(seedbuf, 0, checksum_seed);
md5_update(&m, seedbuf, 4);
}
}
md5_result(&m, (uchar *)sum);
break;
}
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED: {
int32 i;
static char *buf1;
static int32 len1;
mdfour_begin(&m);
if (len > len1) {
if (buf1)
free(buf1);
buf1 = new_array(char, len+4);
len1 = len;
if (!buf1)
out_of_memory("get_checksum2");
}
memcpy(buf1, buf, len);
if (checksum_seed) {
SIVAL(buf1,len,checksum_seed);
len += 4;
}
for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK)
mdfour_update(&m, (uchar *)(buf1+i), CSUM_CHUNK);
/*
* Prior to version 27 an incorrect MD4 checksum was computed
* by failing to call mdfour_tail() for block sizes that
* are multiples of 64. This is fixed by calling mdfour_update()
* are multiples of 64. This is fixed by calling mdfour_update()
* even when there are no more bytes.
*/
if (len - i > 0 || xfersum_type != CSUM_MD4_BUSTED)
mdfour_update(&m, (uchar *)(buf1+i), len-i);
mdfour_result(&m, (uchar *)sum);
}
}
}
Commit Message:
CWE ID: CWE-354
|
void get_checksum2(char *buf, int32 len, char *sum)
{
md_context m;
switch (xfersum_type) {
case CSUM_MD5: {
uchar seedbuf[4];
md5_begin(&m);
if (proper_seed_order) {
if (checksum_seed) {
SIVALu(seedbuf, 0, checksum_seed);
md5_update(&m, seedbuf, 4);
}
md5_update(&m, (uchar *)buf, len);
} else {
md5_update(&m, (uchar *)buf, len);
if (checksum_seed) {
SIVALu(seedbuf, 0, checksum_seed);
md5_update(&m, seedbuf, 4);
}
}
md5_result(&m, (uchar *)sum);
break;
}
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
case CSUM_MD4_ARCHAIC: {
int32 i;
static char *buf1;
static int32 len1;
mdfour_begin(&m);
if (len > len1) {
if (buf1)
free(buf1);
buf1 = new_array(char, len+4);
len1 = len;
if (!buf1)
out_of_memory("get_checksum2");
}
memcpy(buf1, buf, len);
if (checksum_seed) {
SIVAL(buf1,len,checksum_seed);
len += 4;
}
for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK)
mdfour_update(&m, (uchar *)(buf1+i), CSUM_CHUNK);
/*
* Prior to version 27 an incorrect MD4 checksum was computed
* by failing to call mdfour_tail() for block sizes that
* are multiples of 64. This is fixed by calling mdfour_update()
* are multiples of 64. This is fixed by calling mdfour_update()
* even when there are no more bytes.
*/
if (len - i > 0 || xfersum_type > CSUM_MD4_BUSTED)
mdfour_update(&m, (uchar *)(buf1+i), len-i);
mdfour_result(&m, (uchar *)sum);
}
}
}
| 164,644
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/*tex If no number follows |/CharStrings|, let's read the next line. */
if (sscanf(p, "%i", &i) != 1) {
strcpy(t1_buf_array, t1_line_array);
t1_getline();
strcat(t1_buf_array, t1_line_array);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
Commit Message: writet1 protection against buffer overflow
git-svn-id: svn://tug.org/texlive/trunk/Build/source@48697 c570f23f-e606-0410-a88d-b1316a301751
CWE ID: CWE-119
|
static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/*tex If no number follows |/CharStrings|, let's read the next line. */
if (sscanf(p, "%i", &i) != 1) {
strcpy(t1_buf_array, t1_line_array);
t1_getline();
alloc_array(t1_buf, strlen(t1_line_array) + strlen(t1_buf_array) + 1, T1_BUF_SIZE);
strcat(t1_buf_array, t1_line_array);
alloc_array(t1_line, strlen(t1_buf_array) + 1, T1_BUF_SIZE);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
| 169,021
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: fm_mgr_config_mgr_connect
(
fm_config_conx_hdl *hdl,
fm_mgr_type_t mgr
)
{
char s_path[256];
char c_path[256];
char *mgr_prefix;
p_hsm_com_client_hdl_t *mgr_hdl;
pid_t pid;
memset(s_path,0,sizeof(s_path));
memset(c_path,0,sizeof(c_path));
pid = getpid();
switch ( mgr )
{
case FM_MGR_SM:
mgr_prefix = HSM_FM_SCK_SM;
mgr_hdl = &hdl->sm_hdl;
break;
case FM_MGR_PM:
mgr_prefix = HSM_FM_SCK_PM;
mgr_hdl = &hdl->pm_hdl;
break;
case FM_MGR_FE:
mgr_prefix = HSM_FM_SCK_FE;
mgr_hdl = &hdl->fe_hdl;
break;
default:
return FM_CONF_INIT_ERR;
}
sprintf(s_path,"%s%s%d",HSM_FM_SCK_PREFIX,mgr_prefix,hdl->instance);
sprintf(c_path,"%s%s%d_C_%lu",HSM_FM_SCK_PREFIX,mgr_prefix,
hdl->instance, (long unsigned)pid);
if ( *mgr_hdl == NULL )
{
if ( hcom_client_init(mgr_hdl,s_path,c_path,32768) != HSM_COM_OK )
{
return FM_CONF_INIT_ERR;
}
}
if ( hcom_client_connect(*mgr_hdl) == HSM_COM_OK )
{
hdl->conx_mask |= mgr;
return FM_CONF_OK;
}
return FM_CONF_CONX_ERR;
}
Commit Message: Fix scripts and code that use well-known tmp files.
CWE ID: CWE-362
|
fm_mgr_config_mgr_connect
(
fm_config_conx_hdl *hdl,
fm_mgr_type_t mgr
)
{
char s_path[256];
char c_path[256];
char *mgr_prefix;
p_hsm_com_client_hdl_t *mgr_hdl;
memset(s_path,0,sizeof(s_path));
memset(c_path,0,sizeof(c_path));
switch ( mgr )
{
case FM_MGR_SM:
mgr_prefix = HSM_FM_SCK_SM;
mgr_hdl = &hdl->sm_hdl;
break;
case FM_MGR_PM:
mgr_prefix = HSM_FM_SCK_PM;
mgr_hdl = &hdl->pm_hdl;
break;
case FM_MGR_FE:
mgr_prefix = HSM_FM_SCK_FE;
mgr_hdl = &hdl->fe_hdl;
break;
default:
return FM_CONF_INIT_ERR;
}
sprintf(s_path,"%s%s%d",HSM_FM_SCK_PREFIX,mgr_prefix,hdl->instance);
sprintf(c_path,"%s%s%d_C_XXXXXX",HSM_FM_SCK_PREFIX,mgr_prefix,hdl->instance);
if ( *mgr_hdl == NULL )
{
if ( hcom_client_init(mgr_hdl,s_path,c_path,32768) != HSM_COM_OK )
{
return FM_CONF_INIT_ERR;
}
}
if ( hcom_client_connect(*mgr_hdl) == HSM_COM_OK )
{
hdl->conx_mask |= mgr;
return FM_CONF_OK;
}
return FM_CONF_CONX_ERR;
}
| 170,131
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void Segment::AppendCluster(Cluster* pCluster) {
assert(pCluster);
assert(pCluster->m_index >= 0);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
const long idx = pCluster->m_index;
assert(idx == m_clusterCount);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new Cluster* [n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
if (m_clusterPreloadCount > 0) {
assert(m_clusters);
Cluster** const p = m_clusters + m_clusterCount;
assert(*p);
assert((*p)->m_index < 0);
Cluster** q = p + m_clusterPreloadCount;
assert(q < (m_clusters + size));
for (;;) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
if (q == p)
break;
}
}
m_clusters[idx] = pCluster;
++m_clusterCount;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
void Segment::AppendCluster(Cluster* pCluster) {
bool Segment::AppendCluster(Cluster* pCluster) {
if (pCluster == NULL || pCluster->m_index < 0)
return false;
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
const long idx = pCluster->m_index;
if (size < count || idx != m_clusterCount)
return false;
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new (std::nothrow) Cluster*[n];
if (qq == NULL)
return false;
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
if (m_clusterPreloadCount > 0) {
Cluster** const p = m_clusters + m_clusterCount;
if (*p == NULL || (*p)->m_index >= 0)
return false;
Cluster** q = p + m_clusterPreloadCount;
if (q >= (m_clusters + size))
return false;
for (;;) {
Cluster** const qq = q - 1;
if ((*qq)->m_index >= 0)
return false;
*q = *qq;
q = qq;
if (q == p)
break;
}
}
m_clusters[idx] = pCluster;
++m_clusterCount;
return true;
}
| 173,801
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: _PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic,
const char *s, charset_t src_charset, charset_t dst_charset)
{
size_t count = 0;
#ifdef DEVELOPER
switch (dst_charset) {
case CH_DOS:
case CH_UNIX:
smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)");
default:
break;
}
switch (src_charset) {
case CH_UTF16LE:
case CH_UTF16BE:
smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)");
default:
break;
}
#endif
if (!s) {
return 0;
}
while (*s && !(((uint8_t)*s) & 0x80)) {
s++;
count++;
}
if (!*s) {
return count;
}
while (*s) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(ic, s, src_charset, &c_size);
s += c_size;
switch (dst_charset) {
case CH_UTF16BE:
case CH_UTF16MUNGED:
if (c < 0x10000) {
/* Unicode char fits into 16 bits. */
count += 1;
} else {
/* Double-width unicode char - 32 bits. */
count += 2;
}
break;
case CH_UTF8:
/*
* this only checks ranges, and does not
* check for invalid codepoints
*/
if (c < 0x80) {
count += 1;
} else if (c < 0x800) {
count += 2;
} else if (c < 0x10000) {
count += 3;
} else {
count += 4;
}
break;
default:
/*
* non-unicode encoding:
* assume that each codepoint fits into
* one unit in the destination encoding.
*/
count += 1;
}
}
return count;
}
Commit Message:
CWE ID: CWE-200
|
_PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic,
const char *s, charset_t src_charset, charset_t dst_charset)
{
size_t count = 0;
#ifdef DEVELOPER
switch (dst_charset) {
case CH_DOS:
case CH_UNIX:
smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)");
default:
break;
}
switch (src_charset) {
case CH_UTF16LE:
case CH_UTF16BE:
smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)");
default:
break;
}
#endif
if (!s) {
return 0;
}
while (*s && !(((uint8_t)*s) & 0x80)) {
s++;
count++;
}
if (!*s) {
return count;
}
while (*s) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(ic, s, strnlen(s, 5),
src_charset, &c_size);
s += c_size;
switch (dst_charset) {
case CH_UTF16BE:
case CH_UTF16MUNGED:
if (c < 0x10000) {
/* Unicode char fits into 16 bits. */
count += 1;
} else {
/* Double-width unicode char - 32 bits. */
count += 2;
}
break;
case CH_UTF8:
/*
* this only checks ranges, and does not
* check for invalid codepoints
*/
if (c < 0x80) {
count += 1;
} else if (c < 0x800) {
count += 2;
} else if (c < 0x10000) {
count += 3;
} else {
count += 4;
}
break;
default:
/*
* non-unicode encoding:
* assume that each codepoint fits into
* one unit in the destination encoding.
*/
count += 1;
}
}
return count;
}
| 164,671
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: jp2_box_t *jp2_box_create(int type)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
return 0;
}
memset(box, 0, sizeof(jp2_box_t));
box->type = type;
box->len = 0;
if (!(boxinfo = jp2_boxinfolookup(type))) {
return 0;
}
box->info = boxinfo;
box->ops = &boxinfo->ops;
return box;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476
|
jp2_box_t *jp2_box_create(int type)
jp2_box_t *jp2_box_create0()
{
jp2_box_t *box;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
return 0;
}
memset(box, 0, sizeof(jp2_box_t));
box->type = 0;
box->len = 0;
// Mark the box data as never having been constructed
// so that we will not errantly attempt to destroy it later.
box->ops = &jp2_boxinfo_unk.ops;
return box;
}
jp2_box_t *jp2_box_create(int type)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
if (!(box = jp2_box_create0())) {
return 0;
}
box->type = type;
box->len = 0;
if (!(boxinfo = jp2_boxinfolookup(type))) {
return 0;
}
box->info = boxinfo;
box->ops = &boxinfo->ops;
return box;
}
| 168,317
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.