instruction
stringclasses
1 value
input
stringlengths
222
112k
output
stringlengths
21
113k
__index_level_0__
int64
15
30k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1586 CWE ID: CWE-119
static PixelChannels **AcquirePixelThreadSet(const Image *image) static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); }
19,788
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition) { ASSERT(m_document); ASSERT(!hasParserBlockingScript()); { ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script); ASSERT(scriptLoader); if (!scriptLoader) return; ASSERT(scriptLoader->isParserInserted()); if (!isExecutingScript()) Microtask::performCheckpoint(); InsertionPointRecord insertionPointRecord(m_host->inputStream()); NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); scriptLoader->prepareScript(scriptStartPosition); if (!scriptLoader->willBeParserExecuted()) return; if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) { requestDeferredScript(script); } else if (scriptLoader->readyToBeParserExecuted()) { if (m_scriptNestingLevel == 1) { m_parserBlockingScript.setElement(script); m_parserBlockingScript.setStartingPosition(scriptStartPosition); } else { ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition); scriptLoader->executeScript(sourceCode); } } else { requestParsingBlockingScript(script); } } } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254
void HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition) { ASSERT(m_document); ASSERT(!hasParserBlockingScript()); { ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script); ASSERT(scriptLoader); if (!scriptLoader) return; ASSERT(scriptLoader->isParserInserted()); if (!isExecutingScript()) Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate()); InsertionPointRecord insertionPointRecord(m_host->inputStream()); NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); scriptLoader->prepareScript(scriptStartPosition); if (!scriptLoader->willBeParserExecuted()) return; if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) { requestDeferredScript(script); } else if (scriptLoader->readyToBeParserExecuted()) { if (m_scriptNestingLevel == 1) { m_parserBlockingScript.setElement(script); m_parserBlockingScript.setStartingPosition(scriptStartPosition); } else { ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition); scriptLoader->executeScript(sourceCode); } } else { requestParsingBlockingScript(script); } } }
22,834
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void red_channel_pipes_add_type(RedChannel *channel, int pipe_item_type) { RingItem *link; RING_FOREACH(link, &channel->clients) { red_channel_client_pipe_add_type( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), pipe_item_type); } } Commit Message: CWE ID: CWE-399
void red_channel_pipes_add_type(RedChannel *channel, int pipe_item_type) { RingItem *link, *next; RING_FOREACH_SAFE(link, next, &channel->clients) { red_channel_client_pipe_add_type( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), pipe_item_type); } }
26,848
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool Cues::Find( long long time_ns, const Track* pTrack, const CuePoint*& pCP, const CuePoint::TrackPosition*& pTP) const { assert(time_ns >= 0); assert(pTrack); #if 0 LoadCuePoint(); //establish invariant assert(m_cue_points); assert(m_count > 0); CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count + m_preload_count; CuePoint** j = jj; pCP = *i; assert(pCP); if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL); } IMkvReader* const pReader = m_pSegment->m_pReader; while (i < j) { CuePoint** const k = i + (j - i) / 2; assert(k < jj); CuePoint* const pCP = *k; assert(pCP); pCP->Load(pReader); const long long t = pCP->GetTime(m_pSegment); if (t <= time_ns) i = k + 1; else j = k; assert(i <= j); } assert(i == j); assert(i <= jj); assert(i > ii); pCP = *--i; assert(pCP); assert(pCP->GetTime(m_pSegment) <= time_ns); #else if (m_cue_points == NULL) return false; if (m_count == 0) return false; CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count; CuePoint** j = jj; pCP = *i; assert(pCP); if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL); } while (i < j) { CuePoint** const k = i + (j - i) / 2; assert(k < jj); CuePoint* const pCP = *k; assert(pCP); const long long t = pCP->GetTime(m_pSegment); if (t <= time_ns) i = k + 1; else j = k; assert(i <= j); } assert(i == j); assert(i <= jj); assert(i > ii); pCP = *--i; assert(pCP); assert(pCP->GetTime(m_pSegment) <= time_ns); #endif pTP = pCP->Find(pTrack); return (pTP != NULL); } 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
bool Cues::Find( bool Cues::Find(long long time_ns, const Track* pTrack, const CuePoint*& pCP, const CuePoint::TrackPosition*& pTP) const { assert(time_ns >= 0); assert(pTrack); #if 0 LoadCuePoint(); //establish invariant assert(m_cue_points); assert(m_count > 0); CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count + m_preload_count; CuePoint** j = jj; pCP = *i; assert(pCP); if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL); } IMkvReader* const pReader = m_pSegment->m_pReader; while (i < j) { CuePoint** const k = i + (j - i) / 2; assert(k < jj); CuePoint* const pCP = *k; assert(pCP); pCP->Load(pReader); const long long t = pCP->GetTime(m_pSegment); if (t <= time_ns) i = k + 1; else j = k; assert(i <= j); } assert(i == j); assert(i <= jj); assert(i > ii); pCP = *--i; assert(pCP); assert(pCP->GetTime(m_pSegment) <= time_ns); #else if (m_cue_points == NULL) return false; if (m_count == 0) return false; CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count; CuePoint** j = jj; pCP = *i; assert(pCP); if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL);
27,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len, int atomic) { unsigned long copy; while (len > 0) { while (!iov->iov_len) iov++; copy = min_t(unsigned long, len, iov->iov_len); if (atomic) { if (__copy_from_user_inatomic(to, iov->iov_base, copy)) return -EFAULT; } else { if (copy_from_user(to, iov->iov_base, copy)) return -EFAULT; } to += copy; len -= copy; iov->iov_base += copy; iov->iov_len -= copy; } return 0; } Commit Message: new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len,
19,705
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns) { struct mnt_namespace *new_ns; struct ucounts *ucounts; int ret; ucounts = inc_mnt_namespaces(user_ns); if (!ucounts) return ERR_PTR(-ENOSPC); new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL); if (!new_ns) { dec_mnt_namespaces(ucounts); return ERR_PTR(-ENOMEM); } ret = ns_alloc_inum(&new_ns->ns); if (ret) { kfree(new_ns); dec_mnt_namespaces(ucounts); return ERR_PTR(ret); } new_ns->ns.ops = &mntns_operations; new_ns->seq = atomic64_add_return(1, &mnt_ns_seq); atomic_set(&new_ns->count, 1); new_ns->root = NULL; INIT_LIST_HEAD(&new_ns->list); init_waitqueue_head(&new_ns->poll); new_ns->event = 0; new_ns->user_ns = get_user_ns(user_ns); new_ns->ucounts = ucounts; return new_ns; } Commit Message: mnt: Add a per mount namespace limit on the number of mounts CAI Qian <[email protected]> pointed out that the semantics of shared subtrees make it possible to create an exponentially increasing number of mounts in a mount namespace. mkdir /tmp/1 /tmp/2 mount --make-rshared / for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done Will create create 2^20 or 1048576 mounts, which is a practical problem as some people have managed to hit this by accident. As such CVE-2016-6213 was assigned. Ian Kent <[email protected]> described the situation for autofs users as follows: > The number of mounts for direct mount maps is usually not very large because of > the way they are implemented, large direct mount maps can have performance > problems. There can be anywhere from a few (likely case a few hundred) to less > than 10000, plus mounts that have been triggered and not yet expired. > > Indirect mounts have one autofs mount at the root plus the number of mounts that > have been triggered and not yet expired. > > The number of autofs indirect map entries can range from a few to the common > case of several thousand and in rare cases up to between 30000 and 50000. I've > not heard of people with maps larger than 50000 entries. > > The larger the number of map entries the greater the possibility for a large > number of active mounts so it's not hard to expect cases of a 1000 or somewhat > more active mounts. So I am setting the default number of mounts allowed per mount namespace at 100,000. This is more than enough for any use case I know of, but small enough to quickly stop an exponential increase in mounts. Which should be perfect to catch misconfigurations and malfunctioning programs. For anyone who needs a higher limit this can be changed by writing to the new /proc/sys/fs/mount-max sysctl. Tested-by: CAI Qian <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-400
static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns) { struct mnt_namespace *new_ns; struct ucounts *ucounts; int ret; ucounts = inc_mnt_namespaces(user_ns); if (!ucounts) return ERR_PTR(-ENOSPC); new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL); if (!new_ns) { dec_mnt_namespaces(ucounts); return ERR_PTR(-ENOMEM); } ret = ns_alloc_inum(&new_ns->ns); if (ret) { kfree(new_ns); dec_mnt_namespaces(ucounts); return ERR_PTR(ret); } new_ns->ns.ops = &mntns_operations; new_ns->seq = atomic64_add_return(1, &mnt_ns_seq); atomic_set(&new_ns->count, 1); new_ns->root = NULL; INIT_LIST_HEAD(&new_ns->list); init_waitqueue_head(&new_ns->poll); new_ns->event = 0; new_ns->user_ns = get_user_ns(user_ns); new_ns->ucounts = ucounts; new_ns->mounts = 0; new_ns->pending_mounts = 0; return new_ns; }
27,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = (uint64_t)mTimeToSampleCount * 2 * sizeof(uint32_t); if (allocSize > UINT32_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new (std::nothrow) uint32_t[mTimeToSampleCount * 2]; if (!mTimeToSample) return ERROR_OUT_OF_RANGE; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (!mTimeToSample.empty() || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { // Choose this bound because // 1) 2 * sizeof(uint32_t) is the amount of memory needed for one // time-to-sample entry in the time-to-sample table. // 2) mTimeToSampleCount is the number of entries of the time-to-sample // table. // 3) We hope that the table size does not exceed UINT32_MAX. ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } // Note: At this point, we know that mTimeToSampleCount * 2 will not // overflow because of the above condition. if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } return OK; }
27,170
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int snd_timer_start_slave(struct snd_timer_instance *timeri) { unsigned long flags; spin_lock_irqsave(&slave_active_lock, flags); timeri->flags |= SNDRV_TIMER_IFLG_RUNNING; if (timeri->master) list_add_tail(&timeri->active_list, &timeri->master->slave_active_head); spin_unlock_irqrestore(&slave_active_lock, flags); return 1; /* delayed start */ } Commit Message: ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-20
static int snd_timer_start_slave(struct snd_timer_instance *timeri) { unsigned long flags; spin_lock_irqsave(&slave_active_lock, flags); timeri->flags |= SNDRV_TIMER_IFLG_RUNNING; if (timeri->master && timeri->timer) { spin_lock(&timeri->timer->lock); list_add_tail(&timeri->active_list, &timeri->master->slave_active_head); spin_unlock(&timeri->timer->lock); } spin_unlock_irqrestore(&slave_active_lock, flags); return 1; /* delayed start */ }
11,197
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags, key_perm_t perm) { struct keyring_search_context ctx = { .match_data.cmp = lookup_user_key_possessed, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; struct request_key_auth *rka; struct key *key; key_ref_t key_ref, skey_ref; int ret; try_again: ctx.cred = get_current_cred(); key_ref = ERR_PTR(-ENOKEY); switch (id) { case KEY_SPEC_THREAD_KEYRING: if (!ctx.cred->thread_keyring) { if (!(lflags & KEY_LOOKUP_CREATE)) goto error; ret = install_thread_keyring(); if (ret < 0) { key_ref = ERR_PTR(ret); goto error; } goto reget_creds; } key = ctx.cred->thread_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_PROCESS_KEYRING: if (!ctx.cred->process_keyring) { if (!(lflags & KEY_LOOKUP_CREATE)) goto error; ret = install_process_keyring(); if (ret < 0) { key_ref = ERR_PTR(ret); goto error; } goto reget_creds; } key = ctx.cred->process_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_SESSION_KEYRING: if (!ctx.cred->session_keyring) { /* always install a session keyring upon access if one * doesn't exist yet */ ret = install_user_keyrings(); if (ret < 0) goto error; if (lflags & KEY_LOOKUP_CREATE) ret = join_session_keyring(NULL); else ret = install_session_keyring( ctx.cred->user->session_keyring); if (ret < 0) goto error; goto reget_creds; } else if (ctx.cred->session_keyring == ctx.cred->user->session_keyring && lflags & KEY_LOOKUP_CREATE) { ret = join_session_keyring(NULL); if (ret < 0) goto error; goto reget_creds; } rcu_read_lock(); key = rcu_dereference(ctx.cred->session_keyring); __key_get(key); rcu_read_unlock(); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_USER_KEYRING: if (!ctx.cred->user->uid_keyring) { ret = install_user_keyrings(); if (ret < 0) goto error; } key = ctx.cred->user->uid_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_USER_SESSION_KEYRING: if (!ctx.cred->user->session_keyring) { ret = install_user_keyrings(); if (ret < 0) goto error; } key = ctx.cred->user->session_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_GROUP_KEYRING: /* group keyrings are not yet supported */ key_ref = ERR_PTR(-EINVAL); goto error; case KEY_SPEC_REQKEY_AUTH_KEY: key = ctx.cred->request_key_auth; if (!key) goto error; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_REQUESTOR_KEYRING: if (!ctx.cred->request_key_auth) goto error; down_read(&ctx.cred->request_key_auth->sem); if (test_bit(KEY_FLAG_REVOKED, &ctx.cred->request_key_auth->flags)) { key_ref = ERR_PTR(-EKEYREVOKED); key = NULL; } else { rka = ctx.cred->request_key_auth->payload.data[0]; key = rka->dest_keyring; __key_get(key); } up_read(&ctx.cred->request_key_auth->sem); if (!key) goto error; key_ref = make_key_ref(key, 1); break; default: key_ref = ERR_PTR(-EINVAL); if (id < 1) goto error; key = key_lookup(id); if (IS_ERR(key)) { key_ref = ERR_CAST(key); goto error; } key_ref = make_key_ref(key, 0); /* check to see if we possess the key */ ctx.index_key.type = key->type; ctx.index_key.description = key->description; ctx.index_key.desc_len = strlen(key->description); ctx.match_data.raw_data = key; kdebug("check possessed"); skey_ref = search_process_keyrings(&ctx); kdebug("possessed=%p", skey_ref); if (!IS_ERR(skey_ref)) { key_put(key); key_ref = skey_ref; } break; } /* unlink does not use the nominated key in any way, so can skip all * the permission checks as it is only concerned with the keyring */ if (lflags & KEY_LOOKUP_FOR_UNLINK) { ret = 0; goto error; } if (!(lflags & KEY_LOOKUP_PARTIAL)) { ret = wait_for_key_construction(key, true); switch (ret) { case -ERESTARTSYS: goto invalid_key; default: if (perm) goto invalid_key; case 0: break; } } else if (perm) { ret = key_validate(key); if (ret < 0) goto invalid_key; } ret = -EIO; if (!(lflags & KEY_LOOKUP_PARTIAL) && !test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) goto invalid_key; /* check the permissions */ ret = key_task_permission(key_ref, ctx.cred, perm); if (ret < 0) goto invalid_key; key->last_used_at = current_kernel_time().tv_sec; error: put_cred(ctx.cred); return key_ref; invalid_key: key_ref_put(key_ref); key_ref = ERR_PTR(ret); goto error; /* if we attempted to install a keyring, then it may have caused new * creds to be installed */ reget_creds: put_cred(ctx.cred); goto try_again; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags, key_perm_t perm) { struct keyring_search_context ctx = { .match_data.cmp = lookup_user_key_possessed, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; struct request_key_auth *rka; struct key *key; key_ref_t key_ref, skey_ref; int ret; try_again: ctx.cred = get_current_cred(); key_ref = ERR_PTR(-ENOKEY); switch (id) { case KEY_SPEC_THREAD_KEYRING: if (!ctx.cred->thread_keyring) { if (!(lflags & KEY_LOOKUP_CREATE)) goto error; ret = install_thread_keyring(); if (ret < 0) { key_ref = ERR_PTR(ret); goto error; } goto reget_creds; } key = ctx.cred->thread_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_PROCESS_KEYRING: if (!ctx.cred->process_keyring) { if (!(lflags & KEY_LOOKUP_CREATE)) goto error; ret = install_process_keyring(); if (ret < 0) { key_ref = ERR_PTR(ret); goto error; } goto reget_creds; } key = ctx.cred->process_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_SESSION_KEYRING: if (!ctx.cred->session_keyring) { /* always install a session keyring upon access if one * doesn't exist yet */ ret = install_user_keyrings(); if (ret < 0) goto error; if (lflags & KEY_LOOKUP_CREATE) ret = join_session_keyring(NULL); else ret = install_session_keyring( ctx.cred->user->session_keyring); if (ret < 0) goto error; goto reget_creds; } else if (ctx.cred->session_keyring == ctx.cred->user->session_keyring && lflags & KEY_LOOKUP_CREATE) { ret = join_session_keyring(NULL); if (ret < 0) goto error; goto reget_creds; } rcu_read_lock(); key = rcu_dereference(ctx.cred->session_keyring); __key_get(key); rcu_read_unlock(); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_USER_KEYRING: if (!ctx.cred->user->uid_keyring) { ret = install_user_keyrings(); if (ret < 0) goto error; } key = ctx.cred->user->uid_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_USER_SESSION_KEYRING: if (!ctx.cred->user->session_keyring) { ret = install_user_keyrings(); if (ret < 0) goto error; } key = ctx.cred->user->session_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_GROUP_KEYRING: /* group keyrings are not yet supported */ key_ref = ERR_PTR(-EINVAL); goto error; case KEY_SPEC_REQKEY_AUTH_KEY: key = ctx.cred->request_key_auth; if (!key) goto error; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_REQUESTOR_KEYRING: if (!ctx.cred->request_key_auth) goto error; down_read(&ctx.cred->request_key_auth->sem); if (test_bit(KEY_FLAG_REVOKED, &ctx.cred->request_key_auth->flags)) { key_ref = ERR_PTR(-EKEYREVOKED); key = NULL; } else { rka = ctx.cred->request_key_auth->payload.data[0]; key = rka->dest_keyring; __key_get(key); } up_read(&ctx.cred->request_key_auth->sem); if (!key) goto error; key_ref = make_key_ref(key, 1); break; default: key_ref = ERR_PTR(-EINVAL); if (id < 1) goto error; key = key_lookup(id); if (IS_ERR(key)) { key_ref = ERR_CAST(key); goto error; } key_ref = make_key_ref(key, 0); /* check to see if we possess the key */ ctx.index_key.type = key->type; ctx.index_key.description = key->description; ctx.index_key.desc_len = strlen(key->description); ctx.match_data.raw_data = key; kdebug("check possessed"); skey_ref = search_process_keyrings(&ctx); kdebug("possessed=%p", skey_ref); if (!IS_ERR(skey_ref)) { key_put(key); key_ref = skey_ref; } break; } /* unlink does not use the nominated key in any way, so can skip all * the permission checks as it is only concerned with the keyring */ if (lflags & KEY_LOOKUP_FOR_UNLINK) { ret = 0; goto error; } if (!(lflags & KEY_LOOKUP_PARTIAL)) { ret = wait_for_key_construction(key, true); switch (ret) { case -ERESTARTSYS: goto invalid_key; default: if (perm) goto invalid_key; case 0: break; } } else if (perm) { ret = key_validate(key); if (ret < 0) goto invalid_key; } ret = -EIO; if (!(lflags & KEY_LOOKUP_PARTIAL) && key_read_state(key) == KEY_IS_UNINSTANTIATED) goto invalid_key; /* check the permissions */ ret = key_task_permission(key_ref, ctx.cred, perm); if (ret < 0) goto invalid_key; key->last_used_at = current_kernel_time().tv_sec; error: put_cred(ctx.cred); return key_ref; invalid_key: key_ref_put(key_ref); key_ref = ERR_PTR(ret); goto error; /* if we attempted to install a keyring, then it may have caused new * creds to be installed */ reget_creds: put_cred(ctx.cred); goto try_again; }
23,499
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: std::string* GetTestingDMToken() { static std::string dm_token; return &dm_token; } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
std::string* GetTestingDMToken() { const char** GetTestingDMTokenStorage() { static const char* dm_token = ""; return &dm_token; }
18,842
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (!ShouldAllowSession(session)) return false; protocol::EmulationHandler* emulation_handler = new protocol::EmulationHandler(); session->AddHandler(base::WrapUnique(new protocol::BrowserHandler())); session->AddHandler(base::WrapUnique(new protocol::DOMHandler())); session->AddHandler(base::WrapUnique(emulation_handler)); session->AddHandler(base::WrapUnique(new protocol::InputHandler())); session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::IOHandler( GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::MemoryHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler( GetId(), frame_tree_node_ ? frame_tree_node_->devtools_frame_token() : base::UnguessableToken(), GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler())); session->AddHandler(base::WrapUnique(new protocol::StorageHandler())); session->AddHandler(base::WrapUnique(new protocol::TargetHandler( session->client()->MayAttachToBrowser() ? protocol::TargetHandler::AccessMode::kRegular : protocol::TargetHandler::AccessMode::kAutoAttachOnly, GetId(), GetRendererChannel(), session->GetRootSession()))); session->AddHandler(base::WrapUnique(new protocol::PageHandler( emulation_handler, session->client()->MayAffectLocalFiles()))); session->AddHandler(base::WrapUnique(new protocol::SecurityHandler())); if (!frame_tree_node_ || !frame_tree_node_->parent()) { session->AddHandler(base::WrapUnique( new protocol::TracingHandler(frame_tree_node_, GetIOContext()))); } if (sessions().empty()) { bool use_video_capture_api = true; #ifdef OS_ANDROID if (!CompositorImpl::IsInitialized()) use_video_capture_api = false; #endif if (!use_video_capture_api) frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder()); GrantPolicy(); #if defined(OS_ANDROID) GetWakeLock()->RequestWakeLock(); #endif } return true; } Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles Bug: 805557 Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f Reviewed-on: https://chromium-review.googlesource.com/c/1334847 Reviewed-by: Pavel Feldman <[email protected]> Commit-Queue: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#607902} CWE ID: CWE-254
bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (!ShouldAllowSession(session)) return false; protocol::EmulationHandler* emulation_handler = new protocol::EmulationHandler(); session->AddHandler(base::WrapUnique(new protocol::BrowserHandler())); session->AddHandler(base::WrapUnique( new protocol::DOMHandler(session->client()->MayAffectLocalFiles()))); session->AddHandler(base::WrapUnique(emulation_handler)); session->AddHandler(base::WrapUnique(new protocol::InputHandler())); session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::IOHandler( GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::MemoryHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler( GetId(), frame_tree_node_ ? frame_tree_node_->devtools_frame_token() : base::UnguessableToken(), GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler())); session->AddHandler(base::WrapUnique(new protocol::StorageHandler())); session->AddHandler(base::WrapUnique(new protocol::TargetHandler( session->client()->MayAttachToBrowser() ? protocol::TargetHandler::AccessMode::kRegular : protocol::TargetHandler::AccessMode::kAutoAttachOnly, GetId(), GetRendererChannel(), session->GetRootSession()))); session->AddHandler(base::WrapUnique(new protocol::PageHandler( emulation_handler, session->client()->MayAffectLocalFiles()))); session->AddHandler(base::WrapUnique(new protocol::SecurityHandler())); if (!frame_tree_node_ || !frame_tree_node_->parent()) { session->AddHandler(base::WrapUnique( new protocol::TracingHandler(frame_tree_node_, GetIOContext()))); } if (sessions().empty()) { bool use_video_capture_api = true; #ifdef OS_ANDROID if (!CompositorImpl::IsInitialized()) use_video_capture_api = false; #endif if (!use_video_capture_api) frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder()); GrantPolicy(); #if defined(OS_ANDROID) GetWakeLock()->RequestWakeLock(); #endif } return true; }
12,575
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info, size_t count, const uint64_t clsid[2]) { size_t i; cdf_timestamp_t tp; struct timespec ts; char buf[64]; const char *str = NULL; const char *s; int len; if (!NOTMIME(ms)) str = cdf_clsid_to_mime(clsid, clsid2mime); for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf, info[i].pi_s16) == -1) return -1; break; case CDF_SIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf, info[i].pi_s32) == -1) return -1; break; case CDF_UNSIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf, info[i].pi_u32) == -1) return -1; break; case CDF_FLOAT: if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf, info[i].pi_f) == -1) return -1; break; case CDF_DOUBLE: if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf, info[i].pi_d) == -1) return -1; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: len = info[i].pi_str.s_len; if (len > 1) { char vbuf[1024]; size_t j, k = 1; if (info[i].pi_type == CDF_LENGTH32_WSTRING) k++; s = info[i].pi_str.s_buf; for (j = 0; j < sizeof(vbuf) && len--; j++, s += k) { if (*s == '\0') break; if (isprint((unsigned char)*s)) vbuf[j] = *s; } if (j == sizeof(vbuf)) --j; vbuf[j] = '\0'; if (NOTMIME(ms)) { if (vbuf[0]) { if (file_printf(ms, ", %s: %s", buf, vbuf) == -1) return -1; } } else if (str == NULL && info[i].pi_id == CDF_PROPERTY_NAME_OF_APPLICATION) { str = cdf_app_to_mime(vbuf, app2mime); } } break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp != 0) { char tbuf[64]; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(tbuf, sizeof(tbuf), tp); if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, tbuf) == -1) return -1; } else { char *c, *ec; cdf_timestamp_to_timespec(&ts, tp); c = cdf_ctime(&ts.tv_sec, tbuf); if (c != NULL && (ec = strchr(c, '\n')) != NULL) *ec = '\0'; if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, c) == -1) return -1; } } break; case CDF_CLIPBOARD: break; default: return -1; } } if (!NOTMIME(ms)) { if (str == NULL) return 0; if (file_printf(ms, "application/%s", str) == -1) return -1; } return 1; } Commit Message: Apply patches from file-CVE-2012-1571.patch From Francisco Alonso Espejo: file < 5.18/git version can be made to crash when checking some corrupt CDF files (Using an invalid cdf_read_short_sector size) The problem I found here, is that in most situations (if h_short_sec_size_p2 > 8) because the blocksize is 512 and normal values are 06 which means reading 64 bytes.As long as the check for the block size copy is not checked properly (there's an assert that makes wrong/invalid assumptions) CWE ID: CWE-119
cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info, size_t count, const cdf_directory_t *root_storage) { size_t i; cdf_timestamp_t tp; struct timespec ts; char buf[64]; const char *str = NULL; const char *s; int len; if (!NOTMIME(ms) && root_storage) str = cdf_clsid_to_mime(root_storage->d_storage_uuid, clsid2mime); for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf, info[i].pi_s16) == -1) return -1; break; case CDF_SIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf, info[i].pi_s32) == -1) return -1; break; case CDF_UNSIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf, info[i].pi_u32) == -1) return -1; break; case CDF_FLOAT: if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf, info[i].pi_f) == -1) return -1; break; case CDF_DOUBLE: if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf, info[i].pi_d) == -1) return -1; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: len = info[i].pi_str.s_len; if (len > 1) { char vbuf[1024]; size_t j, k = 1; if (info[i].pi_type == CDF_LENGTH32_WSTRING) k++; s = info[i].pi_str.s_buf; for (j = 0; j < sizeof(vbuf) && len--; j++, s += k) { if (*s == '\0') break; if (isprint((unsigned char)*s)) vbuf[j] = *s; } if (j == sizeof(vbuf)) --j; vbuf[j] = '\0'; if (NOTMIME(ms)) { if (vbuf[0]) { if (file_printf(ms, ", %s: %s", buf, vbuf) == -1) return -1; } } else if (str == NULL && info[i].pi_id == CDF_PROPERTY_NAME_OF_APPLICATION) { str = cdf_app_to_mime(vbuf, app2mime); } } break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp != 0) { char tbuf[64]; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(tbuf, sizeof(tbuf), tp); if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, tbuf) == -1) return -1; } else { char *c, *ec; cdf_timestamp_to_timespec(&ts, tp); c = cdf_ctime(&ts.tv_sec, tbuf); if (c != NULL && (ec = strchr(c, '\n')) != NULL) *ec = '\0'; if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, c) == -1) return -1; } } break; case CDF_CLIPBOARD: break; default: return -1; } } if (!NOTMIME(ms)) { if (str == NULL) return 0; if (file_printf(ms, "application/%s", str) == -1) return -1; } return 1; }
834
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: WebContents* DevToolsWindow::OpenURLFromTab( WebContents* source, const content::OpenURLParams& params) { DCHECK(source == main_web_contents_); if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) { WebContents* inspected_web_contents = GetInspectedWebContents(); return inspected_web_contents ? inspected_web_contents->OpenURL(params) : NULL; } bindings_->Reload(); return main_web_contents_; } Commit Message: [DevTools] Use no-referrer for DevTools links Bug: 732751 Change-Id: I77753120e2424203dedcc7bc0847fb67f87fe2b2 Reviewed-on: https://chromium-review.googlesource.com/615021 Reviewed-by: Andrey Kosyakov <[email protected]> Commit-Queue: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#494413} CWE ID: CWE-668
WebContents* DevToolsWindow::OpenURLFromTab( WebContents* source, const content::OpenURLParams& params) { DCHECK(source == main_web_contents_); if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) { WebContents* inspected_web_contents = GetInspectedWebContents(); if (!inspected_web_contents) return nullptr; content::OpenURLParams modified = params; modified.referrer = content::Referrer(); return inspected_web_contents->OpenURL(modified); } bindings_->Reload(); return main_web_contents_; }
24,155
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
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)");
15,918
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: juniper_atm2_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM2; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */ (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) { ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */ return l2info.header_len; if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
juniper_atm2_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM2; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */ (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) { ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */ return l2info.header_len; if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; }
10,518
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: PHP_METHOD(Phar, getSupportedCompression) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, "GZ", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, "BZIP2", 5, 1); } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, getSupportedCompression) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, "GZ", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, "BZIP2", 5, 1); } }
9,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static struct ip_options *ip_options_get_alloc(const int optlen) { return kzalloc(sizeof(struct ip_options) + ((optlen + 3) & ~3), GFP_KERNEL); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static struct ip_options *ip_options_get_alloc(const int optlen) static struct ip_options_rcu *ip_options_get_alloc(const int optlen) { return kzalloc(sizeof(struct ip_options_rcu) + ((optlen + 3) & ~3), GFP_KERNEL); }
18,827
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; access_token_.clear(); expires_in_seconds_ = 0; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; request_.reset(new UrlFetcher(GURL(provider_info_.access_token_url), UrlFetcher::POST)); request_->SetRequestContext(request_context_getter_); request_->SetUploadData("application/x-www-form-urlencoded", post_body); request_->Start( base::Bind(&GaiaOAuthClient::Core::OnAuthTokenFetchComplete, this)); } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; access_token_.clear(); expires_in_seconds_ = 0; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; request_.reset(net::URLFetcher::Create( GURL(provider_info_.access_token_url), net::URLFetcher::POST, this)); request_->SetRequestContext(request_context_getter_); request_->SetUploadData("application/x-www-form-urlencoded", post_body); url_fetcher_type_ = URL_FETCHER_REFRESH_TOKEN; request_->Start(); } void GaiaOAuthClient::Core::OnURLFetchComplete( const net::URLFetcher* source) { std::string response_string; source->GetResponseAsString(&response_string); switch (url_fetcher_type_) { case URL_FETCHER_REFRESH_TOKEN: OnAuthTokenFetchComplete(source->GetStatus(), source->GetResponseCode(), response_string); break; case URL_FETCHER_GET_USER_INFO: OnUserInfoFetchComplete(source->GetStatus(), source->GetResponseCode(), response_string); break; default: LOG(ERROR) << "Unrecognised URLFetcher type: " << url_fetcher_type_; } }
28,874
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { if (!render_frame_created_) return false; ScopedActiveURL scoped_active_url(this); bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; if (delegate_->OnMessageReceived(this, msg)) return true; RenderFrameProxyHost* proxy = frame_tree_node_->render_manager()->GetProxyToParent(); if (proxy && proxy->cross_process_frame_connector() && proxy->cross_process_frame_connector()->OnMessageReceived(msg)) return true; handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole, OnDidAddMessageToConsole) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoad, OnDidStartProvisionalLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted, OnDocumentOnLoadCompleted) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse, OnJavaScriptExecuteResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse, OnVisualStateResponse) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog, OnRunJavaScriptDialog) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(FrameHostMsg_RunFileChooser, OnRunFileChooser) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies, OnDidAddContentSecurityPolicies) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy, OnDidChangeFramePolicy) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties, OnDidChangeFrameOwnerProperties) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust) IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent, OnForwardResourceTimingToParent) IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse, OnTextSurroundingSelectionResponse) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult, OnAccessibilityFindInPageResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult, OnAccessibilityChildFrameHitTestResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse, OnAccessibilitySnapshotResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged, OnSuddenTerminationDisablerChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress, OnDidChangeLoadProgress) IPC_MESSAGE_HANDLER(FrameHostMsg_SerializeAsMHTMLResponse, OnSerializeAsMHTMLResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGesture, OnSetHasReceivedUserGesture) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation, OnSetHasReceivedUserGestureBeforeNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame, OnScrollRectToVisibleInParentFrame) #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) #endif IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken, OnRequestOverlayRoutingToken) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow) IPC_MESSAGE_HANDLER(FrameHostMsg_StreamHandleConsumed, OnStreamHandleConsumed) IPC_END_MESSAGE_MAP() return handled; } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID:
bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { if (!render_frame_created_) return false; ScopedActiveURL scoped_active_url(this); bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; if (delegate_->OnMessageReceived(this, msg)) return true; RenderFrameProxyHost* proxy = frame_tree_node_->render_manager()->GetProxyToParent(); if (proxy && proxy->cross_process_frame_connector() && proxy->cross_process_frame_connector()->OnMessageReceived(msg)) return true; handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole, OnDidAddMessageToConsole) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoad, OnDidStartProvisionalLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted, OnDocumentOnLoadCompleted) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse, OnJavaScriptExecuteResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse, OnVisualStateResponse) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog, OnRunJavaScriptDialog) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(FrameHostMsg_RunFileChooser, OnRunFileChooser) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies, OnDidAddContentSecurityPolicies) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy, OnDidChangeFramePolicy) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties, OnDidChangeFrameOwnerProperties) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust) IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent, OnForwardResourceTimingToParent) IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse, OnTextSurroundingSelectionResponse) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult, OnAccessibilityFindInPageResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult, OnAccessibilityChildFrameHitTestResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse, OnAccessibilitySnapshotResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged, OnSuddenTerminationDisablerChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress, OnDidChangeLoadProgress) IPC_MESSAGE_HANDLER(FrameHostMsg_SerializeAsMHTMLResponse, OnSerializeAsMHTMLResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGesture, OnSetHasReceivedUserGesture) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation, OnSetHasReceivedUserGestureBeforeNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame, OnScrollRectToVisibleInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus) #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) #endif IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken, OnRequestOverlayRoutingToken) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow) IPC_MESSAGE_HANDLER(FrameHostMsg_StreamHandleConsumed, OnStreamHandleConsumed) IPC_END_MESSAGE_MAP() return handled; }
20,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; ext4_lblk_t punch_start, punch_stop; handle_t *handle; unsigned int credits; loff_t new_size, ioffset; int ret; /* * We need to test this early because xfstests assumes that a * collapse range of (0, 1) will return EOPNOTSUPP if the file * system does not support collapse range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Collapse range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EINVAL; trace_ext4_collapse_range(inode, offset, len); punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb); punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down offset to be aligned with page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* * There is no need to overlap collapse range with EOF, in which case * it is effectively a truncate operation */ if (offset + len >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } truncate_pagecache(inode, ioffset); /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_dio; } down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ext4_discard_preallocations(inode); ret = ext4_ext_shift_extents(inode, handle, punch_stop, punch_stop - punch_start, SHIFT_LEFT); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } new_size = i_size_read(inode) - len; i_size_write(inode, new_size); EXT4_I(inode)->i_disksize = new_size; up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-362
int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; ext4_lblk_t punch_start, punch_stop; handle_t *handle; unsigned int credits; loff_t new_size, ioffset; int ret; /* * We need to test this early because xfstests assumes that a * collapse range of (0, 1) will return EOPNOTSUPP if the file * system does not support collapse range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Collapse range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EINVAL; trace_ext4_collapse_range(inode, offset, len); punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb); punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down offset to be aligned with page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* * There is no need to overlap collapse range with EOF, in which case * it is effectively a truncate operation */ if (offset + len >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* * Prevent page faults from reinstantiating pages we have released from * page cache. */ down_write(&EXT4_I(inode)->i_mmap_sem); truncate_pagecache(inode, ioffset); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_mmap; } down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ext4_discard_preallocations(inode); ret = ext4_ext_shift_extents(inode, handle, punch_stop, punch_stop - punch_start, SHIFT_LEFT); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } new_size = i_size_read(inode) - len; i_size_write(inode, new_size); EXT4_I(inode)->i_disksize = new_size; up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_mmap: up_write(&EXT4_I(inode)->i_mmap_sem); ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; }
25,589
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static InputMethodStatusConnection* GetConnection( void* language_library, LanguageCurrentInputMethodMonitorFunction current_input_method_changed, LanguageRegisterImePropertiesFunction register_ime_properties, LanguageUpdateImePropertyFunction update_ime_property, LanguageConnectionChangeMonitorFunction connection_change_handler) { DCHECK(language_library); DCHECK(current_input_method_changed), DCHECK(register_ime_properties); DCHECK(update_ime_property); InputMethodStatusConnection* object = GetInstance(); if (!object->language_library_) { object->language_library_ = language_library; object->current_input_method_changed_ = current_input_method_changed; object->register_ime_properties_= register_ime_properties; object->update_ime_property_ = update_ime_property; object->connection_change_handler_ = connection_change_handler; object->MaybeRestoreConnections(); } else if (object->language_library_ != language_library) { LOG(ERROR) << "Unknown language_library is passed"; } return object; } 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
static InputMethodStatusConnection* GetConnection( // TODO(satorux,yusukes): Remove use of singleton here. static IBusControllerImpl* GetInstance() { return Singleton<IBusControllerImpl, LeakySingletonTraits<IBusControllerImpl> >::get(); }
29,947
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static v8::Handle<v8::Value> postMessageCallback(const v8::Arguments& args) { INC_STATS("DOM.TestActiveDOMObject.postMessage"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, message, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->postMessage(message); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> postMessageCallback(const v8::Arguments& args) { INC_STATS("DOM.TestActiveDOMObject.postMessage"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, message, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->postMessage(message); return v8::Handle<v8::Value>(); }
2,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int dccp_v6_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in6 *usin = (struct sockaddr_in6 *)uaddr; struct inet_connection_sock *icsk = inet_csk(sk); struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct dccp_sock *dp = dccp_sk(sk); struct in6_addr *saddr = NULL, *final_p, final; struct flowi6 fl6; struct dst_entry *dst; int addr_type; int err; dp->dccps_role = DCCP_ROLE_CLIENT; if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (usin->sin6_family != AF_INET6) return -EAFNOSUPPORT; memset(&fl6, 0, sizeof(fl6)); if (np->sndflow) { fl6.flowlabel = usin->sin6_flowinfo & IPV6_FLOWINFO_MASK; IP6_ECN_flow_init(fl6.flowlabel); if (fl6.flowlabel & IPV6_FLOWLABEL_MASK) { struct ip6_flowlabel *flowlabel; flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; fl6_sock_release(flowlabel); } } /* * connect() to INADDR_ANY means loopback (BSD'ism). */ if (ipv6_addr_any(&usin->sin6_addr)) usin->sin6_addr.s6_addr[15] = 1; addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type & IPV6_ADDR_MULTICAST) return -ENETUNREACH; if (addr_type & IPV6_ADDR_LINKLOCAL) { if (addr_len >= sizeof(struct sockaddr_in6) && usin->sin6_scope_id) { /* If interface is set while binding, indices * must coincide. */ if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != usin->sin6_scope_id) return -EINVAL; sk->sk_bound_dev_if = usin->sin6_scope_id; } /* Connect to link-local address requires an interface */ if (!sk->sk_bound_dev_if) return -EINVAL; } sk->sk_v6_daddr = usin->sin6_addr; np->flow_label = fl6.flowlabel; /* * DCCP over IPv4 */ if (addr_type == IPV6_ADDR_MAPPED) { u32 exthdrlen = icsk->icsk_ext_hdr_len; struct sockaddr_in sin; SOCK_DEBUG(sk, "connect: ipv4 mapped\n"); if (__ipv6_only_sock(sk)) return -ENETUNREACH; sin.sin_family = AF_INET; sin.sin_port = usin->sin6_port; sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3]; icsk->icsk_af_ops = &dccp_ipv6_mapped; sk->sk_backlog_rcv = dccp_v4_do_rcv; err = dccp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin)); if (err) { icsk->icsk_ext_hdr_len = exthdrlen; icsk->icsk_af_ops = &dccp_ipv6_af_ops; sk->sk_backlog_rcv = dccp_v6_do_rcv; goto failure; } np->saddr = sk->sk_v6_rcv_saddr; return err; } if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr)) saddr = &sk->sk_v6_rcv_saddr; fl6.flowi6_proto = IPPROTO_DCCP; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = saddr ? *saddr : np->saddr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.fl6_dport = usin->sin6_port; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); final_p = fl6_update_dst(&fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); goto failure; } if (saddr == NULL) { saddr = &fl6.saddr; sk->sk_v6_rcv_saddr = *saddr; } /* set the source address */ np->saddr = *saddr; inet->inet_rcv_saddr = LOOPBACK4_IPV6; __ip6_dst_store(sk, dst, NULL, NULL); icsk->icsk_ext_hdr_len = 0; if (np->opt != NULL) icsk->icsk_ext_hdr_len = (np->opt->opt_flen + np->opt->opt_nflen); inet->inet_dport = usin->sin6_port; dccp_set_state(sk, DCCP_REQUESTING); err = inet6_hash_connect(&dccp_death_row, sk); if (err) goto late_failure; dp->dccps_iss = secure_dccpv6_sequence_number(np->saddr.s6_addr32, sk->sk_v6_daddr.s6_addr32, inet->inet_sport, inet->inet_dport); err = dccp_connect(sk); if (err) goto late_failure; return 0; late_failure: dccp_set_state(sk, DCCP_CLOSED); __sk_dst_reset(sk); failure: inet->inet_dport = 0; sk->sk_route_caps = 0; return err; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
static int dccp_v6_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in6 *usin = (struct sockaddr_in6 *)uaddr; struct inet_connection_sock *icsk = inet_csk(sk); struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct dccp_sock *dp = dccp_sk(sk); struct in6_addr *saddr = NULL, *final_p, final; struct ipv6_txoptions *opt; struct flowi6 fl6; struct dst_entry *dst; int addr_type; int err; dp->dccps_role = DCCP_ROLE_CLIENT; if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (usin->sin6_family != AF_INET6) return -EAFNOSUPPORT; memset(&fl6, 0, sizeof(fl6)); if (np->sndflow) { fl6.flowlabel = usin->sin6_flowinfo & IPV6_FLOWINFO_MASK; IP6_ECN_flow_init(fl6.flowlabel); if (fl6.flowlabel & IPV6_FLOWLABEL_MASK) { struct ip6_flowlabel *flowlabel; flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; fl6_sock_release(flowlabel); } } /* * connect() to INADDR_ANY means loopback (BSD'ism). */ if (ipv6_addr_any(&usin->sin6_addr)) usin->sin6_addr.s6_addr[15] = 1; addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type & IPV6_ADDR_MULTICAST) return -ENETUNREACH; if (addr_type & IPV6_ADDR_LINKLOCAL) { if (addr_len >= sizeof(struct sockaddr_in6) && usin->sin6_scope_id) { /* If interface is set while binding, indices * must coincide. */ if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != usin->sin6_scope_id) return -EINVAL; sk->sk_bound_dev_if = usin->sin6_scope_id; } /* Connect to link-local address requires an interface */ if (!sk->sk_bound_dev_if) return -EINVAL; } sk->sk_v6_daddr = usin->sin6_addr; np->flow_label = fl6.flowlabel; /* * DCCP over IPv4 */ if (addr_type == IPV6_ADDR_MAPPED) { u32 exthdrlen = icsk->icsk_ext_hdr_len; struct sockaddr_in sin; SOCK_DEBUG(sk, "connect: ipv4 mapped\n"); if (__ipv6_only_sock(sk)) return -ENETUNREACH; sin.sin_family = AF_INET; sin.sin_port = usin->sin6_port; sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3]; icsk->icsk_af_ops = &dccp_ipv6_mapped; sk->sk_backlog_rcv = dccp_v4_do_rcv; err = dccp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin)); if (err) { icsk->icsk_ext_hdr_len = exthdrlen; icsk->icsk_af_ops = &dccp_ipv6_af_ops; sk->sk_backlog_rcv = dccp_v6_do_rcv; goto failure; } np->saddr = sk->sk_v6_rcv_saddr; return err; } if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr)) saddr = &sk->sk_v6_rcv_saddr; fl6.flowi6_proto = IPPROTO_DCCP; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = saddr ? *saddr : np->saddr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.fl6_dport = usin->sin6_port; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); opt = rcu_dereference_protected(np->opt, sock_owned_by_user(sk)); final_p = fl6_update_dst(&fl6, opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); goto failure; } if (saddr == NULL) { saddr = &fl6.saddr; sk->sk_v6_rcv_saddr = *saddr; } /* set the source address */ np->saddr = *saddr; inet->inet_rcv_saddr = LOOPBACK4_IPV6; __ip6_dst_store(sk, dst, NULL, NULL); icsk->icsk_ext_hdr_len = 0; if (opt) icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen; inet->inet_dport = usin->sin6_port; dccp_set_state(sk, DCCP_REQUESTING); err = inet6_hash_connect(&dccp_death_row, sk); if (err) goto late_failure; dp->dccps_iss = secure_dccpv6_sequence_number(np->saddr.s6_addr32, sk->sk_v6_daddr.s6_addr32, inet->inet_sport, inet->inet_dport); err = dccp_connect(sk); if (err) goto late_failure; return 0; late_failure: dccp_set_state(sk, DCCP_CLOSED); __sk_dst_reset(sk); failure: inet->inet_dport = 0; sk->sk_route_caps = 0; return err; }
14,373
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static void regulator_ena_gpio_free(struct regulator_dev *rdev) { struct regulator_enable_gpio *pin, *n; if (!rdev->ena_pin) return; /* Free the GPIO only in case of no use */ list_for_each_entry_safe(pin, n, &regulator_ena_gpio_list, list) { if (pin->gpiod == rdev->ena_pin->gpiod) { if (pin->request_count <= 1) { pin->request_count = 0; gpiod_put(pin->gpiod); list_del(&pin->list); kfree(pin); } else { pin->request_count--; } } } } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <[email protected]> Signed-off-by: Mark Brown <[email protected]> CWE ID: CWE-416
static void regulator_ena_gpio_free(struct regulator_dev *rdev) { struct regulator_enable_gpio *pin, *n; if (!rdev->ena_pin) return; /* Free the GPIO only in case of no use */ list_for_each_entry_safe(pin, n, &regulator_ena_gpio_list, list) { if (pin->gpiod == rdev->ena_pin->gpiod) { if (pin->request_count <= 1) { pin->request_count = 0; gpiod_put(pin->gpiod); list_del(&pin->list); kfree(pin); rdev->ena_pin = NULL; return; } else { pin->request_count--; } } } }
6,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void ScreenOrientationDispatcherHost::OnLockRequest( RenderFrameHost* render_frame_host, blink::WebScreenOrientationLockType orientation, int request_id) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } current_lock_ = new LockInformation(request_id, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); if (!provider_) { NotifyLockError(request_id, blink::WebLockOrientationErrorNotAvailable); return; } provider_->LockOrientation(request_id, orientation); } Commit Message: Cleanups in ScreenOrientationDispatcherHost. BUG=None Review URL: https://codereview.chromium.org/408213003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void ScreenOrientationDispatcherHost::OnLockRequest( RenderFrameHost* render_frame_host, blink::WebScreenOrientationLockType orientation, int request_id) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_) { NotifyLockError(request_id, blink::WebLockOrientationErrorNotAvailable); return; } current_lock_ = new LockInformation(request_id, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); provider_->LockOrientation(request_id, orientation); }
23,398
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid("incorrect prefix length"); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; } Commit Message: index: error out on unreasonable prefix-compressed path lengths When computing the complete path length from the encoded prefix-compressed path, we end up just allocating the complete path without ever checking what the encoded path length actually is. This can easily lead to a denial of service by just encoding an unreasonable long path name inside of the index. Git already enforces a maximum path length of 4096 bytes. As we also have that enforcement ready in some places, just make sure that the resulting path is smaller than GIT_PATH_MAX. Reported-by: Krishna Ram Prakash R <[email protected]> Reported-by: Vivek Parikh <[email protected]> CWE ID: CWE-190
static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid("incorrect prefix length"); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); if (path_len > GIT_PATH_MAX) return index_error_invalid("unreasonable path length"); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; }
10,067
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: unsigned long long Track::GetDefaultDuration() const { return m_info.defaultDuration; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
unsigned long long Track::GetDefaultDuration() const
2,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void SubpelVarianceTest<SubpelVarianceFunctionType>::RefTest() { for (int x = 0; x < 16; ++x) { for (int y = 0; y < 16; ++y) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { ref_[j] = rnd.Rand8(); } unsigned int sse1, sse2; unsigned int var1; REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y, src_, width_, &sse1)); const unsigned int var2 = subpel_variance_ref(ref_, src_, log2width_, log2height_, x, y, &sse2); EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y; EXPECT_EQ(var1, var2) << "at position " << x << ", " << y; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void SubpelVarianceTest<SubpelVarianceFunctionType>::RefTest() { for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { if (!use_high_bit_depth_) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd_.Rand8(); } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { ref_[j] = rnd_.Rand8(); } #if CONFIG_VP9_HIGHBITDEPTH } else { for (int j = 0; j < block_size_; j++) { CONVERT_TO_SHORTPTR(src_)[j] = rnd_.Rand16() & mask_; } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { CONVERT_TO_SHORTPTR(ref_)[j] = rnd_.Rand16() & mask_; } #endif // CONFIG_VP9_HIGHBITDEPTH } unsigned int sse1, sse2; unsigned int var1; ASM_REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y, src_, width_, &sse1)); const unsigned int var2 = subpel_variance_ref(ref_, src_, log2width_, log2height_, x, y, &sse2, use_high_bit_depth_, bit_depth_); EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y; EXPECT_EQ(var1, var2) << "at position " << x << ", " << y; } } }
11,848
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: MediaStreamDispatcherHost::~MediaStreamDispatcherHost() { DCHECK_CURRENTLY_ON(BrowserThread::IO); bindings_.CloseAllBindings(); CancelAllRequests(); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
MediaStreamDispatcherHost::~MediaStreamDispatcherHost() { DCHECK_CURRENTLY_ON(BrowserThread::IO); CancelAllRequests(); }
27,168
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: AudioParameters GetInputParametersOnDeviceThread(AudioManager* audio_manager, const std::string& device_id) { DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread()); if (!audio_manager->HasAudioInputDevices()) return AudioParameters(); return audio_manager->GetInputStreamParameters(device_id); } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID:
AudioParameters GetInputParametersOnDeviceThread(AudioManager* audio_manager, const std::string& device_id) { DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread()); // returns invalid parameters if the device is not found. if (!audio_manager->HasAudioInputDevices()) return AudioParameters(); return audio_manager->GetInputStreamParameters(device_id); }
16,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void FailStoreGroup() { PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_FailStoreGroup, base::Unretained(this))); const int64_t kTooBig = 10 * 1024 * 1024; // 10M group_ = new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kManifestUrl, AppCacheEntry(AppCacheEntry::MANIFEST, 1, kTooBig)); storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); // Expected to be async. } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void FailStoreGroup() { void FailStoreGroup_SizeTooBig() { PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_FailStoreGroup, base::Unretained(this))); // Set up some preconditions. Create a group and newest cache that const int64_t kTooBig = 10 * 1024 * 1024; // 10M group_ = new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kManifestUrl, AppCacheEntry(AppCacheEntry::MANIFEST, /*response_id=*/1, /*response_size=*/kTooBig, /*padding_size=*/0)); // Hold a ref to the cache to simulate the UpdateJob holding that ref, // and hold a ref to the group to simulate the CacheHost holding that ref. // Conduct the store test. storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); // Expected to be async. } void FailStoreGroup_PaddingTooBig() { // Store a group and its newest cache. Should complete asynchronously. PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_FailStoreGroup, base::Unretained(this))); // Set up some preconditions. Create a group and newest cache that // appear to be "unstored" and big enough to exceed the 5M limit. const int64_t kTooBig = 10 * 1024 * 1024; // 10M group_ = new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT, /*response_id=*/1, /*response_size=*/1, /*padding_size=*/kTooBig)); // Hold a ref to the cache to simulate the UpdateJob holding that ref, storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); // Expected to be async. }
6,482
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ", tok2str(chdlc_cast_values, "0x%02x", p[0]), tok2str(ethertype_values, "Unknown", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1); else isoclns_print(ndo, p, length, ndo->ndo_snapend - p); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, "[|chdlc]")); return ndo->ndo_snapend - bp; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ", tok2str(chdlc_cast_values, "0x%02x", p[0]), tok2str(ethertype_values, "Unknown", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1); else isoclns_print(ndo, p, length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, "[|chdlc]")); return ndo->ndo_snapend - bp; }
2,230
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { char path[PATH_MAX]; struct passwd *pwd; { char path[PATH_MAX]; struct passwd *pwd; FILE *fp; int i, save_errno; uid_t fsuid; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); save_errno = errno; setfsuid(fsuid); if (fp != NULL) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } } Commit Message: CWE ID: CWE-399
check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { char path[PATH_MAX]; struct passwd *pwd; { char path[PATH_MAX]; struct passwd *pwd; FILE *fp = NULL; int i, fd = -1, save_errno; uid_t fsuid; struct stat st; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); if (!stat(path, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; else fd = open(path, O_RDONLY | O_NOCTTY); } save_errno = errno; setfsuid(fsuid); if (fd >= 0) { if (!fstat(fd, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; else fp = fdopen(fd, "r"); } if (!fp) { save_errno = errno; close(fd); } } if (fp) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } }
22,072
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; }
15,553
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */
2,739
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: omx_vdec::omx_vdec(): m_error_propogated(false), m_state(OMX_StateInvalid), m_app_data(NULL), m_inp_mem_ptr(NULL), m_out_mem_ptr(NULL), input_flush_progress (false), output_flush_progress (false), input_use_buffer (false), output_use_buffer (false), ouput_egl_buffers(false), m_use_output_pmem(OMX_FALSE), m_out_mem_region_smi(OMX_FALSE), m_out_pvt_entry_pmem(OMX_FALSE), pending_input_buffers(0), pending_output_buffers(0), m_out_bm_count(0), m_inp_bm_count(0), m_inp_bPopulated(OMX_FALSE), m_out_bPopulated(OMX_FALSE), m_flags(0), #ifdef _ANDROID_ m_heap_ptr(NULL), #endif m_inp_bEnabled(OMX_TRUE), m_out_bEnabled(OMX_TRUE), m_in_alloc_cnt(0), m_platform_list(NULL), m_platform_entry(NULL), m_pmem_info(NULL), h264_parser(NULL), arbitrary_bytes (true), psource_frame (NULL), pdest_frame (NULL), m_inp_heap_ptr (NULL), m_phdr_pmem_ptr(NULL), m_heap_inp_bm_count (0), codec_type_parse ((codec_type)0), first_frame_meta (true), frame_count (0), nal_count (0), nal_length(0), look_ahead_nal (false), first_frame(0), first_buffer(NULL), first_frame_size (0), m_device_file_ptr(NULL), m_vc1_profile((vc1_profile_type)0), h264_last_au_ts(LLONG_MAX), h264_last_au_flags(0), m_disp_hor_size(0), m_disp_vert_size(0), prev_ts(LLONG_MAX), rst_prev_ts(true), frm_int(0), in_reconfig(false), m_display_id(NULL), client_extradata(0), m_reject_avc_1080p_mp (0), #ifdef _ANDROID_ m_enable_android_native_buffers(OMX_FALSE), m_use_android_native_buffers(OMX_FALSE), iDivXDrmDecrypt(NULL), #endif m_desc_buffer_ptr(NULL), secure_mode(false), m_other_extradata(NULL), m_profile(0), client_set_fps(false), m_last_rendered_TS(-1), m_queued_codec_config_count(0), secure_scaling_to_non_secure_opb(false) { /* Assumption is that , to begin with , we have all the frames with decoder */ DEBUG_PRINT_HIGH("In %u bit OMX vdec Constructor", (unsigned int)sizeof(long) * 8); memset(&m_debug,0,sizeof(m_debug)); #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; property_get("vidc.debug.level", property_value, "1"); debug_level = atoi(property_value); property_value[0] = '\0'; DEBUG_PRINT_HIGH("In OMX vdec Constructor"); property_get("vidc.dec.debug.perf", property_value, "0"); perf_flag = atoi(property_value); if (perf_flag) { DEBUG_PRINT_HIGH("vidc.dec.debug.perf is %d", perf_flag); dec_time.start(); proc_frms = latency = 0; } prev_n_filled_len = 0; property_value[0] = '\0'; property_get("vidc.dec.debug.ts", property_value, "0"); m_debug_timestamp = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.ts value is %d",m_debug_timestamp); if (m_debug_timestamp) { time_stamp_dts.set_timestamp_reorder_mode(true); time_stamp_dts.enable_debug_print(true); } property_value[0] = '\0'; property_get("vidc.dec.debug.concealedmb", property_value, "0"); m_debug_concealedmb = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.concealedmb value is %d",m_debug_concealedmb); property_value[0] = '\0'; property_get("vidc.dec.profile.check", property_value, "0"); m_reject_avc_1080p_mp = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.profile.check value is %d",m_reject_avc_1080p_mp); property_value[0] = '\0'; property_get("vidc.dec.log.in", property_value, "0"); m_debug.in_buffer_log = atoi(property_value); property_value[0] = '\0'; property_get("vidc.dec.log.out", property_value, "0"); m_debug.out_buffer_log = atoi(property_value); sprintf(m_debug.log_loc, "%s", BUFFER_LOG_LOC); property_value[0] = '\0'; property_get("vidc.log.loc", property_value, ""); if (*property_value) strlcpy(m_debug.log_loc, property_value, PROPERTY_VALUE_MAX); property_value[0] = '\0'; property_get("vidc.dec.120fps.enabled", property_value, "0"); if(atoi(property_value)) { DEBUG_PRINT_LOW("feature 120 FPS decode enabled"); m_last_rendered_TS = 0; } property_value[0] = '\0'; property_get("vidc.dec.debug.dyn.disabled", property_value, "0"); m_disable_dynamic_buf_mode = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.dyn.disabled value is %d",m_disable_dynamic_buf_mode); #endif memset(&m_cmp,0,sizeof(m_cmp)); memset(&m_cb,0,sizeof(m_cb)); memset (&drv_ctx,0,sizeof(drv_ctx)); memset (&h264_scratch,0,sizeof (OMX_BUFFERHEADERTYPE)); memset (m_hwdevice_name,0,sizeof(m_hwdevice_name)); memset(m_demux_offsets, 0, ( sizeof(OMX_U32) * 8192) ); memset(&m_custom_buffersize, 0, sizeof(m_custom_buffersize)); m_demux_entries = 0; msg_thread_id = 0; async_thread_id = 0; msg_thread_created = false; async_thread_created = false; #ifdef _ANDROID_ICS_ memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS)); #endif memset(&drv_ctx.extradata_info, 0, sizeof(drv_ctx.extradata_info)); /* invalidate m_frame_pack_arrangement */ memset(&m_frame_pack_arrangement, 0, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); m_frame_pack_arrangement.cancel_flag = 1; drv_ctx.timestamp_adjust = false; drv_ctx.video_driver_fd = -1; m_vendor_config.pData = NULL; pthread_mutex_init(&m_lock, NULL); pthread_mutex_init(&c_lock, NULL); sem_init(&m_cmd_lock,0,0); sem_init(&m_safe_flush, 0, 0); streaming[CAPTURE_PORT] = streaming[OUTPUT_PORT] = false; #ifdef _ANDROID_ char extradata_value[PROPERTY_VALUE_MAX] = {0}; property_get("vidc.dec.debug.extradata", extradata_value, "0"); m_debug_extradata = atoi(extradata_value); DEBUG_PRINT_HIGH("vidc.dec.debug.extradata value is %d",m_debug_extradata); #endif m_fill_output_msg = OMX_COMPONENT_GENERATE_FTB; client_buffers.set_vdec_client(this); dynamic_buf_mode = false; out_dynamic_list = NULL; is_down_scalar_enabled = false; m_smoothstreaming_mode = false; m_smoothstreaming_width = 0; m_smoothstreaming_height = 0; is_q6_platform = false; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e CWE ID:
omx_vdec::omx_vdec(): m_error_propogated(false), m_state(OMX_StateInvalid), m_app_data(NULL), m_inp_mem_ptr(NULL), m_out_mem_ptr(NULL), input_flush_progress (false), output_flush_progress (false), input_use_buffer (false), output_use_buffer (false), ouput_egl_buffers(false), m_use_output_pmem(OMX_FALSE), m_out_mem_region_smi(OMX_FALSE), m_out_pvt_entry_pmem(OMX_FALSE), pending_input_buffers(0), pending_output_buffers(0), m_out_bm_count(0), m_inp_bm_count(0), m_inp_bPopulated(OMX_FALSE), m_out_bPopulated(OMX_FALSE), m_flags(0), #ifdef _ANDROID_ m_heap_ptr(NULL), #endif m_inp_bEnabled(OMX_TRUE), m_out_bEnabled(OMX_TRUE), m_in_alloc_cnt(0), m_platform_list(NULL), m_platform_entry(NULL), m_pmem_info(NULL), h264_parser(NULL), arbitrary_bytes (true), psource_frame (NULL), pdest_frame (NULL), m_inp_heap_ptr (NULL), m_phdr_pmem_ptr(NULL), m_heap_inp_bm_count (0), codec_type_parse ((codec_type)0), first_frame_meta (true), frame_count (0), nal_count (0), nal_length(0), look_ahead_nal (false), first_frame(0), first_buffer(NULL), first_frame_size (0), m_device_file_ptr(NULL), m_vc1_profile((vc1_profile_type)0), h264_last_au_ts(LLONG_MAX), h264_last_au_flags(0), m_disp_hor_size(0), m_disp_vert_size(0), prev_ts(LLONG_MAX), rst_prev_ts(true), frm_int(0), in_reconfig(false), m_display_id(NULL), client_extradata(0), m_reject_avc_1080p_mp (0), #ifdef _ANDROID_ m_enable_android_native_buffers(OMX_FALSE), m_use_android_native_buffers(OMX_FALSE), iDivXDrmDecrypt(NULL), #endif m_desc_buffer_ptr(NULL), secure_mode(false), m_other_extradata(NULL), m_profile(0), client_set_fps(false), m_last_rendered_TS(-1), m_queued_codec_config_count(0), secure_scaling_to_non_secure_opb(false) { /* Assumption is that , to begin with , we have all the frames with decoder */ DEBUG_PRINT_HIGH("In %u bit OMX vdec Constructor", (unsigned int)sizeof(long) * 8); memset(&m_debug,0,sizeof(m_debug)); #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; property_get("vidc.debug.level", property_value, "1"); debug_level = atoi(property_value); property_value[0] = '\0'; DEBUG_PRINT_HIGH("In OMX vdec Constructor"); property_get("vidc.dec.debug.perf", property_value, "0"); perf_flag = atoi(property_value); if (perf_flag) { DEBUG_PRINT_HIGH("vidc.dec.debug.perf is %d", perf_flag); dec_time.start(); proc_frms = latency = 0; } prev_n_filled_len = 0; property_value[0] = '\0'; property_get("vidc.dec.debug.ts", property_value, "0"); m_debug_timestamp = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.ts value is %d",m_debug_timestamp); if (m_debug_timestamp) { time_stamp_dts.set_timestamp_reorder_mode(true); time_stamp_dts.enable_debug_print(true); } property_value[0] = '\0'; property_get("vidc.dec.debug.concealedmb", property_value, "0"); m_debug_concealedmb = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.concealedmb value is %d",m_debug_concealedmb); property_value[0] = '\0'; property_get("vidc.dec.profile.check", property_value, "0"); m_reject_avc_1080p_mp = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.profile.check value is %d",m_reject_avc_1080p_mp); property_value[0] = '\0'; property_get("vidc.dec.log.in", property_value, "0"); m_debug.in_buffer_log = atoi(property_value); property_value[0] = '\0'; property_get("vidc.dec.log.out", property_value, "0"); m_debug.out_buffer_log = atoi(property_value); sprintf(m_debug.log_loc, "%s", BUFFER_LOG_LOC); property_value[0] = '\0'; property_get("vidc.log.loc", property_value, ""); if (*property_value) strlcpy(m_debug.log_loc, property_value, PROPERTY_VALUE_MAX); property_value[0] = '\0'; property_get("vidc.dec.120fps.enabled", property_value, "0"); if(atoi(property_value)) { DEBUG_PRINT_LOW("feature 120 FPS decode enabled"); m_last_rendered_TS = 0; } property_value[0] = '\0'; property_get("vidc.dec.debug.dyn.disabled", property_value, "0"); m_disable_dynamic_buf_mode = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.dyn.disabled value is %d",m_disable_dynamic_buf_mode); #endif memset(&m_cmp,0,sizeof(m_cmp)); memset(&m_cb,0,sizeof(m_cb)); memset (&drv_ctx,0,sizeof(drv_ctx)); memset (&h264_scratch,0,sizeof (OMX_BUFFERHEADERTYPE)); memset (m_hwdevice_name,0,sizeof(m_hwdevice_name)); memset(m_demux_offsets, 0, ( sizeof(OMX_U32) * 8192) ); memset(&m_custom_buffersize, 0, sizeof(m_custom_buffersize)); m_demux_entries = 0; msg_thread_id = 0; async_thread_id = 0; msg_thread_created = false; async_thread_created = false; #ifdef _ANDROID_ICS_ memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS)); #endif memset(&drv_ctx.extradata_info, 0, sizeof(drv_ctx.extradata_info)); /* invalidate m_frame_pack_arrangement */ memset(&m_frame_pack_arrangement, 0, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); m_frame_pack_arrangement.cancel_flag = 1; drv_ctx.timestamp_adjust = false; drv_ctx.video_driver_fd = -1; m_vendor_config.pData = NULL; pthread_mutex_init(&m_lock, NULL); pthread_mutex_init(&c_lock, NULL); pthread_mutex_init(&buf_lock, NULL); sem_init(&m_cmd_lock,0,0); sem_init(&m_safe_flush, 0, 0); streaming[CAPTURE_PORT] = streaming[OUTPUT_PORT] = false; #ifdef _ANDROID_ char extradata_value[PROPERTY_VALUE_MAX] = {0}; property_get("vidc.dec.debug.extradata", extradata_value, "0"); m_debug_extradata = atoi(extradata_value); DEBUG_PRINT_HIGH("vidc.dec.debug.extradata value is %d",m_debug_extradata); #endif m_fill_output_msg = OMX_COMPONENT_GENERATE_FTB; client_buffers.set_vdec_client(this); dynamic_buf_mode = false; out_dynamic_list = NULL; is_down_scalar_enabled = false; m_smoothstreaming_mode = false; m_smoothstreaming_width = 0; m_smoothstreaming_height = 0; is_q6_platform = false; }
1,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void RunExtremalCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); int max_error = 0; int total_error = 0; const int count_test_block = 100000; DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) { src[j] = rnd.Rand8() % 2 ? 255 : 0; dst[j] = src[j] > 0 ? 0 : 255; test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_temp_block, pitch_)); REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < 64; ++j) { const int diff = dst[j] - src[j]; const int error = diff * diff; if (max_error < error) max_error = error; total_error += error; } EXPECT_GE(1, max_error) << "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has" << "an individual roundtrip error > 1"; EXPECT_GE(count_test_block/5, total_error) << "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has average" << " roundtrip error > 1/5 per block"; } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunExtremalCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); int max_error = 0; int total_error = 0; int total_coeff_error = 0; const int count_test_block = 100000; DECLARE_ALIGNED(16, int16_t, test_input_block[64]); DECLARE_ALIGNED(16, tran_low_t, test_temp_block[64]); DECLARE_ALIGNED(16, tran_low_t, ref_temp_block[64]); DECLARE_ALIGNED(16, uint8_t, dst[64]); DECLARE_ALIGNED(16, uint8_t, src[64]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[64]); DECLARE_ALIGNED(16, uint16_t, src16[64]); #endif for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < 64; ++j) { if (bit_depth_ == VPX_BITS_8) { if (i == 0) { src[j] = 255; dst[j] = 0; } else if (i == 1) { src[j] = 0; dst[j] = 255; } else { src[j] = rnd.Rand8() % 2 ? 255 : 0; dst[j] = rnd.Rand8() % 2 ? 255 : 0; } test_input_block[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { if (i == 0) { src16[j] = mask_; dst16[j] = 0; } else if (i == 1) { src16[j] = 0; dst16[j] = mask_; } else { src16[j] = rnd.Rand8() % 2 ? mask_ : 0; dst16[j] = rnd.Rand8() % 2 ? mask_ : 0; } test_input_block[j] = src16[j] - dst16[j]; #endif } } ASM_REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_temp_block, pitch_)); ASM_REGISTER_STATE_CHECK( fwd_txfm_ref(test_input_block, ref_temp_block, pitch_, tx_type_)); if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, dst, pitch_)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_)); #endif } for (int j = 0; j < 64; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const int diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else const int diff = dst[j] - src[j]; #endif const int error = diff * diff; if (max_error < error) max_error = error; total_error += error; const int coeff_diff = test_temp_block[j] - ref_temp_block[j]; total_coeff_error += abs(coeff_diff); } EXPECT_GE(1 << 2 * (bit_depth_ - 8), max_error) << "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has" << "an individual roundtrip error > 1"; EXPECT_GE((count_test_block << 2 * (bit_depth_ - 8))/5, total_error) << "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has average" << " roundtrip error > 1/5 per block"; EXPECT_EQ(0, total_coeff_error) << "Error: Extremal 8x8 FDCT/FHT has" << "overflow issues in the intermediate steps > 1"; } }
7,447
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: QString IRCView::openTags(TextHtmlData* data, int from) { QString ret, tag; int i = from; for ( ; i < data->openHtmlTags.count(); ++i) { tag = data->openHtmlTags.at(i); if (data->reverse) { ret += fontColorOpenTag(Preferences::self()->color(Preferences::TextViewBackground).name()); } else { ret += fontColorOpenTag(data->lastFgColor); } } else if (tag == QLatin1String("span")) { if (data->reverse) { ret += spanColorOpenTag(data->defaultColor); } else { ret += spanColorOpenTag(data->lastBgColor); } } else { ret += QLatin1Char('<') + tag + QLatin1Char('>'); } } Commit Message: CWE ID:
QString IRCView::openTags(TextHtmlData* data, int from) { QString ret, tag; int i = from > -1 ? from : 0; for ( ; i < data->openHtmlTags.count(); ++i) { tag = data->openHtmlTags.at(i); if (data->reverse) { ret += fontColorOpenTag(Preferences::self()->color(Preferences::TextViewBackground).name()); } else { ret += fontColorOpenTag(data->lastFgColor); } } else if (tag == QLatin1String("span")) { if (data->reverse) { ret += spanColorOpenTag(data->defaultColor); } else { ret += spanColorOpenTag(data->lastBgColor); } } else { ret += QLatin1Char('<') + tag + QLatin1Char('>'); } }
12,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void OneClickSigninSyncStarter::UntrustedSigninConfirmed( StartSyncMode response) { if (response == UNDO_SYNC) { CancelSigninAndDelete(); } else { if (response == CONFIGURE_SYNC_FIRST) start_mode_ = response; SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); signin->CompletePendingSignin(); } } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void OneClickSigninSyncStarter::UntrustedSigninConfirmed( StartSyncMode response) { if (response == UNDO_SYNC) { CancelSigninAndDelete(); // If this was not an interstitial signin, (i.e. it was a SAML signin) // then the browser page is now blank and should redirect to the NTP. if (source_ != SyncPromoUI::SOURCE_UNKNOWN) { EnsureBrowser(); chrome::NavigateParams params(browser_, GURL(chrome::kChromeUINewTabURL), content::PAGE_TRANSITION_AUTO_TOPLEVEL); params.disposition = CURRENT_TAB; params.window_action = chrome::NavigateParams::SHOW_WINDOW; chrome::Navigate(&params); } } else { if (response == CONFIGURE_SYNC_FIRST) start_mode_ = response; SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); signin->CompletePendingSignin(); } }
25,737
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: v8::Handle<v8::Value> V8DirectoryEntry::getDirectoryCallback(const v8::Arguments& args) { INC_STATS("DOM.DirectoryEntry.getDirectory"); DirectoryEntry* imp = V8DirectoryEntry::toNative(args.Holder()); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, path, args[0]); if (args.Length() <= 1) { imp->getDirectory(path); return v8::Handle<v8::Value>(); } RefPtr<WebKitFlags> flags; if (!isUndefinedOrNull(args[1]) && args[1]->IsObject()) { EXCEPTION_BLOCK(v8::Handle<v8::Object>, object, v8::Handle<v8::Object>::Cast(args[1])); flags = WebKitFlags::create(); v8::Local<v8::Value> v8Create = object->Get(v8::String::New("create")); if (!v8Create.IsEmpty() && !isUndefinedOrNull(v8Create)) { EXCEPTION_BLOCK(bool, isCreate, v8Create->BooleanValue()); flags->setCreate(isCreate); } v8::Local<v8::Value> v8Exclusive = object->Get(v8::String::New("exclusive")); if (!v8Exclusive.IsEmpty() && !isUndefinedOrNull(v8Exclusive)) { EXCEPTION_BLOCK(bool, isExclusive, v8Exclusive->BooleanValue()); flags->setExclusive(isExclusive); } } RefPtr<EntryCallback> successCallback; if (args.Length() > 2 && !args[2]->IsNull() && !args[2]->IsUndefined()) { if (!args[2]->IsObject()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); successCallback = V8EntryCallback::create(args[2], getScriptExecutionContext()); } RefPtr<ErrorCallback> errorCallback; if (args.Length() > 3 && !args[3]->IsNull() && !args[3]->IsUndefined()) { if (!args[3]->IsObject()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); errorCallback = V8ErrorCallback::create(args[3], getScriptExecutionContext()); } imp->getDirectory(path, flags, successCallback, errorCallback); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
v8::Handle<v8::Value> V8DirectoryEntry::getDirectoryCallback(const v8::Arguments& args) { INC_STATS("DOM.DirectoryEntry.getDirectory"); DirectoryEntry* imp = V8DirectoryEntry::toNative(args.Holder()); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, path, args[0]); if (args.Length() <= 1) { imp->getDirectory(path); return v8::Handle<v8::Value>(); } RefPtr<WebKitFlags> flags; if (!isUndefinedOrNull(args[1]) && args[1]->IsObject()) { EXCEPTION_BLOCK(v8::Handle<v8::Object>, object, v8::Handle<v8::Object>::Cast(args[1])); flags = WebKitFlags::create(); v8::Local<v8::Value> v8Create = object->Get(v8::String::New("create")); if (!v8Create.IsEmpty() && !isUndefinedOrNull(v8Create)) { EXCEPTION_BLOCK(bool, isCreate, v8Create->BooleanValue()); flags->setCreate(isCreate); } v8::Local<v8::Value> v8Exclusive = object->Get(v8::String::New("exclusive")); if (!v8Exclusive.IsEmpty() && !isUndefinedOrNull(v8Exclusive)) { EXCEPTION_BLOCK(bool, isExclusive, v8Exclusive->BooleanValue()); flags->setExclusive(isExclusive); } } RefPtr<EntryCallback> successCallback; if (args.Length() > 2 && !args[2]->IsNull() && !args[2]->IsUndefined()) { if (!args[2]->IsObject()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); successCallback = V8EntryCallback::create(args[2], getScriptExecutionContext()); } RefPtr<ErrorCallback> errorCallback; if (args.Length() > 3 && !args[3]->IsNull() && !args[3]->IsUndefined()) { if (!args[3]->IsObject()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); errorCallback = V8ErrorCallback::create(args[3], getScriptExecutionContext()); } imp->getDirectory(path, flags, successCallback, errorCallback); return v8::Handle<v8::Value>(); }
16,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void MediaStreamDispatcherHost::StopStreamDevice(const std::string& device_id, int32_t session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); media_stream_manager_->StopStreamDevice(render_process_id_, render_frame_id_, device_id, session_id); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void MediaStreamDispatcherHost::StopStreamDevice(const std::string& device_id, int32_t session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); media_stream_manager_->StopStreamDevice(render_process_id_, render_frame_id_, requester_id_, device_id, session_id); }
24,964
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len, RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value, const RBinDwarfCompUnitHdr *hdr, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf; const ut8 *buf_end = obuf + obuf_len; size_t j; if (!spec || !value || !hdr || !obuf || obuf_len < 0) { return NULL; } value->form = spec->attr_form; value->name = spec->attr_name; value->encoding.block.data = NULL; value->encoding.str_struct.string = NULL; value->encoding.str_struct.offset = 0; switch (spec->attr_form) { case DW_FORM_addr: switch (hdr->pointer_size) { case 1: value->encoding.address = READ (buf, ut8); break; case 2: value->encoding.address = READ (buf, ut16); break; case 4: value->encoding.address = READ (buf, ut32); break; case 8: value->encoding.address = READ (buf, ut64); break; default: eprintf("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size); return NULL; } break; case DW_FORM_block2: value->encoding.block.length = READ (buf, ut16); if (value->encoding.block.length > 0) { value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_block4: value->encoding.block.length = READ (buf, ut32); if (value->encoding.block.length > 0) { ut8 *data = calloc (sizeof (ut8), value->encoding.block.length); if (data) { for (j = 0; j < value->encoding.block.length; j++) { data[j] = READ (buf, ut8); } } value->encoding.block.data = data; } break; //// This causes segfaults to happen case DW_FORM_data2: value->encoding.data = READ (buf, ut16); break; case DW_FORM_data4: value->encoding.data = READ (buf, ut32); break; case DW_FORM_data8: value->encoding.data = READ (buf, ut64); break; case DW_FORM_string: value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL; buf += (strlen ((const char*)buf) + 1); break; case DW_FORM_block: buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length); if (!buf) { return NULL; } value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } break; case DW_FORM_block1: value->encoding.block.length = READ (buf, ut8); value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } break; case DW_FORM_flag: value->encoding.flag = READ (buf, ut8); break; case DW_FORM_sdata: buf = r_leb128 (buf, &value->encoding.sdata); break; case DW_FORM_strp: value->encoding.str_struct.offset = READ (buf, ut32); if (debug_str && value->encoding.str_struct.offset < debug_str_len) { value->encoding.str_struct.string = strdup ( (const char *)(debug_str + value->encoding.str_struct.offset)); } else { value->encoding.str_struct.string = NULL; } break; case DW_FORM_udata: { ut64 ndata = 0; const ut8 *data = (const ut8*)&ndata; buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata); memcpy (&value->encoding.data, data, sizeof (value->encoding.data)); value->encoding.str_struct.string = NULL; } break; case DW_FORM_ref_addr: value->encoding.reference = READ (buf, ut64); // addr size of machine break; case DW_FORM_ref1: value->encoding.reference = READ (buf, ut8); break; case DW_FORM_ref2: value->encoding.reference = READ (buf, ut16); break; case DW_FORM_ref4: value->encoding.reference = READ (buf, ut32); break; case DW_FORM_ref8: value->encoding.reference = READ (buf, ut64); break; case DW_FORM_data1: value->encoding.data = READ (buf, ut8); break; default: eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form); value->encoding.data = 0; return NULL; } return buf; } Commit Message: Fix #8813 - segfault in dwarf parser CWE ID: CWE-125
static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len, RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value, const RBinDwarfCompUnitHdr *hdr, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf; const ut8 *buf_end = obuf + obuf_len; size_t j; if (!spec || !value || !hdr || !obuf || obuf_len < 1) { return NULL; } value->form = spec->attr_form; value->name = spec->attr_name; value->encoding.block.data = NULL; value->encoding.str_struct.string = NULL; value->encoding.str_struct.offset = 0; switch (spec->attr_form) { case DW_FORM_addr: switch (hdr->pointer_size) { case 1: value->encoding.address = READ (buf, ut8); break; case 2: value->encoding.address = READ (buf, ut16); break; case 4: value->encoding.address = READ (buf, ut32); break; case 8: value->encoding.address = READ (buf, ut64); break; default: eprintf ("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size); return NULL; } break; case DW_FORM_block2: value->encoding.block.length = READ (buf, ut16); if (value->encoding.block.length > 0) { value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_block4: value->encoding.block.length = READ (buf, ut32); if (value->encoding.block.length > 0) { ut8 *data = calloc (sizeof (ut8), value->encoding.block.length); if (data) { for (j = 0; j < value->encoding.block.length; j++) { data[j] = READ (buf, ut8); } } value->encoding.block.data = data; } break; #if 0 //// This causes segfaults to happen case DW_FORM_data2: value->encoding.data = READ (buf, ut16); break; case DW_FORM_data4: value->encoding.data = READ (buf, ut32); break; case DW_FORM_data8: value->encoding.data = READ (buf, ut64); break; #endif case DW_FORM_string: value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL; buf += (strlen ((const char*)buf) + 1); break; case DW_FORM_block: buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length); if (!buf) { return NULL; } value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length); if (value->encoding.block.data) { for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_block1: value->encoding.block.length = READ (buf, ut8); value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1); if (value->encoding.block.data) { for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_flag: value->encoding.flag = READ (buf, ut8); break; case DW_FORM_sdata: buf = r_leb128 (buf, &value->encoding.sdata); break; case DW_FORM_strp: value->encoding.str_struct.offset = READ (buf, ut32); if (debug_str && value->encoding.str_struct.offset < debug_str_len) { value->encoding.str_struct.string = strdup ( (const char *)(debug_str + value->encoding.str_struct.offset)); } else { value->encoding.str_struct.string = NULL; } break; case DW_FORM_udata: { ut64 ndata = 0; const ut8 *data = (const ut8*)&ndata; buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata); memcpy (&value->encoding.data, data, sizeof (value->encoding.data)); value->encoding.str_struct.string = NULL; } break; case DW_FORM_ref_addr: value->encoding.reference = READ (buf, ut64); // addr size of machine break; case DW_FORM_ref1: value->encoding.reference = READ (buf, ut8); break; case DW_FORM_ref2: value->encoding.reference = READ (buf, ut16); break; case DW_FORM_ref4: value->encoding.reference = READ (buf, ut32); break; case DW_FORM_ref8: value->encoding.reference = READ (buf, ut64); break; case DW_FORM_data1: value->encoding.data = READ (buf, ut8); break; default: eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form); value->encoding.data = 0; return NULL; } return buf; }
3,940
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: cJSON *cJSON_CreateArray( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_Array; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_CreateArray( void )
28,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void BrowserTabStripController::TabDetachedAt(TabContents* contents, int model_index) { hover_tab_selector_.CancelTabTransition(); tabstrip_->RemoveTabAt(model_index); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserTabStripController::TabDetachedAt(TabContents* contents, void BrowserTabStripController::TabDetachedAt(WebContents* contents, int model_index) { hover_tab_selector_.CancelTabTransition(); tabstrip_->RemoveTabAt(model_index); }
28,040
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count, int preview_request_id) { VLOG(1) << "Print preview request finished with " << expected_pages_count << " pages"; if (!initial_preview_start_time_.is_null()) { UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime", base::TimeTicks::Now() - initial_preview_start_time_); UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial", expected_pages_count); initial_preview_start_time_ = base::TimeTicks(); } base::StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier, ui_preview_request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count, int preview_request_id) { VLOG(1) << "Print preview request finished with " << expected_pages_count << " pages"; if (!initial_preview_start_time_.is_null()) { UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime", base::TimeTicks::Now() - initial_preview_start_time_); UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial", expected_pages_count); initial_preview_start_time_ = base::TimeTicks(); } base::FundamentalValue ui_identifier(id_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier, ui_preview_request_id); }
15,941
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: XGetFeedbackControl( register Display *dpy, XDevice *dev, int *num_feedbacks) { XFeedbackState *Feedback = NULL; XFeedbackState *Sav = NULL; xFeedbackState *f = NULL; xFeedbackState *sav = NULL; xGetFeedbackControlReq *req; xGetFeedbackControlReply rep; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(GetFeedbackControl, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetFeedbackControl; req->deviceid = dev->device_id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) goto out; if (rep.length > 0) { unsigned long nbytes; size_t size = 0; int i; *num_feedbacks = rep.num_feedbacks; if (rep.length < (INT_MAX >> 2)) { nbytes = rep.length << 2; f = Xmalloc(nbytes); } if (!f) { _XEatDataWords(dpy, rep.length); goto out; goto out; } sav = f; _XRead(dpy, (char *)f, nbytes); for (i = 0; i < *num_feedbacks; i++) { if (f->length > nbytes) goto out; nbytes -= f->length; break; case PtrFeedbackClass: size += sizeof(XPtrFeedbackState); break; case IntegerFeedbackClass: size += sizeof(XIntegerFeedbackState); break; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; size += sizeof(XStringFeedbackState) + (strf->num_syms_supported * sizeof(KeySym)); } size += sizeof(XBellFeedbackState); break; default: size += f->length; break; } if (size > INT_MAX) goto out; f = (xFeedbackState *) ((char *)f + f->length); } Feedback = Xmalloc(size); if (!Feedback) goto out; Sav = Feedback; f = sav; for (i = 0; i < *num_feedbacks; i++) { switch (f->class) { case KbdFeedbackClass: { xKbdFeedbackState *k; XKbdFeedbackState *K; k = (xKbdFeedbackState *) f; K = (XKbdFeedbackState *) Feedback; K->class = k->class; K->length = sizeof(XKbdFeedbackState); K->id = k->id; K->click = k->click; K->percent = k->percent; K->pitch = k->pitch; K->duration = k->duration; K->led_mask = k->led_mask; K->global_auto_repeat = k->global_auto_repeat; memcpy((char *)&K->auto_repeats[0], (char *)&k->auto_repeats[0], 32); break; } case PtrFeedbackClass: { xPtrFeedbackState *p; XPtrFeedbackState *P; p = (xPtrFeedbackState *) f; P = (XPtrFeedbackState *) Feedback; P->class = p->class; P->length = sizeof(XPtrFeedbackState); P->id = p->id; P->accelNum = p->accelNum; P->accelDenom = p->accelDenom; P->threshold = p->threshold; break; } case IntegerFeedbackClass: { xIntegerFeedbackState *ifs; XIntegerFeedbackState *I; ifs = (xIntegerFeedbackState *) f; I = (XIntegerFeedbackState *) Feedback; I->class = ifs->class; I->length = sizeof(XIntegerFeedbackState); I->id = ifs->id; I->resolution = ifs->resolution; I->minVal = ifs->min_value; I->maxVal = ifs->max_value; break; } case StringFeedbackClass: { xStringFeedbackState *s; XStringFeedbackState *S; s = (xStringFeedbackState *) f; S = (XStringFeedbackState *) Feedback; S->class = s->class; S->length = sizeof(XStringFeedbackState) + (s->num_syms_supported * sizeof(KeySym)); S->id = s->id; S->max_symbols = s->max_symbols; S->num_syms_supported = s->num_syms_supported; S->syms_supported = (KeySym *) (S + 1); memcpy((char *)S->syms_supported, (char *)(s + 1), (S->num_syms_supported * sizeof(KeySym))); break; } case LedFeedbackClass: { xLedFeedbackState *l; XLedFeedbackState *L; l = (xLedFeedbackState *) f; L = (XLedFeedbackState *) Feedback; L->class = l->class; L->length = sizeof(XLedFeedbackState); L->id = l->id; L->led_values = l->led_values; L->led_mask = l->led_mask; break; } case BellFeedbackClass: { xBellFeedbackState *b; XBellFeedbackState *B; b = (xBellFeedbackState *) f; B = (XBellFeedbackState *) Feedback; B->class = b->class; B->length = sizeof(XBellFeedbackState); B->id = b->id; B->percent = b->percent; B->pitch = b->pitch; B->duration = b->duration; break; } default: break; } f = (xFeedbackState *) ((char *)f + f->length); Feedback = (XFeedbackState *) ((char *)Feedback + Feedback->length); } } out: XFree((char *)sav); UnlockDisplay(dpy); SyncHandle(); return (Sav); } Commit Message: CWE ID: CWE-284
XGetFeedbackControl( register Display *dpy, XDevice *dev, int *num_feedbacks) { XFeedbackState *Feedback = NULL; XFeedbackState *Sav = NULL; xFeedbackState *f = NULL; xFeedbackState *sav = NULL; char *end = NULL; xGetFeedbackControlReq *req; xGetFeedbackControlReply rep; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(GetFeedbackControl, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetFeedbackControl; req->deviceid = dev->device_id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) goto out; if (rep.length > 0) { unsigned long nbytes; size_t size = 0; int i; *num_feedbacks = rep.num_feedbacks; if (rep.length < (INT_MAX >> 2)) { nbytes = rep.length << 2; f = Xmalloc(nbytes); } if (!f) { _XEatDataWords(dpy, rep.length); goto out; goto out; } sav = f; end = (char *)f + nbytes; _XRead(dpy, (char *)f, nbytes); for (i = 0; i < *num_feedbacks; i++) { if ((char *)f + sizeof(*f) > end || f->length == 0 || f->length > nbytes) goto out; nbytes -= f->length; break; case PtrFeedbackClass: size += sizeof(XPtrFeedbackState); break; case IntegerFeedbackClass: size += sizeof(XIntegerFeedbackState); break; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; if ((char *)f + sizeof(*strf) > end) goto out; size += sizeof(XStringFeedbackState) + (strf->num_syms_supported * sizeof(KeySym)); } size += sizeof(XBellFeedbackState); break; default: size += f->length; break; } if (size > INT_MAX) goto out; f = (xFeedbackState *) ((char *)f + f->length); } Feedback = Xmalloc(size); if (!Feedback) goto out; Sav = Feedback; f = sav; for (i = 0; i < *num_feedbacks; i++) { switch (f->class) { case KbdFeedbackClass: { xKbdFeedbackState *k; XKbdFeedbackState *K; k = (xKbdFeedbackState *) f; K = (XKbdFeedbackState *) Feedback; K->class = k->class; K->length = sizeof(XKbdFeedbackState); K->id = k->id; K->click = k->click; K->percent = k->percent; K->pitch = k->pitch; K->duration = k->duration; K->led_mask = k->led_mask; K->global_auto_repeat = k->global_auto_repeat; memcpy((char *)&K->auto_repeats[0], (char *)&k->auto_repeats[0], 32); break; } case PtrFeedbackClass: { xPtrFeedbackState *p; XPtrFeedbackState *P; p = (xPtrFeedbackState *) f; P = (XPtrFeedbackState *) Feedback; P->class = p->class; P->length = sizeof(XPtrFeedbackState); P->id = p->id; P->accelNum = p->accelNum; P->accelDenom = p->accelDenom; P->threshold = p->threshold; break; } case IntegerFeedbackClass: { xIntegerFeedbackState *ifs; XIntegerFeedbackState *I; ifs = (xIntegerFeedbackState *) f; I = (XIntegerFeedbackState *) Feedback; I->class = ifs->class; I->length = sizeof(XIntegerFeedbackState); I->id = ifs->id; I->resolution = ifs->resolution; I->minVal = ifs->min_value; I->maxVal = ifs->max_value; break; } case StringFeedbackClass: { xStringFeedbackState *s; XStringFeedbackState *S; s = (xStringFeedbackState *) f; S = (XStringFeedbackState *) Feedback; S->class = s->class; S->length = sizeof(XStringFeedbackState) + (s->num_syms_supported * sizeof(KeySym)); S->id = s->id; S->max_symbols = s->max_symbols; S->num_syms_supported = s->num_syms_supported; S->syms_supported = (KeySym *) (S + 1); memcpy((char *)S->syms_supported, (char *)(s + 1), (S->num_syms_supported * sizeof(KeySym))); break; } case LedFeedbackClass: { xLedFeedbackState *l; XLedFeedbackState *L; l = (xLedFeedbackState *) f; L = (XLedFeedbackState *) Feedback; L->class = l->class; L->length = sizeof(XLedFeedbackState); L->id = l->id; L->led_values = l->led_values; L->led_mask = l->led_mask; break; } case BellFeedbackClass: { xBellFeedbackState *b; XBellFeedbackState *B; b = (xBellFeedbackState *) f; B = (XBellFeedbackState *) Feedback; B->class = b->class; B->length = sizeof(XBellFeedbackState); B->id = b->id; B->percent = b->percent; B->pitch = b->pitch; B->duration = b->duration; break; } default: break; } f = (xFeedbackState *) ((char *)f + f->length); Feedback = (XFeedbackState *) ((char *)Feedback + Feedback->length); } } out: XFree((char *)sav); UnlockDisplay(dpy); SyncHandle(); return (Sav); }
1,967
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: MagickBooleanType sixel_decode(unsigned char /* in */ *p, /* sixel bytes */ unsigned char /* out */ **pixels, /* decoded pixels */ size_t /* out */ *pwidth, /* image width */ size_t /* out */ *pheight, /* image height */ unsigned char /* out */ **palette, /* ARGB palette */ size_t /* out */ *ncolors /* palette size (<= 256) */) { int n, i, r, g, b, sixel_vertical_mask, c; int posision_x, posision_y; int max_x, max_y; int attributed_pan, attributed_pad; int attributed_ph, attributed_pv; int repeat_count, color_index, max_color_index = 2, background_color_index; int param[10]; int sixel_palet[SIXEL_PALETTE_MAX]; unsigned char *imbuf, *dmbuf; int imsx, imsy; int dmsx, dmsy; int y; posision_x = posision_y = 0; max_x = max_y = 0; attributed_pan = 2; attributed_pad = 1; attributed_ph = attributed_pv = 0; repeat_count = 1; color_index = 0; background_color_index = 0; imsx = 2048; imsy = 2048; imbuf = (unsigned char *) AcquireQuantumMemory(imsx * imsy,1); if (imbuf == NULL) { return(MagickFalse); } for (n = 0; n < 16; n++) { sixel_palet[n] = sixel_default_color_table[n]; } /* colors 16-231 are a 6x6x6 color cube */ for (r = 0; r < 6; r++) { for (g = 0; g < 6; g++) { for (b = 0; b < 6; b++) { sixel_palet[n++] = SIXEL_RGB(r * 51, g * 51, b * 51); } } } /* colors 232-255 are a grayscale ramp, intentionally leaving out */ for (i = 0; i < 24; i++) { sixel_palet[n++] = SIXEL_RGB(i * 11, i * 11, i * 11); } for (; n < SIXEL_PALETTE_MAX; n++) { sixel_palet[n] = SIXEL_RGB(255, 255, 255); } (void) ResetMagickMemory(imbuf, background_color_index, imsx * imsy); while (*p != '\0') { if ((p[0] == '\033' && p[1] == 'P') || *p == 0x90) { if (*p == '\033') { p++; } p = get_params(++p, param, &n); if (*p == 'q') { p++; if (n > 0) { /* Pn1 */ switch(param[0]) { case 0: case 1: attributed_pad = 2; break; case 2: attributed_pad = 5; break; case 3: attributed_pad = 4; break; case 4: attributed_pad = 4; break; case 5: attributed_pad = 3; break; case 6: attributed_pad = 3; break; case 7: attributed_pad = 2; break; case 8: attributed_pad = 2; break; case 9: attributed_pad = 1; break; } } if (n > 2) { /* Pn3 */ if (param[2] == 0) { param[2] = 10; } attributed_pan = attributed_pan * param[2] / 10; attributed_pad = attributed_pad * param[2] / 10; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; } } } else if ((p[0] == '\033' && p[1] == '\\') || *p == 0x9C) { break; } else if (*p == '"') { /* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */ p = get_params(++p, param, &n); if (n > 0) attributed_pad = param[0]; if (n > 1) attributed_pan = param[1]; if (n > 2 && param[2] > 0) attributed_ph = param[2]; if (n > 3 && param[3] > 0) attributed_pv = param[3]; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; if (imsx < attributed_ph || imsy < attributed_pv) { dmsx = imsx > attributed_ph ? imsx : attributed_ph; dmsy = imsy > attributed_pv ? imsy : attributed_pv; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) ResetMagickMemory(dmbuf, background_color_index, dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } } else if (*p == '!') { /* DECGRI Graphics Repeat Introducer ! Pn Ch */ p = get_params(++p, param, &n); if (n > 0) { repeat_count = param[0]; } } else if (*p == '#') { /* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */ p = get_params(++p, param, &n); if (n > 0) { if ((color_index = param[0]) < 0) { color_index = 0; } else if (color_index >= SIXEL_PALETTE_MAX) { color_index = SIXEL_PALETTE_MAX - 1; } } if (n > 4) { if (param[1] == 1) { /* HLS */ if (param[2] > 360) param[2] = 360; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = hls_to_rgb(param[2] * 100 / 360, param[3], param[4]); } else if (param[1] == 2) { /* RGB */ if (param[2] > 100) param[2] = 100; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = SIXEL_XRGB(param[2], param[3], param[4]); } } } else if (*p == '$') { /* DECGCR Graphics Carriage Return */ p++; posision_x = 0; repeat_count = 1; } else if (*p == '-') { /* DECGNL Graphics Next Line */ p++; posision_x = 0; posision_y += 6; repeat_count = 1; } else if (*p >= '?' && *p <= '\177') { if (imsx < (posision_x + repeat_count) || imsy < (posision_y + 6)) { int nx = imsx * 2; int ny = imsy * 2; while (nx < (posision_x + repeat_count) || ny < (posision_y + 6)) { nx *= 2; ny *= 2; } dmsx = nx; dmsy = ny; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) ResetMagickMemory(dmbuf, background_color_index, dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } if (color_index > max_color_index) { max_color_index = color_index; } if ((b = *(p++) - '?') == 0) { posision_x += repeat_count; } else { sixel_vertical_mask = 0x01; if (repeat_count <= 1) { for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { imbuf[imsx * (posision_y + i) + posision_x] = color_index; if (max_x < posision_x) { max_x = posision_x; } if (max_y < (posision_y + i)) { max_y = posision_y + i; } } sixel_vertical_mask <<= 1; } posision_x += 1; } else { /* repeat_count > 1 */ for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { c = sixel_vertical_mask << 1; for (n = 1; (i + n) < 6; n++) { if ((b & c) == 0) { break; } c <<= 1; } for (y = posision_y + i; y < posision_y + i + n; ++y) { (void) ResetMagickMemory(imbuf + imsx * y + posision_x, color_index, repeat_count); } if (max_x < (posision_x + repeat_count - 1)) { max_x = posision_x + repeat_count - 1; } if (max_y < (posision_y + i + n - 1)) { max_y = posision_y + i + n - 1; } i += (n - 1); sixel_vertical_mask <<= (n - 1); } sixel_vertical_mask <<= 1; } posision_x += repeat_count; } } repeat_count = 1; } else { p++; } } if (++max_x < attributed_ph) { max_x = attributed_ph; } if (++max_y < attributed_pv) { max_y = attributed_pv; } if (imsx > max_x || imsy > max_y) { dmsx = max_x; dmsy = max_y; if ((dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1)) == NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } for (y = 0; y < dmsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, dmsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } *pixels = imbuf; *pwidth = imsx; *pheight = imsy; *ncolors = max_color_index + 1; *palette = (unsigned char *) AcquireQuantumMemory(*ncolors,4); for (n = 0; n < (ssize_t) *ncolors; ++n) { (*palette)[n * 4 + 0] = sixel_palet[n] >> 16 & 0xff; (*palette)[n * 4 + 1] = sixel_palet[n] >> 8 & 0xff; (*palette)[n * 4 + 2] = sixel_palet[n] & 0xff; (*palette)[n * 4 + 3] = 0xff; } return(MagickTrue); } Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu) CWE ID: CWE-119
MagickBooleanType sixel_decode(unsigned char /* in */ *p, /* sixel bytes */ unsigned char /* out */ **pixels, /* decoded pixels */ size_t /* out */ *pwidth, /* image width */ size_t /* out */ *pheight, /* image height */ unsigned char /* out */ **palette, /* ARGB palette */ size_t /* out */ *ncolors /* palette size (<= 256) */) { int n, i, r, g, b, sixel_vertical_mask, c; int posision_x, posision_y; int max_x, max_y; int attributed_pan, attributed_pad; int attributed_ph, attributed_pv; int repeat_count, color_index, max_color_index = 2, background_color_index; int param[10]; int sixel_palet[SIXEL_PALETTE_MAX]; unsigned char *imbuf, *dmbuf; int imsx, imsy; int dmsx, dmsy; int y; posision_x = posision_y = 0; max_x = max_y = 0; attributed_pan = 2; attributed_pad = 1; attributed_ph = attributed_pv = 0; repeat_count = 1; color_index = 0; background_color_index = 0; imsx = 2048; imsy = 2048; imbuf = (unsigned char *) AcquireQuantumMemory(imsx , imsy); if (imbuf == NULL) { return(MagickFalse); } for (n = 0; n < 16; n++) { sixel_palet[n] = sixel_default_color_table[n]; } /* colors 16-231 are a 6x6x6 color cube */ for (r = 0; r < 6; r++) { for (g = 0; g < 6; g++) { for (b = 0; b < 6; b++) { sixel_palet[n++] = SIXEL_RGB(r * 51, g * 51, b * 51); } } } /* colors 232-255 are a grayscale ramp, intentionally leaving out */ for (i = 0; i < 24; i++) { sixel_palet[n++] = SIXEL_RGB(i * 11, i * 11, i * 11); } for (; n < SIXEL_PALETTE_MAX; n++) { sixel_palet[n] = SIXEL_RGB(255, 255, 255); } (void) ResetMagickMemory(imbuf, background_color_index, (size_t) imsx * imsy); while (*p != '\0') { if ((p[0] == '\033' && p[1] == 'P') || *p == 0x90) { if (*p == '\033') { p++; } p = get_params(++p, param, &n); if (*p == 'q') { p++; if (n > 0) { /* Pn1 */ switch(param[0]) { case 0: case 1: attributed_pad = 2; break; case 2: attributed_pad = 5; break; case 3: attributed_pad = 4; break; case 4: attributed_pad = 4; break; case 5: attributed_pad = 3; break; case 6: attributed_pad = 3; break; case 7: attributed_pad = 2; break; case 8: attributed_pad = 2; break; case 9: attributed_pad = 1; break; } } if (n > 2) { /* Pn3 */ if (param[2] == 0) { param[2] = 10; } attributed_pan = attributed_pan * param[2] / 10; attributed_pad = attributed_pad * param[2] / 10; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; } } } else if ((p[0] == '\033' && p[1] == '\\') || *p == 0x9C) { break; } else if (*p == '"') { /* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */ p = get_params(++p, param, &n); if (n > 0) attributed_pad = param[0]; if (n > 1) attributed_pan = param[1]; if (n > 2 && param[2] > 0) attributed_ph = param[2]; if (n > 3 && param[3] > 0) attributed_pv = param[3]; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; if (imsx < attributed_ph || imsy < attributed_pv) { dmsx = imsx > attributed_ph ? imsx : attributed_ph; dmsy = imsy > attributed_pv ? imsy : attributed_pv; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) ResetMagickMemory(dmbuf, background_color_index, (size_t) dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + (size_t) imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } } else if (*p == '!') { /* DECGRI Graphics Repeat Introducer ! Pn Ch */ p = get_params(++p, param, &n); if (n > 0) { repeat_count = param[0]; } } else if (*p == '#') { /* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */ p = get_params(++p, param, &n); if (n > 0) { if ((color_index = param[0]) < 0) { color_index = 0; } else if (color_index >= SIXEL_PALETTE_MAX) { color_index = SIXEL_PALETTE_MAX - 1; } } if (n > 4) { if (param[1] == 1) { /* HLS */ if (param[2] > 360) param[2] = 360; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = hls_to_rgb(param[2] * 100 / 360, param[3], param[4]); } else if (param[1] == 2) { /* RGB */ if (param[2] > 100) param[2] = 100; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = SIXEL_XRGB(param[2], param[3], param[4]); } } } else if (*p == '$') { /* DECGCR Graphics Carriage Return */ p++; posision_x = 0; repeat_count = 1; } else if (*p == '-') { /* DECGNL Graphics Next Line */ p++; posision_x = 0; posision_y += 6; repeat_count = 1; } else if (*p >= '?' && *p <= '\177') { if (imsx < (posision_x + repeat_count) || imsy < (posision_y + 6)) { int nx = imsx * 2; int ny = imsy * 2; while (nx < (posision_x + repeat_count) || ny < (posision_y + 6)) { nx *= 2; ny *= 2; } dmsx = nx; dmsy = ny; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) ResetMagickMemory(dmbuf, background_color_index, (size_t) dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + (size_t) imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } if (color_index > max_color_index) { max_color_index = color_index; } if ((b = *(p++) - '?') == 0) { posision_x += repeat_count; } else { sixel_vertical_mask = 0x01; if (repeat_count <= 1) { for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { imbuf[imsx * (posision_y + i) + posision_x] = color_index; if (max_x < posision_x) { max_x = posision_x; } if (max_y < (posision_y + i)) { max_y = posision_y + i; } } sixel_vertical_mask <<= 1; } posision_x += 1; } else { /* repeat_count > 1 */ for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { c = sixel_vertical_mask << 1; for (n = 1; (i + n) < 6; n++) { if ((b & c) == 0) { break; } c <<= 1; } for (y = posision_y + i; y < posision_y + i + n; ++y) { (void) ResetMagickMemory(imbuf + (size_t) imsx * y + posision_x, color_index, repeat_count); } if (max_x < (posision_x + repeat_count - 1)) { max_x = posision_x + repeat_count - 1; } if (max_y < (posision_y + i + n - 1)) { max_y = posision_y + i + n - 1; } i += (n - 1); sixel_vertical_mask <<= (n - 1); } sixel_vertical_mask <<= 1; } posision_x += repeat_count; } } repeat_count = 1; } else { p++; } } if (++max_x < attributed_ph) { max_x = attributed_ph; } if (++max_y < attributed_pv) { max_y = attributed_pv; } if (imsx > max_x || imsy > max_y) { dmsx = max_x; dmsy = max_y; if ((dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy)) == NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } for (y = 0; y < dmsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, dmsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } *pixels = imbuf; *pwidth = imsx; *pheight = imsy; *ncolors = max_color_index + 1; *palette = (unsigned char *) AcquireQuantumMemory(*ncolors,4); for (n = 0; n < (ssize_t) *ncolors; ++n) { (*palette)[n * 4 + 0] = sixel_palet[n] >> 16 & 0xff; (*palette)[n * 4 + 1] = sixel_palet[n] >> 8 & 0xff; (*palette)[n * 4 + 2] = sixel_palet[n] & 0xff; (*palette)[n * 4 + 3] = 0xff; } return(MagickTrue); }
29,093
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: mainloop_destroy_trigger(crm_trigger_t * source) { source->trigger = FALSE; if (source->id > 0) { g_source_remove(source->id); } return TRUE; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
mainloop_destroy_trigger(crm_trigger_t * source) { source->trigger = FALSE; if (source->id > 0) { g_source_remove(source->id); source->id = 0; } return TRUE; }
462
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur); } ret = inputPush(ctxt, input); GROW; return(ret); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur); } ret = inputPush(ctxt, input); if (ctxt->instate == XML_PARSER_EOF) return(-1); GROW; return(ret); }
17,541
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; handle_t *handle; struct ext4_ext_path *path; struct ext4_extent *extent; ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0; unsigned int credits, ee_len; int ret = 0, depth, split_flag = 0; loff_t ioffset; /* * We need to test this early because xfstests assumes that an * insert range of (0, 1) will return EOPNOTSUPP if the file * system does not support insert range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Insert range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EOPNOTSUPP; trace_ext4_insert_range(inode, offset, len); offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb); len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down to align start offset to page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } /* Check for wrap through zero */ if (inode->i_size + len > inode->i_sb->s_maxbytes) { ret = -EFBIG; goto out_mutex; } /* Offset should be less than i_size */ if (offset >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } truncate_pagecache(inode, ioffset); /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_dio; } /* Expand file to avoid data loss if there is error while shifting */ inode->i_size += len; EXT4_I(inode)->i_disksize += len; inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ret = ext4_mark_inode_dirty(handle, inode); if (ret) goto out_stop; down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); path = ext4_find_extent(inode, offset_lblk, NULL, 0); if (IS_ERR(path)) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } depth = ext_depth(inode); extent = path[depth].p_ext; if (extent) { ee_start_lblk = le32_to_cpu(extent->ee_block); ee_len = ext4_ext_get_actual_len(extent); /* * If offset_lblk is not the starting block of extent, split * the extent @offset_lblk */ if ((offset_lblk > ee_start_lblk) && (offset_lblk < (ee_start_lblk + ee_len))) { if (ext4_ext_is_unwritten(extent)) split_flag = EXT4_EXT_MARK_UNWRIT1 | EXT4_EXT_MARK_UNWRIT2; ret = ext4_split_extent_at(handle, inode, &path, offset_lblk, split_flag, EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO | EXT4_GET_BLOCKS_METADATA_NOFAIL); } ext4_ext_drop_refs(path); kfree(path); if (ret < 0) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } } ret = ext4_es_remove_extent(inode, offset_lblk, EXT_MAX_BLOCKS - offset_lblk); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } /* * if offset_lblk lies in a hole which is at start of file, use * ee_start_lblk to shift extents */ ret = ext4_ext_shift_extents(inode, handle, ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk, len_lblk, SHIFT_RIGHT); up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); out_stop: ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-362
int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; handle_t *handle; struct ext4_ext_path *path; struct ext4_extent *extent; ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0; unsigned int credits, ee_len; int ret = 0, depth, split_flag = 0; loff_t ioffset; /* * We need to test this early because xfstests assumes that an * insert range of (0, 1) will return EOPNOTSUPP if the file * system does not support insert range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Insert range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EOPNOTSUPP; trace_ext4_insert_range(inode, offset, len); offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb); len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down to align start offset to page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } /* Check for wrap through zero */ if (inode->i_size + len > inode->i_sb->s_maxbytes) { ret = -EFBIG; goto out_mutex; } /* Offset should be less than i_size */ if (offset >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* * Prevent page faults from reinstantiating pages we have released from * page cache. */ down_write(&EXT4_I(inode)->i_mmap_sem); truncate_pagecache(inode, ioffset); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_mmap; } /* Expand file to avoid data loss if there is error while shifting */ inode->i_size += len; EXT4_I(inode)->i_disksize += len; inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ret = ext4_mark_inode_dirty(handle, inode); if (ret) goto out_stop; down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); path = ext4_find_extent(inode, offset_lblk, NULL, 0); if (IS_ERR(path)) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } depth = ext_depth(inode); extent = path[depth].p_ext; if (extent) { ee_start_lblk = le32_to_cpu(extent->ee_block); ee_len = ext4_ext_get_actual_len(extent); /* * If offset_lblk is not the starting block of extent, split * the extent @offset_lblk */ if ((offset_lblk > ee_start_lblk) && (offset_lblk < (ee_start_lblk + ee_len))) { if (ext4_ext_is_unwritten(extent)) split_flag = EXT4_EXT_MARK_UNWRIT1 | EXT4_EXT_MARK_UNWRIT2; ret = ext4_split_extent_at(handle, inode, &path, offset_lblk, split_flag, EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO | EXT4_GET_BLOCKS_METADATA_NOFAIL); } ext4_ext_drop_refs(path); kfree(path); if (ret < 0) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } } ret = ext4_es_remove_extent(inode, offset_lblk, EXT_MAX_BLOCKS - offset_lblk); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } /* * if offset_lblk lies in a hole which is at start of file, use * ee_start_lblk to shift extents */ ret = ext4_ext_shift_extents(inode, handle, ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk, len_lblk, SHIFT_RIGHT); up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); out_stop: ext4_journal_stop(handle); out_mmap: up_write(&EXT4_I(inode)->i_mmap_sem); ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; }
7,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_iovlen = 1; msg.msg_iov = &iov; iov.iov_len = size; iov.iov_base = ubuf; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = sizeof(address); if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_iovlen = 1; msg.msg_iov = &iov; iov.iov_len = size; iov.iov_base = ubuf; /* Save some cycles and don't copy the address if not needed */ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; /* We assume all kernel code knows the size of sockaddr_storage */ msg.msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; }
18,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787
tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, t2p->tiff_datasize, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); }
26,051
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: NetworkLibrary* CrosLibrary::GetNetworkLibrary() { return network_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
NetworkLibrary* CrosLibrary::GetNetworkLibrary() {
14,468
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn, PNG_CONST png_byte bit_depthIn, PNG_CONST int palette_numberIn, PNG_CONST int interlace_typeIn, PNG_CONST double file_gammaIn, PNG_CONST double screen_gammaIn, PNG_CONST png_byte sbitIn, PNG_CONST int threshold_testIn, PNG_CONST char *name, PNG_CONST int use_input_precisionIn, PNG_CONST int scale16In, PNG_CONST int expand16In, PNG_CONST int do_backgroundIn, PNG_CONST png_color_16 *bkgd_colorIn, double bkgd_gammaIn) { gamma_display d; context(&pmIn->this, fault); gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn, palette_numberIn, interlace_typeIn, 0, 0, 0), file_gammaIn, screen_gammaIn, sbitIn, threshold_testIn, use_input_precisionIn, scale16In, expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn); Try { png_structp pp; png_infop pi; gama_modification gama_mod; srgb_modification srgb_mod; sbit_modification sbit_mod; /* For the moment don't use the png_modifier support here. */ d.pm->encoding_counter = 0; modifier_set_encoding(d.pm); /* Just resets everything */ d.pm->current_gamma = d.file_gamma; /* Make an appropriate modifier to set the PNG file gamma to the * given gamma value and the sBIT chunk to the given precision. */ d.pm->modifications = NULL; gama_modification_init(&gama_mod, d.pm, d.file_gamma); srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/); if (d.sbit > 0) sbit_modification_init(&sbit_mod, d.pm, d.sbit); modification_reset(d.pm->modifications); /* Get a png_struct for writing the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, name); standard_palette_init(&d.this); /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row, gamma_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ gamma_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) gamma_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); if (d.pm->log && !d.threshold_test && !d.this.speed) fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n", d.this.bit_depth, colour_types[d.this.colour_type], name, d.maxerrout, d.maxerrabs, 100*d.maxerrpc); /* Log the summary values too. */ if (d.this.colour_type == 0 || d.this.colour_type == 4) { switch (d.this.bit_depth) { case 1: break; case 2: if (d.maxerrout > d.pm->error_gray_2) d.pm->error_gray_2 = d.maxerrout; break; case 4: if (d.maxerrout > d.pm->error_gray_4) d.pm->error_gray_4 = d.maxerrout; break; case 8: if (d.maxerrout > d.pm->error_gray_8) d.pm->error_gray_8 = d.maxerrout; break; case 16: if (d.maxerrout > d.pm->error_gray_16) d.pm->error_gray_16 = d.maxerrout; break; default: png_error(pp, "bad bit depth (internal: 1)"); } } else if (d.this.colour_type == 2 || d.this.colour_type == 6) { switch (d.this.bit_depth) { case 8: if (d.maxerrout > d.pm->error_color_8) d.pm->error_color_8 = d.maxerrout; break; case 16: if (d.maxerrout > d.pm->error_color_16) d.pm->error_color_16 = d.maxerrout; break; default: png_error(pp, "bad bit depth (internal: 2)"); } } else if (d.this.colour_type == 3) { if (d.maxerrout > d.pm->error_indexed) d.pm->error_indexed = d.maxerrout; } } Catch(fault) modifier_reset(voidcast(png_modifier*,(void*)fault)); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn, gamma_test(png_modifier *pmIn, const png_byte colour_typeIn, const png_byte bit_depthIn, const int palette_numberIn, const int interlace_typeIn, const double file_gammaIn, const double screen_gammaIn, const png_byte sbitIn, const int threshold_testIn, const char *name, const int use_input_precisionIn, const int scale16In, const int expand16In, const int do_backgroundIn, const png_color_16 *bkgd_colorIn, double bkgd_gammaIn) { gamma_display d; context(&pmIn->this, fault); gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn, palette_numberIn, interlace_typeIn, 0, 0, 0), file_gammaIn, screen_gammaIn, sbitIn, threshold_testIn, use_input_precisionIn, scale16In, expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn); Try { png_structp pp; png_infop pi; gama_modification gama_mod; srgb_modification srgb_mod; sbit_modification sbit_mod; /* For the moment don't use the png_modifier support here. */ d.pm->encoding_counter = 0; modifier_set_encoding(d.pm); /* Just resets everything */ d.pm->current_gamma = d.file_gamma; /* Make an appropriate modifier to set the PNG file gamma to the * given gamma value and the sBIT chunk to the given precision. */ d.pm->modifications = NULL; gama_modification_init(&gama_mod, d.pm, d.file_gamma); srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/); if (d.sbit > 0) sbit_modification_init(&sbit_mod, d.pm, d.sbit); modification_reset(d.pm->modifications); /* Get a png_struct for reading the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, name); standard_palette_init(&d.this); /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row, gamma_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ gamma_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) gamma_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); if (d.pm->log && !d.threshold_test && !d.this.speed) fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n", d.this.bit_depth, colour_types[d.this.colour_type], name, d.maxerrout, d.maxerrabs, 100*d.maxerrpc); /* Log the summary values too. */ if (d.this.colour_type == 0 || d.this.colour_type == 4) { switch (d.this.bit_depth) { case 1: break; case 2: if (d.maxerrout > d.pm->error_gray_2) d.pm->error_gray_2 = d.maxerrout; break; case 4: if (d.maxerrout > d.pm->error_gray_4) d.pm->error_gray_4 = d.maxerrout; break; case 8: if (d.maxerrout > d.pm->error_gray_8) d.pm->error_gray_8 = d.maxerrout; break; case 16: if (d.maxerrout > d.pm->error_gray_16) d.pm->error_gray_16 = d.maxerrout; break; default: png_error(pp, "bad bit depth (internal: 1)"); } } else if (d.this.colour_type == 2 || d.this.colour_type == 6) { switch (d.this.bit_depth) { case 8: if (d.maxerrout > d.pm->error_color_8) d.pm->error_color_8 = d.maxerrout; break; case 16: if (d.maxerrout > d.pm->error_color_16) d.pm->error_color_16 = d.maxerrout; break; default: png_error(pp, "bad bit depth (internal: 2)"); } } else if (d.this.colour_type == 3) { if (d.maxerrout > d.pm->error_indexed) d.pm->error_indexed = d.maxerrout; } } Catch(fault) modifier_reset(voidcast(png_modifier*,(void*)fault)); }
14,914
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void PasswordInputType::EnableSecureTextInput() { LocalFrame* frame = GetElement().GetDocument().GetFrame(); if (!frame) return; frame->Selection().SetUseSecureKeyboardEntryWhenActive(true); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
void PasswordInputType::EnableSecureTextInput() {
22,284
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int parse_rock_ridge_inode(struct iso_directory_record *de, struct inode *inode) { int result = parse_rock_ridge_inode_internal(de, inode, 0); /* * if rockridge flag was reset and we didn't look for attributes * behind eventual XA attributes, have a look there */ if ((ISOFS_SB(inode->i_sb)->s_rock_offset == -1) && (ISOFS_SB(inode->i_sb)->s_rock == 2)) { result = parse_rock_ridge_inode_internal(de, inode, 14); } return result; } Commit Message: isofs: Fix unbounded recursion when processing relocated directories We did not check relocated directory in any way when processing Rock Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL entry pointing to another CL entry leading to possibly unbounded recursion in kernel code and thus stack overflow or deadlocks (if there is a loop created from CL entries). Fix the problem by not allowing CL entry to point to a directory entry with CL entry (such use makes no good sense anyway) and by checking whether CL entry doesn't point to itself. CC: [email protected] Reported-by: Chris Evans <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20
int parse_rock_ridge_inode(struct iso_directory_record *de, struct inode *inode) int parse_rock_ridge_inode(struct iso_directory_record *de, struct inode *inode, int relocated) { int flags = relocated ? RR_RELOC_DE : 0; int result = parse_rock_ridge_inode_internal(de, inode, flags); /* * if rockridge flag was reset and we didn't look for attributes * behind eventual XA attributes, have a look there */ if ((ISOFS_SB(inode->i_sb)->s_rock_offset == -1) && (ISOFS_SB(inode->i_sb)->s_rock == 2)) { result = parse_rock_ridge_inode_internal(de, inode, flags | RR_REGARD_XA); } return result; }
24,353
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool MockContentSettingsClient::allowAutoplay(bool default_value) { return default_value || flags_->autoplay_allowed(); } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} CWE ID: CWE-119
bool MockContentSettingsClient::allowAutoplay(bool default_value) { return flags_->autoplay_allowed(); }
1,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void FetchManager::Loader::Start() { if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) && !execution_context_->GetContentSecurityPolicy()->AllowConnectToSource( fetch_request_data_->Url())) { PerformNetworkError( "Refused to connect to '" + fetch_request_data_->Url().ElidedString() + "' because it violates the document's Content Security Policy."); return; } if ((SecurityOrigin::Create(fetch_request_data_->Url()) ->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) || (fetch_request_data_->Url().ProtocolIsData() && fetch_request_data_->SameOriginDataURLFlag()) || (fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) { PerformSchemeFetch(); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) { PerformNetworkError("Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". Request mode is \"same-origin\" but the URL\'s " "origin is not same as the request origin " + fetch_request_data_->Origin()->ToString() + "."); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) { fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting); PerformSchemeFetch(); return; } if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI( fetch_request_data_->Url().Protocol())) { PerformNetworkError( "Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". URL scheme must be \"http\" or \"https\" for CORS request."); return; } fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting); PerformHTTPFetch(); } Commit Message: [Fetch API] Fix redirect leak on "no-cors" requests The spec issue is now fixed, and this CL follows the spec change[1]. 1: https://github.com/whatwg/fetch/commit/14858d3e9402285a7ff3b5e47a22896ff3adc95d Bug: 791324 Change-Id: Ic3e3955f43578b38fc44a5a6b2a1b43d56a2becb Reviewed-on: https://chromium-review.googlesource.com/1023613 Reviewed-by: Tsuyoshi Horo <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#552964} CWE ID: CWE-200
void FetchManager::Loader::Start() { if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) && !execution_context_->GetContentSecurityPolicy()->AllowConnectToSource( fetch_request_data_->Url())) { PerformNetworkError( "Refused to connect to '" + fetch_request_data_->Url().ElidedString() + "' because it violates the document's Content Security Policy."); return; } if ((SecurityOrigin::Create(fetch_request_data_->Url()) ->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) || (fetch_request_data_->Url().ProtocolIsData() && fetch_request_data_->SameOriginDataURLFlag()) || (fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) { PerformSchemeFetch(); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) { PerformNetworkError("Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". Request mode is \"same-origin\" but the URL\'s " "origin is not same as the request origin " + fetch_request_data_->Origin()->ToString() + "."); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) { // "If |request|'s redirect mode is not |follow|, then return a network // error. if (fetch_request_data_->Redirect() != FetchRedirectMode::kFollow) { PerformNetworkError("Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". Request mode is \"no-cors\" but the redirect mode " " is not \"follow\"."); return; } fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting); PerformSchemeFetch(); return; } if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI( fetch_request_data_->Url().Protocol())) { PerformNetworkError( "Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". URL scheme must be \"http\" or \"https\" for CORS request."); return; } fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting); PerformHTTPFetch(); }
22,828
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int cap_bprm_set_creds(struct linux_binprm *bprm) { const struct cred *old = current_cred(); struct cred *new = bprm->cred; bool effective, has_cap = false; int ret; effective = false; ret = get_file_caps(bprm, &effective, &has_cap); if (ret < 0) return ret; if (!issecure(SECURE_NOROOT)) { /* * If the legacy file capability is set, then don't set privs * for a setuid root binary run by a non-root user. Do set it * for a root user just to cause least surprise to an admin. */ if (has_cap && new->uid != 0 && new->euid == 0) { warn_setuid_and_fcaps_mixed(bprm->filename); goto skip; } /* * To support inheritance of root-permissions and suid-root * executables under compatibility mode, we override the * capability sets for the file. * * If only the real uid is 0, we do not set the effective bit. */ if (new->euid == 0 || new->uid == 0) { /* pP' = (cap_bset & ~0) | (pI & ~0) */ new->cap_permitted = cap_combine(old->cap_bset, old->cap_inheritable); } if (new->euid == 0) effective = true; } skip: /* Don't let someone trace a set[ug]id/setpcap binary with the revised * credentials unless they have the appropriate permit */ if ((new->euid != old->uid || new->egid != old->gid || !cap_issubset(new->cap_permitted, old->cap_permitted)) && bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) { /* downgrade; they get no more than they had, and maybe less */ if (!capable(CAP_SETUID)) { new->euid = new->uid; new->egid = new->gid; } new->cap_permitted = cap_intersect(new->cap_permitted, old->cap_permitted); } new->suid = new->fsuid = new->euid; new->sgid = new->fsgid = new->egid; if (effective) new->cap_effective = new->cap_permitted; else cap_clear(new->cap_effective); bprm->cap_effective = effective; /* * Audit candidate if current->cap_effective is set * * We do not bother to audit if 3 things are true: * 1) cap_effective has all caps * 2) we are root * 3) root is supposed to have all caps (SECURE_NOROOT) * Since this is just a normal root execing a process. * * Number 1 above might fail if you don't have a full bset, but I think * that is interesting information to audit. */ if (!cap_isclear(new->cap_effective)) { if (!cap_issubset(CAP_FULL_SET, new->cap_effective) || new->euid != 0 || new->uid != 0 || issecure(SECURE_NOROOT)) { ret = audit_log_bprm_fcaps(bprm, new, old); if (ret < 0) return ret; } } new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS); return 0; } Commit Message: fcaps: clear the same personality flags as suid when fcaps are used If a process increases permissions using fcaps all of the dangerous personality flags which are cleared for suid apps should also be cleared. Thus programs given priviledge with fcaps will continue to have address space randomization enabled even if the parent tried to disable it to make it easier to attack. Signed-off-by: Eric Paris <[email protected]> Reviewed-by: Serge Hallyn <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264
int cap_bprm_set_creds(struct linux_binprm *bprm) { const struct cred *old = current_cred(); struct cred *new = bprm->cred; bool effective, has_cap = false; int ret; effective = false; ret = get_file_caps(bprm, &effective, &has_cap); if (ret < 0) return ret; if (!issecure(SECURE_NOROOT)) { /* * If the legacy file capability is set, then don't set privs * for a setuid root binary run by a non-root user. Do set it * for a root user just to cause least surprise to an admin. */ if (has_cap && new->uid != 0 && new->euid == 0) { warn_setuid_and_fcaps_mixed(bprm->filename); goto skip; } /* * To support inheritance of root-permissions and suid-root * executables under compatibility mode, we override the * capability sets for the file. * * If only the real uid is 0, we do not set the effective bit. */ if (new->euid == 0 || new->uid == 0) { /* pP' = (cap_bset & ~0) | (pI & ~0) */ new->cap_permitted = cap_combine(old->cap_bset, old->cap_inheritable); } if (new->euid == 0) effective = true; } skip: /* if we have fs caps, clear dangerous personality flags */ if (!cap_issubset(new->cap_permitted, old->cap_permitted)) bprm->per_clear |= PER_CLEAR_ON_SETID; /* Don't let someone trace a set[ug]id/setpcap binary with the revised * credentials unless they have the appropriate permit */ if ((new->euid != old->uid || new->egid != old->gid || !cap_issubset(new->cap_permitted, old->cap_permitted)) && bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) { /* downgrade; they get no more than they had, and maybe less */ if (!capable(CAP_SETUID)) { new->euid = new->uid; new->egid = new->gid; } new->cap_permitted = cap_intersect(new->cap_permitted, old->cap_permitted); } new->suid = new->fsuid = new->euid; new->sgid = new->fsgid = new->egid; if (effective) new->cap_effective = new->cap_permitted; else cap_clear(new->cap_effective); bprm->cap_effective = effective; /* * Audit candidate if current->cap_effective is set * * We do not bother to audit if 3 things are true: * 1) cap_effective has all caps * 2) we are root * 3) root is supposed to have all caps (SECURE_NOROOT) * Since this is just a normal root execing a process. * * Number 1 above might fail if you don't have a full bset, but I think * that is interesting information to audit. */ if (!cap_isclear(new->cap_effective)) { if (!cap_issubset(CAP_FULL_SET, new->cap_effective) || new->euid != 0 || new->uid != 0 || issecure(SECURE_NOROOT)) { ret = audit_log_bprm_fcaps(bprm, new, old); if (ret < 0) return ret; } } new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS); return 0; }
12,220
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool omx_vdec::release_output_done(void) { bool bRet = false; unsigned i=0,j=0; DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_inp_mem_ptr); if (m_out_mem_ptr) { for (; j < drv_ctx.op_buf.actualcount ; j++) { if (BITMASK_PRESENT(&m_out_bm_count,j)) { break; } } if (j == drv_ctx.op_buf.actualcount) { m_out_bm_count = 0; bRet = true; } } else { m_out_bm_count = 0; bRet = true; } return bRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: add safety checks for freeing buffers Allow only up to 64 buffers on input/output port (since the allocation bitmap is only 64-wide). Do not allow changing theactual buffer count while still holding allocation (Client can technically negotiate buffer count on a free/disabled port) Add safety checks to free only as many buffers were allocated. Fixes: Security Vulnerability - Heap Overflow and Possible Local Privilege Escalation in MediaServer (libOmxVdec problem #3) Bug: 27532282 27661749 Change-Id: I06dd680d43feaef3efdc87311e8a6703e234b523 CWE ID: CWE-119
bool omx_vdec::release_output_done(void) { bool bRet = false; unsigned i=0,j=0; DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_out_mem_ptr); if (m_out_mem_ptr) { for (; j < drv_ctx.op_buf.actualcount ; j++) { if (BITMASK_PRESENT(&m_out_bm_count,j)) { break; } } if (j == drv_ctx.op_buf.actualcount) { m_out_bm_count = 0; bRet = true; } } else { m_out_bm_count = 0; bRet = true; } return bRet; }
12,296
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static void sas_revalidate_domain(struct work_struct *work) { int res = 0; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; struct sas_ha_struct *ha = port->ha; struct domain_device *ddev = port->port_dev; /* prevent revalidation from finding sata links in recovery */ mutex_lock(&ha->disco_mutex); if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) { SAS_DPRINTK("REVALIDATION DEFERRED on port %d, pid:%d\n", port->id, task_pid_nr(current)); goto out; } clear_bit(DISCE_REVALIDATE_DOMAIN, &port->disc.pending); SAS_DPRINTK("REVALIDATING DOMAIN on port %d, pid:%d\n", port->id, task_pid_nr(current)); if (ddev && (ddev->dev_type == SAS_FANOUT_EXPANDER_DEVICE || ddev->dev_type == SAS_EDGE_EXPANDER_DEVICE)) res = sas_ex_revalidate_domain(ddev); SAS_DPRINTK("done REVALIDATING DOMAIN on port %d, pid:%d, res 0x%x\n", port->id, task_pid_nr(current), res); out: mutex_unlock(&ha->disco_mutex); } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID:
static void sas_revalidate_domain(struct work_struct *work) { int res = 0; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; struct sas_ha_struct *ha = port->ha; struct domain_device *ddev = port->port_dev; /* prevent revalidation from finding sata links in recovery */ mutex_lock(&ha->disco_mutex); if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) { SAS_DPRINTK("REVALIDATION DEFERRED on port %d, pid:%d\n", port->id, task_pid_nr(current)); goto out; } clear_bit(DISCE_REVALIDATE_DOMAIN, &port->disc.pending); SAS_DPRINTK("REVALIDATING DOMAIN on port %d, pid:%d\n", port->id, task_pid_nr(current)); if (ddev && (ddev->dev_type == SAS_FANOUT_EXPANDER_DEVICE || ddev->dev_type == SAS_EDGE_EXPANDER_DEVICE)) res = sas_ex_revalidate_domain(ddev); SAS_DPRINTK("done REVALIDATING DOMAIN on port %d, pid:%d, res 0x%x\n", port->id, task_pid_nr(current), res); out: mutex_unlock(&ha->disco_mutex); sas_destruct_devices(port); sas_destruct_ports(port); sas_probe_devices(port); }
10,146
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void AudioRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, int input_channels) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(LookupById(stream_id) == NULL); media::AudioParameters audio_params(params); uint32 buffer_size = media::AudioBus::CalculateMemorySize(audio_params); DCHECK_GT(buffer_size, 0U); DCHECK_LE(buffer_size, static_cast<uint32>(media::limits::kMaxPacketSizeInBytes)); DCHECK_GE(input_channels, 0); DCHECK_LT(input_channels, media::limits::kMaxChannels); int output_memory_size = AudioBus::CalculateMemorySize(audio_params); DCHECK_GT(output_memory_size, 0); int frames = audio_params.frames_per_buffer(); int input_memory_size = AudioBus::CalculateMemorySize(input_channels, frames); DCHECK_GE(input_memory_size, 0); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 io_buffer_size = output_memory_size + input_memory_size; uint32 shared_memory_size = media::TotalSharedMemorySizeInBytes(io_buffer_size); if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioSyncReader> reader( new AudioSyncReader(&entry->shared_memory, params, input_channels)); if (!reader->Init()) { SendErrorMessage(stream_id); return; } entry->reader.reset(reader.release()); entry->controller = media::AudioOutputController::Create( audio_manager_, this, audio_params, entry->reader.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); if (media_observer_) media_observer_->OnSetAudioStreamStatus(this, stream_id, "created"); } Commit Message: Improve validation when creating audio streams. BUG=166795 Review URL: https://codereview.chromium.org/11647012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void AudioRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, int input_channels) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // media::AudioParameters is validated in the deserializer. if (input_channels < 0 || input_channels > media::limits::kMaxChannels || LookupById(stream_id) != NULL) { SendErrorMessage(stream_id); return; } media::AudioParameters audio_params(params); int output_memory_size = AudioBus::CalculateMemorySize(audio_params); int frames = audio_params.frames_per_buffer(); int input_memory_size = AudioBus::CalculateMemorySize(input_channels, frames); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 io_buffer_size = output_memory_size + input_memory_size; uint32 shared_memory_size = media::TotalSharedMemorySizeInBytes(io_buffer_size); if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioSyncReader> reader( new AudioSyncReader(&entry->shared_memory, params, input_channels)); if (!reader->Init()) { SendErrorMessage(stream_id); return; } entry->reader.reset(reader.release()); entry->controller = media::AudioOutputController::Create( audio_manager_, this, audio_params, entry->reader.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); if (media_observer_) media_observer_->OnSetAudioStreamStatus(this, stream_id, "created"); }
135
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void inode_init_owner(struct inode *inode, const struct inode *dir, umode_t mode) { inode->i_uid = current_fsuid(); if (dir && dir->i_mode & S_ISGID) { inode->i_gid = dir->i_gid; if (S_ISDIR(mode)) mode |= S_ISGID; } else inode->i_gid = current_fsgid(); inode->i_mode = mode; } Commit Message: Fix up non-directory creation in SGID directories sgid directories have special semantics, making newly created files in the directory belong to the group of the directory, and newly created subdirectories will also become sgid. This is historically used for group-shared directories. But group directories writable by non-group members should not imply that such non-group members can magically join the group, so make sure to clear the sgid bit on non-directories for non-members (but remember that sgid without group execute means "mandatory locking", just to confuse things even more). Reported-by: Jann Horn <[email protected]> Cc: Andy Lutomirski <[email protected]> Cc: Al Viro <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-269
void inode_init_owner(struct inode *inode, const struct inode *dir, umode_t mode) { inode->i_uid = current_fsuid(); if (dir && dir->i_mode & S_ISGID) { inode->i_gid = dir->i_gid; /* Directories are special, and always inherit S_ISGID */ if (S_ISDIR(mode)) mode |= S_ISGID; else if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP) && !in_group_p(inode->i_gid) && !capable_wrt_inode_uidgid(dir, CAP_FSETID)) mode &= ~S_ISGID; } else inode->i_gid = current_fsgid(); inode->i_mode = mode; }
17,058
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) return -ENOKEY; p = key->payload.data[0]; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kzfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kzfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kzfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kzfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kzfree(datablob); kzfree(new_o); return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
static int trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (key_is_negative(key)) return -ENOKEY; p = key->payload.data[0]; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kzfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kzfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kzfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kzfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kzfree(datablob); kzfree(new_o); return ret; }
16,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int digi_startup(struct usb_serial *serial) { struct digi_serial *serial_priv; int ret; serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL); if (!serial_priv) return -ENOMEM; spin_lock_init(&serial_priv->ds_serial_lock); serial_priv->ds_oob_port_num = serial->type->num_ports; serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num]; ret = digi_port_init(serial_priv->ds_oob_port, serial_priv->ds_oob_port_num); if (ret) { kfree(serial_priv); return ret; } usb_set_serial_data(serial, serial_priv); return 0; } Commit Message: USB: digi_acceleport: do sanity checking for the number of ports The driver can be crashed with devices that expose crafted descriptors with too few endpoints. See: http://seclists.org/bugtraq/2016/Mar/61 Signed-off-by: Oliver Neukum <[email protected]> [johan: fix OOB endpoint check and add error messages ] Cc: stable <[email protected]> Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID:
static int digi_startup(struct usb_serial *serial) { struct device *dev = &serial->interface->dev; struct digi_serial *serial_priv; int ret; int i; /* check whether the device has the expected number of endpoints */ if (serial->num_port_pointers < serial->type->num_ports + 1) { dev_err(dev, "OOB endpoints missing\n"); return -ENODEV; } for (i = 0; i < serial->type->num_ports + 1 ; i++) { if (!serial->port[i]->read_urb) { dev_err(dev, "bulk-in endpoint missing\n"); return -ENODEV; } if (!serial->port[i]->write_urb) { dev_err(dev, "bulk-out endpoint missing\n"); return -ENODEV; } } serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL); if (!serial_priv) return -ENOMEM; spin_lock_init(&serial_priv->ds_serial_lock); serial_priv->ds_oob_port_num = serial->type->num_ports; serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num]; ret = digi_port_init(serial_priv->ds_oob_port, serial_priv->ds_oob_port_num); if (ret) { kfree(serial_priv); return ret; } usb_set_serial_data(serial, serial_priv); return 0; }
3,967
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: RenderFrameHostManager::DetermineSiteInstanceForURL( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* current_instance, SiteInstance* dest_instance, ui::PageTransition transition, bool dest_is_restore, bool dest_is_view_source_mode, bool force_browsing_instance_swap, bool was_server_redirect) { SiteInstanceImpl* current_instance_impl = static_cast<SiteInstanceImpl*>(current_instance); NavigationControllerImpl& controller = delegate_->GetControllerForRenderManager(); BrowserContext* browser_context = controller.GetBrowserContext(); if (dest_instance) { if (force_browsing_instance_swap) { CHECK(!dest_instance->IsRelatedSiteInstance( render_frame_host_->GetSiteInstance())); } return SiteInstanceDescriptor(dest_instance); } if (force_browsing_instance_swap) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kProcessPerSite) && ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) { return SiteInstanceDescriptor(current_instance_impl); } if (SiteIsolationPolicy::AreCrossProcessFramesPossible() && !frame_tree_node_->IsMainFrame()) { SiteInstance* parent_site_instance = frame_tree_node_->parent()->current_frame_host()->GetSiteInstance(); if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) && dest_url.SchemeIs(kChromeUIScheme)) { return SiteInstanceDescriptor(parent_site_instance); } } if (!current_instance_impl->HasSite()) { bool use_process_per_site = RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) && RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url); if (current_instance_impl->HasRelatedSiteInstance(dest_url) || use_process_per_site) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } if (current_instance_impl->HasWrongProcessForURL(dest_url)) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); if (dest_is_view_source_mode) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } if (dest_is_restore && GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) { current_instance_impl->SetSite(dest_url); } return SiteInstanceDescriptor(current_instance_impl); } NavigationEntry* current_entry = controller.GetLastCommittedEntry(); if (interstitial_page_) { current_entry = controller.GetEntryAtOffset(-1); } if (current_entry && current_entry->IsViewSourceMode() != dest_is_view_source_mode && !IsRendererDebugURL(dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } GURL about_blank(url::kAboutBlankURL); GURL about_srcdoc(content::kAboutSrcDocURL); bool dest_is_data_or_about = dest_url == about_srcdoc || dest_url == about_blank || dest_url.scheme() == url::kDataScheme; if (source_instance && dest_is_data_or_about && !was_server_redirect) return SiteInstanceDescriptor(source_instance); if (IsCurrentlySameSite(render_frame_host_.get(), dest_url)) return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) { if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* main_frame = frame_tree_node_->frame_tree()->root()->current_frame_host(); if (IsCurrentlySameSite(main_frame, dest_url)) return SiteInstanceDescriptor(main_frame->GetSiteInstance()); } if (frame_tree_node_->opener()) { RenderFrameHostImpl* opener_frame = frame_tree_node_->opener()->current_frame_host(); if (IsCurrentlySameSite(opener_frame, dest_url)) return SiteInstanceDescriptor(opener_frame->GetSiteInstance()); } } if (!frame_tree_node_->IsMainFrame() && SiteIsolationPolicy::IsTopDocumentIsolationEnabled() && !SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url)) { if (GetContentClient() ->browser() ->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation( dest_url, current_instance)) { return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); } return SiteInstanceDescriptor( browser_context, dest_url, SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME); } if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* parent = frame_tree_node_->parent()->current_frame_host(); bool dest_url_requires_dedicated_process = SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url); if (!parent->GetSiteInstance()->RequiresDedicatedProcess() && !dest_url_requires_dedicated_process) { return SiteInstanceDescriptor(parent->GetSiteInstance()); } } return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } 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
RenderFrameHostManager::DetermineSiteInstanceForURL( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* current_instance, SiteInstance* dest_instance, ui::PageTransition transition, bool dest_is_restore, bool dest_is_view_source_mode, bool force_browsing_instance_swap, bool was_server_redirect) { SiteInstanceImpl* current_instance_impl = static_cast<SiteInstanceImpl*>(current_instance); NavigationControllerImpl& controller = delegate_->GetControllerForRenderManager(); BrowserContext* browser_context = controller.GetBrowserContext(); if (dest_instance) { if (force_browsing_instance_swap) { CHECK(!dest_instance->IsRelatedSiteInstance( render_frame_host_->GetSiteInstance())); } return SiteInstanceDescriptor(dest_instance); } if (force_browsing_instance_swap) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kProcessPerSite) && ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) { return SiteInstanceDescriptor(current_instance_impl); } if (SiteIsolationPolicy::AreCrossProcessFramesPossible() && !frame_tree_node_->IsMainFrame()) { SiteInstance* parent_site_instance = frame_tree_node_->parent()->current_frame_host()->GetSiteInstance(); if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) && dest_url.SchemeIs(kChromeUIScheme)) { return SiteInstanceDescriptor(parent_site_instance); } } if (!current_instance_impl->HasSite()) { bool use_process_per_site = RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) && RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url); if (current_instance_impl->HasRelatedSiteInstance(dest_url) || use_process_per_site) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } if (current_instance_impl->HasWrongProcessForURL(dest_url)) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); if (dest_is_view_source_mode) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } if (dest_is_restore && GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) { current_instance_impl->SetSite(dest_url); } return SiteInstanceDescriptor(current_instance_impl); } NavigationEntry* current_entry = controller.GetLastCommittedEntry(); if (delegate_->GetInterstitialForRenderManager()) { current_entry = controller.GetEntryAtOffset(-1); } if (current_entry && current_entry->IsViewSourceMode() != dest_is_view_source_mode && !IsRendererDebugURL(dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } GURL about_blank(url::kAboutBlankURL); GURL about_srcdoc(content::kAboutSrcDocURL); bool dest_is_data_or_about = dest_url == about_srcdoc || dest_url == about_blank || dest_url.scheme() == url::kDataScheme; if (source_instance && dest_is_data_or_about && !was_server_redirect) return SiteInstanceDescriptor(source_instance); if (IsCurrentlySameSite(render_frame_host_.get(), dest_url)) return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) { if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* main_frame = frame_tree_node_->frame_tree()->root()->current_frame_host(); if (IsCurrentlySameSite(main_frame, dest_url)) return SiteInstanceDescriptor(main_frame->GetSiteInstance()); } if (frame_tree_node_->opener()) { RenderFrameHostImpl* opener_frame = frame_tree_node_->opener()->current_frame_host(); if (IsCurrentlySameSite(opener_frame, dest_url)) return SiteInstanceDescriptor(opener_frame->GetSiteInstance()); } } if (!frame_tree_node_->IsMainFrame() && SiteIsolationPolicy::IsTopDocumentIsolationEnabled() && !SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url)) { if (GetContentClient() ->browser() ->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation( dest_url, current_instance)) { return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); } return SiteInstanceDescriptor( browser_context, dest_url, SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME); } if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* parent = frame_tree_node_->parent()->current_frame_host(); bool dest_url_requires_dedicated_process = SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url); if (!parent->GetSiteInstance()->RequiresDedicatedProcess() && !dest_url_requires_dedicated_process) { return SiteInstanceDescriptor(parent->GetSiteInstance()); } } return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); }
27,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void MediaInterfaceProxy::CreateCdm( media::mojom::ContentDecryptionModuleRequest request) { DCHECK(thread_checker_.CalledOnValidThread()); GetMediaInterfaceFactory()->CreateCdm(std::move(request)); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
void MediaInterfaceProxy::CreateCdm( media::mojom::ContentDecryptionModuleRequest request) { DCHECK(thread_checker_.CalledOnValidThread()); GetCdmInterfaceFactory()->CreateCdm(std::move(request)); }
4,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); } Commit Message: CWE ID: CWE-189
create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = (size_t)height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); }
21,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void HttpBridge::MakeAsynchronousPost() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); base::AutoLock lock(fetch_state_lock_); DCHECK(!fetch_state_.request_completed); if (fetch_state_.aborted) return; fetch_state_.url_poster = new URLFetcher(url_for_request_, URLFetcher::POST, this); fetch_state_.url_poster->set_request_context(context_getter_for_request_); fetch_state_.url_poster->set_upload_data(content_type_, request_content_); fetch_state_.url_poster->set_extra_request_headers(extra_headers_); fetch_state_.url_poster->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES); fetch_state_.url_poster->Start(); } Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc. This change modified http_bridge so that it uses a factory to construct the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to use an URLFetcher factory which will prevent access to www.example.com during the test. BUG=none TEST=sync_backend_host_unittest.cc Review URL: http://codereview.chromium.org/7053011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void HttpBridge::MakeAsynchronousPost() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); base::AutoLock lock(fetch_state_lock_); DCHECK(!fetch_state_.request_completed); if (fetch_state_.aborted) return; fetch_state_.url_poster = URLFetcher::Create(0, url_for_request_, URLFetcher::POST, this); fetch_state_.url_poster->set_request_context(context_getter_for_request_); fetch_state_.url_poster->set_upload_data(content_type_, request_content_); fetch_state_.url_poster->set_extra_request_headers(extra_headers_); fetch_state_.url_poster->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES); fetch_state_.url_poster->Start(); }
6,298
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { get_page(buf->page); } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
void generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { return try_get_page(buf->page); }
10,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void RTCPeerConnectionHandlerChromium::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription) { if (!m_webHandler) return; m_webHandler->setRemoteDescription(request, sessionDescription); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
void RTCPeerConnectionHandlerChromium::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription)
27,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int _snd_timer_stop(struct snd_timer_instance * timeri, int keep_flag, int event) { struct snd_timer *timer; unsigned long flags; if (snd_BUG_ON(!timeri)) return -ENXIO; if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) { if (!keep_flag) { spin_lock_irqsave(&slave_active_lock, flags); timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING; spin_unlock_irqrestore(&slave_active_lock, flags); } goto __end; } timer = timeri->timer; if (!timer) return -EINVAL; spin_lock_irqsave(&timer->lock, flags); list_del_init(&timeri->ack_list); list_del_init(&timeri->active_list); if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) && !(--timer->running)) { timer->hw.stop(timer); if (timer->flags & SNDRV_TIMER_FLG_RESCHED) { timer->flags &= ~SNDRV_TIMER_FLG_RESCHED; snd_timer_reschedule(timer, 0); if (timer->flags & SNDRV_TIMER_FLG_CHANGE) { timer->flags &= ~SNDRV_TIMER_FLG_CHANGE; timer->hw.start(timer); } } } if (!keep_flag) timeri->flags &= ~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START); spin_unlock_irqrestore(&timer->lock, flags); __end: if (event != SNDRV_TIMER_EVENT_RESOLUTION) snd_timer_notify1(timeri, event); return 0; } Commit Message: ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-20
static int _snd_timer_stop(struct snd_timer_instance * timeri, int keep_flag, int event) { struct snd_timer *timer; unsigned long flags; if (snd_BUG_ON(!timeri)) return -ENXIO; if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) { if (!keep_flag) { spin_lock_irqsave(&slave_active_lock, flags); timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING; list_del_init(&timeri->ack_list); list_del_init(&timeri->active_list); spin_unlock_irqrestore(&slave_active_lock, flags); } goto __end; } timer = timeri->timer; if (!timer) return -EINVAL; spin_lock_irqsave(&timer->lock, flags); list_del_init(&timeri->ack_list); list_del_init(&timeri->active_list); if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) && !(--timer->running)) { timer->hw.stop(timer); if (timer->flags & SNDRV_TIMER_FLG_RESCHED) { timer->flags &= ~SNDRV_TIMER_FLG_RESCHED; snd_timer_reschedule(timer, 0); if (timer->flags & SNDRV_TIMER_FLG_CHANGE) { timer->flags &= ~SNDRV_TIMER_FLG_CHANGE; timer->hw.start(timer); } } } if (!keep_flag) timeri->flags &= ~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START); spin_unlock_irqrestore(&timer->lock, flags); __end: if (event != SNDRV_TIMER_EVENT_RESOLUTION) snd_timer_notify1(timeri, event); return 0; }
19,510
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; } Commit Message: Resolve a merge issue between lmp and lmp-mr1+ Change-Id: I336cb003fb7f50fd7d95c30ca47e45530a7ad503 (cherry picked from commit 33f6da1092834f1e4be199cfa3b6310d66b521c0) (cherry picked from commit bb3a0338b58fafb01ac5b34efc450b80747e71e4) CWE ID: CWE-119
status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsSecure && !audio && mVideoTrack.mSource != NULL) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; }
24,694
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void StreamingProcessor::releaseRecordingFrame(const sp<IMemory>& mem) { ATRACE_CALL(); status_t res; Mutex::Autolock m(mMutex); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); if (heap->getHeapID() != mRecordingHeap->mHeap->getHeapID()) { ALOGW("%s: Camera %d: Mismatched heap ID, ignoring release " "(got %x, expected %x)", __FUNCTION__, mId, heap->getHeapID(), mRecordingHeap->mHeap->getHeapID()); return; } VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); if (payload->eType != kMetadataBufferTypeANWBuffer) { ALOGE("%s: Camera %d: Recording frame type invalid (got %x, expected %x)", __FUNCTION__, mId, payload->eType, kMetadataBufferTypeANWBuffer); return; } size_t itemIndex; for (itemIndex = 0; itemIndex < mRecordingBuffers.size(); itemIndex++) { const BufferItem item = mRecordingBuffers[itemIndex]; if (item.mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT && item.mGraphicBuffer->getNativeBuffer() == payload->pBuffer) { break; } } if (itemIndex == mRecordingBuffers.size()) { ALOGE("%s: Camera %d: Can't find returned ANW Buffer %p in list of " "outstanding buffers", __FUNCTION__, mId, payload->pBuffer); return; } ALOGVV("%s: Camera %d: Freeing returned ANW buffer %p index %d", __FUNCTION__, mId, payload->pBuffer, itemIndex); res = mRecordingConsumer->releaseBuffer(mRecordingBuffers[itemIndex]); if (res != OK) { ALOGE("%s: Camera %d: Unable to free recording frame " "(Returned ANW buffer: %p): %s (%d)", __FUNCTION__, mId, payload->pBuffer, strerror(-res), res); return; } mRecordingBuffers.replaceAt(itemIndex); mRecordingHeapFree++; ALOGV_IF(mRecordingHeapFree == mRecordingHeapCount, "%s: Camera %d: All %d recording buffers returned", __FUNCTION__, mId, mRecordingHeapCount); } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200
void StreamingProcessor::releaseRecordingFrame(const sp<IMemory>& mem) { ATRACE_CALL(); status_t res; Mutex::Autolock m(mMutex); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); if (heap->getHeapID() != mRecordingHeap->mHeap->getHeapID()) { ALOGW("%s: Camera %d: Mismatched heap ID, ignoring release " "(got %x, expected %x)", __FUNCTION__, mId, heap->getHeapID(), mRecordingHeap->mHeap->getHeapID()); return; } VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); if (payload->eType != kMetadataBufferTypeANWBuffer) { ALOGE("%s: Camera %d: Recording frame type invalid (got %x, expected %x)", __FUNCTION__, mId, payload->eType, kMetadataBufferTypeANWBuffer); return; } // b/28466701 payload->pBuffer = (ANativeWindowBuffer*)(((uint8_t*)payload->pBuffer) + ICameraRecordingProxy::getCommonBaseAddress()); size_t itemIndex; for (itemIndex = 0; itemIndex < mRecordingBuffers.size(); itemIndex++) { const BufferItem item = mRecordingBuffers[itemIndex]; if (item.mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT && item.mGraphicBuffer->getNativeBuffer() == payload->pBuffer) { break; } } if (itemIndex == mRecordingBuffers.size()) { ALOGE("%s: Camera %d: Can't find returned ANW Buffer %p in list of " "outstanding buffers", __FUNCTION__, mId, payload->pBuffer); return; } ALOGVV("%s: Camera %d: Freeing returned ANW buffer %p index %d", __FUNCTION__, mId, payload->pBuffer, itemIndex); res = mRecordingConsumer->releaseBuffer(mRecordingBuffers[itemIndex]); if (res != OK) { ALOGE("%s: Camera %d: Unable to free recording frame " "(Returned ANW buffer: %p): %s (%d)", __FUNCTION__, mId, payload->pBuffer, strerror(-res), res); return; } mRecordingBuffers.replaceAt(itemIndex); mRecordingHeapFree++; ALOGV_IF(mRecordingHeapFree == mRecordingHeapCount, "%s: Camera %d: All %d recording buffers returned", __FUNCTION__, mId, mRecordingHeapCount); }
22,841
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void DataReductionProxyConfig::InitializeOnIOThread( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, WarmupURLFetcher::CreateCustomProxyConfigCallback create_custom_proxy_config_callback, NetworkPropertiesManager* manager) { DCHECK(thread_checker_.CalledOnValidThread()); network_properties_manager_ = manager; network_properties_manager_->ResetWarmupURLFetchMetrics(); secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory)); warmup_url_fetcher_.reset(new WarmupURLFetcher( url_loader_factory, create_custom_proxy_config_callback, base::BindRepeating( &DataReductionProxyConfig::HandleWarmupFetcherResponse, base::Unretained(this)), base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate, base::Unretained(this)), ui_task_runner_)); if (ShouldAddDefaultProxyBypassRules()) AddDefaultProxyBypassRules(); network_connection_tracker_->AddNetworkConnectionObserver(this); network_connection_tracker_->GetConnectionType( &connection_type_, base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged, weak_factory_.GetWeakPtr())); } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} CWE ID: CWE-20
void DataReductionProxyConfig::InitializeOnIOThread( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, WarmupURLFetcher::CreateCustomProxyConfigCallback create_custom_proxy_config_callback, NetworkPropertiesManager* manager) { DCHECK(thread_checker_.CalledOnValidThread()); network_properties_manager_ = manager; network_properties_manager_->ResetWarmupURLFetchMetrics(); secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory)); warmup_url_fetcher_.reset(new WarmupURLFetcher( url_loader_factory, create_custom_proxy_config_callback, base::BindRepeating( &DataReductionProxyConfig::HandleWarmupFetcherResponse, base::Unretained(this)), base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate, base::Unretained(this)), ui_task_runner_)); AddDefaultProxyBypassRules(); network_connection_tracker_->AddNetworkConnectionObserver(this); network_connection_tracker_->GetConnectionType( &connection_type_, base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged, weak_factory_.GetWeakPtr())); }
15,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::ListValue* val) const { v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize())); for (size_t i = 0; i < val->GetSize(); ++i) { const base::Value* child = NULL; CHECK(val->Get(i, &child)); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, child); CHECK(!child_v8.IsEmpty()); v8::TryCatch try_catch(isolate); result->Set(static_cast<uint32_t>(i), child_v8); if (try_catch.HasCaught()) LOG(ERROR) << "Setter for index " << i << " threw an exception."; } return result; } Commit Message: V8ValueConverter::ToV8Value should not trigger setters BUG=606390 Review URL: https://codereview.chromium.org/1918793003 Cr-Commit-Position: refs/heads/master@{#390045} CWE ID:
v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::ListValue* val) const { v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize())); // TODO(robwu): Callers should pass in the context. v8::Local<v8::Context> context = isolate->GetCurrentContext(); for (size_t i = 0; i < val->GetSize(); ++i) { const base::Value* child = NULL; CHECK(val->Get(i, &child)); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, child); CHECK(!child_v8.IsEmpty()); v8::Maybe<bool> maybe = result->CreateDataProperty(context, static_cast<uint32_t>(i), child_v8); if (!maybe.IsJust() || !maybe.FromJust()) LOG(ERROR) << "Failed to set value at index " << i; } return result; }
26,870
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void RenderFrameImpl::OnSelectPopupMenuItems( bool canceled, const std::vector<int>& selected_indices) { if (!external_popup_menu_) return; blink::WebScopedUserGesture gesture(frame_); external_popup_menu_->DidSelectItems(canceled, selected_indices); external_popup_menu_.reset(); } Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s) ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl. We need to reset external_popup_menu_ before calling it. Bug: 912211 Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc Reviewed-on: https://chromium-review.googlesource.com/c/1381325 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#618026} CWE ID: CWE-416
void RenderFrameImpl::OnSelectPopupMenuItems( bool canceled, const std::vector<int>& selected_indices) { if (!external_popup_menu_) return; blink::WebScopedUserGesture gesture(frame_); // We need to reset |external_popup_menu_| before calling DidSelectItems(), // which might delete |this|. // See ExternalPopupMenuRemoveTest.RemoveFrameOnChange std::unique_ptr<ExternalPopupMenu> popup; popup.swap(external_popup_menu_); popup->DidSelectItems(canceled, selected_indices); }
12,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */ return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <[email protected]> CWE ID: CWE-119
dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); }
28,603
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings) { rdpCredssp* credssp; credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp)); ZeroMemory(credssp, sizeof(rdpCredssp)); if (credssp != NULL) { HKEY hKey; LONG status; DWORD dwType; DWORD dwSize; credssp->instance = instance; credssp->settings = settings; credssp->server = settings->ServerMode; credssp->transport = transport; credssp->send_seq_num = 0; credssp->recv_seq_num = 0; ZeroMemory(&credssp->negoToken, sizeof(SecBuffer)); ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer)); ZeroMemory(&credssp->authInfo, sizeof(SecBuffer)); if (credssp->server) { status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize); if (status == ERROR_SUCCESS) { credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, (BYTE*) credssp->SspiModule, &dwSize); if (status == ERROR_SUCCESS) { _tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule); RegCloseKey(hKey); } } } } } return credssp; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings) { rdpCredssp* credssp; credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp)); ZeroMemory(credssp, sizeof(rdpCredssp)); if (credssp != NULL) { HKEY hKey; LONG status; DWORD dwType; DWORD dwSize; credssp->instance = instance; credssp->settings = settings; credssp->server = settings->ServerMode; credssp->transport = transport; credssp->send_seq_num = 0; credssp->recv_seq_num = 0; ZeroMemory(&credssp->negoToken, sizeof(SecBuffer)); ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer)); ZeroMemory(&credssp->authInfo, sizeof(SecBuffer)); SecInvalidateHandle(&credssp->context); if (credssp->server) { status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize); if (status == ERROR_SUCCESS) { credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, (BYTE*) credssp->SspiModule, &dwSize); if (status == ERROR_SUCCESS) { _tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule); RegCloseKey(hKey); } } } } } return credssp; }
27,513
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gint base64_len) { GstBuffer *img; guchar *img_data; gsize img_len; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; img_data = g_try_malloc0 (base64_len * 3 / 4); if (img_data == NULL) goto alloc_failed; img_len = g_base64_decode_step (img_data_base64, base64_len, img_data, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (img_data, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); g_free (img_data); return; /* ERRORS */ { GST_WARNING ("COVERART tag with too little base64-encoded data"); GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } alloc_failed: { GST_WARNING ("Couldn't allocate enough memory to decode COVERART tag"); return; } decode_failed: { GST_WARNING ("Couldn't decode bas64 image data from COVERART tag"); g_free (img_data); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); g_free (img_data); return; } } Commit Message: CWE ID: CWE-189
gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gst_vorbis_tag_add_coverart (GstTagList * tags, gchar * img_data_base64, gint base64_len) { GstBuffer *img; gsize img_len; guchar *out; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; /* img_data_base64 points to a temporary copy of the base64 encoded data, so * it's safe to do inpace decoding here * TODO: glib 2.20 and later provides g_base64_decode_inplace, so change this * to use glib's API instead once it's in wider use: * http://bugzilla.gnome.org/show_bug.cgi?id=564728 * http://svn.gnome.org/viewvc/glib?view=revision&revision=7807 */ out = (guchar *) img_data_base64; img_len = g_base64_decode_step (img_data_base64, base64_len, out, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (out, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); return; /* ERRORS */ { GST_WARNING ("COVERART tag with too little base64-encoded data"); GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } decode_failed: { GST_WARNING ("Couldn't decode base64 image data from COVERART tag"); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); return; } }
2,103
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void PeopleHandler::HandleSignout(const base::ListValue* args) { bool delete_profile = false; args->GetBoolean(0, &delete_profile); if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) { DCHECK(delete_profile); } else { SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_); if (signin_manager->IsAuthenticated()) { if (GetSyncService()) ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS); signin_metrics::SignoutDelete delete_metric = delete_profile ? signin_metrics::SignoutDelete::DELETED : signin_metrics::SignoutDelete::KEEPING; signin_manager->SignOutAndRemoveAllAccounts( signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric); } else { DCHECK(!delete_profile) << "Deleting the profile should only be offered the user is syncing."; ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) ->RevokeAllCredentials(); } } if (delete_profile) { webui::DeleteProfileAtPath(profile_->GetPath(), ProfileMetrics::DELETE_PROFILE_SETTINGS); } } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} CWE ID: CWE-20
void PeopleHandler::HandleSignout(const base::ListValue* args) { bool delete_profile = false; args->GetBoolean(0, &delete_profile); if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) { DCHECK(delete_profile); } else { SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_); if (signin_manager->IsAuthenticated()) { if (GetSyncService()) ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS); signin_metrics::SignoutDelete delete_metric = delete_profile ? signin_metrics::SignoutDelete::DELETED : signin_metrics::SignoutDelete::KEEPING; signin_manager->SignOutAndRemoveAllAccounts( signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric); } else { DCHECK(!delete_profile) << "Deleting the profile should only be offered the user is syncing."; ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) ->RevokeAllCredentials( signin_metrics::SourceForRefreshTokenOperation:: kSettings_Signout); } } if (delete_profile) { webui::DeleteProfileAtPath(profile_->GetPath(), ProfileMetrics::DELETE_PROFILE_SETTINGS); } }
29,597
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') separator = *src++; /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); } Commit Message: Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option This fixes a directory traversal in the cpio tool. CWE ID: CWE-22
cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path is absolute"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); }
29,771
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { freerdp_peer* client = (freerdp_peer*) extra; rdpRdp* rdp = client->context->rdp; switch (rdp->state) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) return -1; if (rdp->nego->selected_protocol & PROTOCOL_NLA) { sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity)); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); credssp_free(rdp->nego->transport->credssp); } else { IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE); } break; case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (rdp->settings->DisableEncryption) { if (!rdp_server_accept_client_keys(rdp, s)) return -1; break; } rdp->state = CONNECTION_STATE_ESTABLISH_KEYS; /* FALLTHROUGH */ case CONNECTION_STATE_ESTABLISH_KEYS: if (!rdp_server_accept_client_info(rdp, s)) return -1; IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) return -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_server_accept_confirm_active(rdp, s)) { /** * During reactivation sequence the client might sent some input or channel data * before receiving the Deactivate All PDU. We need to process them as usual. */ Stream_SetPosition(s, 0); return peer_recv_pdu(client, s); } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) return -1; break; default: fprintf(stderr, "Invalid state %d\n", rdp->state); return -1; } return 0; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { freerdp_peer* client = (freerdp_peer*) extra; rdpRdp* rdp = client->context->rdp; switch (rdp->state) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) return -1; if (rdp->nego->selected_protocol & PROTOCOL_NLA) { sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity)); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); credssp_free(rdp->nego->transport->credssp); rdp->nego->transport->credssp = NULL; } else { IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE); } break; case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (rdp->settings->DisableEncryption) { if (!rdp_server_accept_client_keys(rdp, s)) return -1; break; } rdp->state = CONNECTION_STATE_ESTABLISH_KEYS; /* FALLTHROUGH */ case CONNECTION_STATE_ESTABLISH_KEYS: if (!rdp_server_accept_client_info(rdp, s)) return -1; IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) return -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_server_accept_confirm_active(rdp, s)) { /** * During reactivation sequence the client might sent some input or channel data * before receiving the Deactivate All PDU. We need to process them as usual. */ Stream_SetPosition(s, 0); return peer_recv_pdu(client, s); } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) return -1; break; default: fprintf(stderr, "Invalid state %d\n", rdp->state); return -1; } return 0; }
7,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int x86_emulate_insn(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; int rc = X86EMUL_CONTINUE; int saved_dst_type = ctxt->dst.type; ctxt->mem_read.pos = 0; /* LOCK prefix is allowed only with some instructions */ if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) { rc = emulate_ud(ctxt); goto done; } if (unlikely(ctxt->d & (No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) { if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) || (ctxt->d & Undefined)) { rc = emulate_ud(ctxt); goto done; } if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM))) || ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) { rc = emulate_nm(ctxt); goto done; } if (ctxt->d & Mmx) { rc = flush_pending_x87_faults(ctxt); if (rc != X86EMUL_CONTINUE) goto done; /* * Now that we know the fpu is exception safe, we can fetch * operands from it. */ fetch_possible_mmx_operand(ctxt, &ctxt->src); fetch_possible_mmx_operand(ctxt, &ctxt->src2); if (!(ctxt->d & Mov)) fetch_possible_mmx_operand(ctxt, &ctxt->dst); } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_PRE_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } /* Privileged instruction can be executed only in CPL=0 */ if ((ctxt->d & Priv) && ops->cpl(ctxt)) { if (ctxt->d & PrivUD) rc = emulate_ud(ctxt); else rc = emulate_gp(ctxt, 0); goto done; } /* Instruction can only be executed in protected mode */ if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) { rc = emulate_ud(ctxt); goto done; } /* Do instruction specific permission checks */ if (ctxt->d & CheckPerm) { rc = ctxt->check_perm(ctxt); if (rc != X86EMUL_CONTINUE) goto done; } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) { /* All REP prefixes have the same first termination condition */ if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) { ctxt->eip = ctxt->_eip; ctxt->eflags &= ~EFLG_RF; goto done; } } } if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) { rc = segmented_read(ctxt, ctxt->src.addr.mem, ctxt->src.valptr, ctxt->src.bytes); if (rc != X86EMUL_CONTINUE) goto done; ctxt->src.orig_val64 = ctxt->src.val64; } if (ctxt->src2.type == OP_MEM) { rc = segmented_read(ctxt, ctxt->src2.addr.mem, &ctxt->src2.val, ctxt->src2.bytes); if (rc != X86EMUL_CONTINUE) goto done; } if ((ctxt->d & DstMask) == ImplicitOps) goto special_insn; if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) { /* optimisation - avoid slow emulated read if Mov */ rc = segmented_read(ctxt, ctxt->dst.addr.mem, &ctxt->dst.val, ctxt->dst.bytes); if (rc != X86EMUL_CONTINUE) goto done; } ctxt->dst.orig_val = ctxt->dst.val; special_insn: if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_MEMACCESS); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) ctxt->eflags |= EFLG_RF; else ctxt->eflags &= ~EFLG_RF; if (ctxt->execute) { if (ctxt->d & Fastop) { void (*fop)(struct fastop *) = (void *)ctxt->execute; rc = fastop(ctxt, fop); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } rc = ctxt->execute(ctxt); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } if (ctxt->opcode_len == 2) goto twobyte_insn; else if (ctxt->opcode_len == 3) goto threebyte_insn; switch (ctxt->b) { case 0x63: /* movsxd */ if (ctxt->mode != X86EMUL_MODE_PROT64) goto cannot_emulate; ctxt->dst.val = (s32) ctxt->src.val; break; case 0x70 ... 0x7f: /* jcc (short) */ if (test_cc(ctxt->b, ctxt->eflags)) jmp_rel(ctxt, ctxt->src.val); break; case 0x8d: /* lea r16/r32, m */ ctxt->dst.val = ctxt->src.addr.mem.ea; break; case 0x90 ... 0x97: /* nop / xchg reg, rax */ if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX)) ctxt->dst.type = OP_NONE; else rc = em_xchg(ctxt); break; case 0x98: /* cbw/cwde/cdqe */ switch (ctxt->op_bytes) { case 2: ctxt->dst.val = (s8)ctxt->dst.val; break; case 4: ctxt->dst.val = (s16)ctxt->dst.val; break; case 8: ctxt->dst.val = (s32)ctxt->dst.val; break; } break; case 0xcc: /* int3 */ rc = emulate_int(ctxt, 3); break; case 0xcd: /* int n */ rc = emulate_int(ctxt, ctxt->src.val); break; case 0xce: /* into */ if (ctxt->eflags & EFLG_OF) rc = emulate_int(ctxt, 4); break; case 0xe9: /* jmp rel */ case 0xeb: /* jmp rel short */ jmp_rel(ctxt, ctxt->src.val); ctxt->dst.type = OP_NONE; /* Disable writeback. */ break; case 0xf4: /* hlt */ ctxt->ops->halt(ctxt); break; case 0xf5: /* cmc */ /* complement carry flag from eflags reg */ ctxt->eflags ^= EFLG_CF; break; case 0xf8: /* clc */ ctxt->eflags &= ~EFLG_CF; break; case 0xf9: /* stc */ ctxt->eflags |= EFLG_CF; break; case 0xfc: /* cld */ ctxt->eflags &= ~EFLG_DF; break; case 0xfd: /* std */ ctxt->eflags |= EFLG_DF; break; default: goto cannot_emulate; } if (rc != X86EMUL_CONTINUE) goto done; writeback: if (ctxt->d & SrcWrite) { BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR); rc = writeback(ctxt, &ctxt->src); if (rc != X86EMUL_CONTINUE) goto done; } if (!(ctxt->d & NoWrite)) { rc = writeback(ctxt, &ctxt->dst); if (rc != X86EMUL_CONTINUE) goto done; } /* * restore dst type in case the decoding will be reused * (happens for string instruction ) */ ctxt->dst.type = saved_dst_type; if ((ctxt->d & SrcMask) == SrcSI) string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src); if ((ctxt->d & DstMask) == DstDI) string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst); if (ctxt->rep_prefix && (ctxt->d & String)) { unsigned int count; struct read_cache *r = &ctxt->io_read; if ((ctxt->d & SrcMask) == SrcSI) count = ctxt->src.count; else count = ctxt->dst.count; register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -count); if (!string_insn_completed(ctxt)) { /* * Re-enter guest when pio read ahead buffer is empty * or, if it is not used, after each 1024 iteration. */ if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) && (r->end == 0 || r->end != r->pos)) { /* * Reset read cache. Usually happens before * decode, but since instruction is restarted * we have to do it here. */ ctxt->mem_read.end = 0; writeback_registers(ctxt); return EMULATION_RESTART; } goto done; /* skip rip writeback */ } ctxt->eflags &= ~EFLG_RF; } ctxt->eip = ctxt->_eip; done: if (rc == X86EMUL_PROPAGATE_FAULT) { WARN_ON(ctxt->exception.vector > 0x1f); ctxt->have_exception = true; } if (rc == X86EMUL_INTERCEPTED) return EMULATION_INTERCEPTED; if (rc == X86EMUL_CONTINUE) writeback_registers(ctxt); return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK; twobyte_insn: switch (ctxt->b) { case 0x09: /* wbinvd */ (ctxt->ops->wbinvd)(ctxt); break; case 0x08: /* invd */ case 0x0d: /* GrpP (prefetch) */ case 0x18: /* Grp16 (prefetch/nop) */ case 0x1f: /* nop */ break; case 0x20: /* mov cr, reg */ ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg); break; case 0x21: /* mov from dr to reg */ ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val); break; case 0x40 ... 0x4f: /* cmov */ if (test_cc(ctxt->b, ctxt->eflags)) ctxt->dst.val = ctxt->src.val; else if (ctxt->mode != X86EMUL_MODE_PROT64 || ctxt->op_bytes != 4) ctxt->dst.type = OP_NONE; /* no writeback */ break; case 0x80 ... 0x8f: /* jnz rel, etc*/ if (test_cc(ctxt->b, ctxt->eflags)) jmp_rel(ctxt, ctxt->src.val); break; case 0x90 ... 0x9f: /* setcc r/m8 */ ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags); break; case 0xae: /* clflush */ break; case 0xb6 ... 0xb7: /* movzx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val : (u16) ctxt->src.val; break; case 0xbe ... 0xbf: /* movsx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val : (s16) ctxt->src.val; break; case 0xc3: /* movnti */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->op_bytes == 8) ? (u64) ctxt->src.val : (u32) ctxt->src.val; break; default: goto cannot_emulate; } threebyte_insn: if (rc != X86EMUL_CONTINUE) goto done; goto writeback; cannot_emulate: return EMULATION_FAILED; } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
int x86_emulate_insn(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; int rc = X86EMUL_CONTINUE; int saved_dst_type = ctxt->dst.type; ctxt->mem_read.pos = 0; /* LOCK prefix is allowed only with some instructions */ if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) { rc = emulate_ud(ctxt); goto done; } if (unlikely(ctxt->d & (No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) { if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) || (ctxt->d & Undefined)) { rc = emulate_ud(ctxt); goto done; } if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM))) || ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) { rc = emulate_nm(ctxt); goto done; } if (ctxt->d & Mmx) { rc = flush_pending_x87_faults(ctxt); if (rc != X86EMUL_CONTINUE) goto done; /* * Now that we know the fpu is exception safe, we can fetch * operands from it. */ fetch_possible_mmx_operand(ctxt, &ctxt->src); fetch_possible_mmx_operand(ctxt, &ctxt->src2); if (!(ctxt->d & Mov)) fetch_possible_mmx_operand(ctxt, &ctxt->dst); } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_PRE_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } /* Privileged instruction can be executed only in CPL=0 */ if ((ctxt->d & Priv) && ops->cpl(ctxt)) { if (ctxt->d & PrivUD) rc = emulate_ud(ctxt); else rc = emulate_gp(ctxt, 0); goto done; } /* Instruction can only be executed in protected mode */ if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) { rc = emulate_ud(ctxt); goto done; } /* Do instruction specific permission checks */ if (ctxt->d & CheckPerm) { rc = ctxt->check_perm(ctxt); if (rc != X86EMUL_CONTINUE) goto done; } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) { /* All REP prefixes have the same first termination condition */ if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) { ctxt->eip = ctxt->_eip; ctxt->eflags &= ~EFLG_RF; goto done; } } } if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) { rc = segmented_read(ctxt, ctxt->src.addr.mem, ctxt->src.valptr, ctxt->src.bytes); if (rc != X86EMUL_CONTINUE) goto done; ctxt->src.orig_val64 = ctxt->src.val64; } if (ctxt->src2.type == OP_MEM) { rc = segmented_read(ctxt, ctxt->src2.addr.mem, &ctxt->src2.val, ctxt->src2.bytes); if (rc != X86EMUL_CONTINUE) goto done; } if ((ctxt->d & DstMask) == ImplicitOps) goto special_insn; if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) { /* optimisation - avoid slow emulated read if Mov */ rc = segmented_read(ctxt, ctxt->dst.addr.mem, &ctxt->dst.val, ctxt->dst.bytes); if (rc != X86EMUL_CONTINUE) goto done; } ctxt->dst.orig_val = ctxt->dst.val; special_insn: if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_MEMACCESS); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) ctxt->eflags |= EFLG_RF; else ctxt->eflags &= ~EFLG_RF; if (ctxt->execute) { if (ctxt->d & Fastop) { void (*fop)(struct fastop *) = (void *)ctxt->execute; rc = fastop(ctxt, fop); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } rc = ctxt->execute(ctxt); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } if (ctxt->opcode_len == 2) goto twobyte_insn; else if (ctxt->opcode_len == 3) goto threebyte_insn; switch (ctxt->b) { case 0x63: /* movsxd */ if (ctxt->mode != X86EMUL_MODE_PROT64) goto cannot_emulate; ctxt->dst.val = (s32) ctxt->src.val; break; case 0x70 ... 0x7f: /* jcc (short) */ if (test_cc(ctxt->b, ctxt->eflags)) rc = jmp_rel(ctxt, ctxt->src.val); break; case 0x8d: /* lea r16/r32, m */ ctxt->dst.val = ctxt->src.addr.mem.ea; break; case 0x90 ... 0x97: /* nop / xchg reg, rax */ if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX)) ctxt->dst.type = OP_NONE; else rc = em_xchg(ctxt); break; case 0x98: /* cbw/cwde/cdqe */ switch (ctxt->op_bytes) { case 2: ctxt->dst.val = (s8)ctxt->dst.val; break; case 4: ctxt->dst.val = (s16)ctxt->dst.val; break; case 8: ctxt->dst.val = (s32)ctxt->dst.val; break; } break; case 0xcc: /* int3 */ rc = emulate_int(ctxt, 3); break; case 0xcd: /* int n */ rc = emulate_int(ctxt, ctxt->src.val); break; case 0xce: /* into */ if (ctxt->eflags & EFLG_OF) rc = emulate_int(ctxt, 4); break; case 0xe9: /* jmp rel */ case 0xeb: /* jmp rel short */ rc = jmp_rel(ctxt, ctxt->src.val); ctxt->dst.type = OP_NONE; /* Disable writeback. */ break; case 0xf4: /* hlt */ ctxt->ops->halt(ctxt); break; case 0xf5: /* cmc */ /* complement carry flag from eflags reg */ ctxt->eflags ^= EFLG_CF; break; case 0xf8: /* clc */ ctxt->eflags &= ~EFLG_CF; break; case 0xf9: /* stc */ ctxt->eflags |= EFLG_CF; break; case 0xfc: /* cld */ ctxt->eflags &= ~EFLG_DF; break; case 0xfd: /* std */ ctxt->eflags |= EFLG_DF; break; default: goto cannot_emulate; } if (rc != X86EMUL_CONTINUE) goto done; writeback: if (ctxt->d & SrcWrite) { BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR); rc = writeback(ctxt, &ctxt->src); if (rc != X86EMUL_CONTINUE) goto done; } if (!(ctxt->d & NoWrite)) { rc = writeback(ctxt, &ctxt->dst); if (rc != X86EMUL_CONTINUE) goto done; } /* * restore dst type in case the decoding will be reused * (happens for string instruction ) */ ctxt->dst.type = saved_dst_type; if ((ctxt->d & SrcMask) == SrcSI) string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src); if ((ctxt->d & DstMask) == DstDI) string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst); if (ctxt->rep_prefix && (ctxt->d & String)) { unsigned int count; struct read_cache *r = &ctxt->io_read; if ((ctxt->d & SrcMask) == SrcSI) count = ctxt->src.count; else count = ctxt->dst.count; register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -count); if (!string_insn_completed(ctxt)) { /* * Re-enter guest when pio read ahead buffer is empty * or, if it is not used, after each 1024 iteration. */ if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) && (r->end == 0 || r->end != r->pos)) { /* * Reset read cache. Usually happens before * decode, but since instruction is restarted * we have to do it here. */ ctxt->mem_read.end = 0; writeback_registers(ctxt); return EMULATION_RESTART; } goto done; /* skip rip writeback */ } ctxt->eflags &= ~EFLG_RF; } ctxt->eip = ctxt->_eip; done: if (rc == X86EMUL_PROPAGATE_FAULT) { WARN_ON(ctxt->exception.vector > 0x1f); ctxt->have_exception = true; } if (rc == X86EMUL_INTERCEPTED) return EMULATION_INTERCEPTED; if (rc == X86EMUL_CONTINUE) writeback_registers(ctxt); return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK; twobyte_insn: switch (ctxt->b) { case 0x09: /* wbinvd */ (ctxt->ops->wbinvd)(ctxt); break; case 0x08: /* invd */ case 0x0d: /* GrpP (prefetch) */ case 0x18: /* Grp16 (prefetch/nop) */ case 0x1f: /* nop */ break; case 0x20: /* mov cr, reg */ ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg); break; case 0x21: /* mov from dr to reg */ ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val); break; case 0x40 ... 0x4f: /* cmov */ if (test_cc(ctxt->b, ctxt->eflags)) ctxt->dst.val = ctxt->src.val; else if (ctxt->mode != X86EMUL_MODE_PROT64 || ctxt->op_bytes != 4) ctxt->dst.type = OP_NONE; /* no writeback */ break; case 0x80 ... 0x8f: /* jnz rel, etc*/ if (test_cc(ctxt->b, ctxt->eflags)) rc = jmp_rel(ctxt, ctxt->src.val); break; case 0x90 ... 0x9f: /* setcc r/m8 */ ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags); break; case 0xae: /* clflush */ break; case 0xb6 ... 0xb7: /* movzx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val : (u16) ctxt->src.val; break; case 0xbe ... 0xbf: /* movsx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val : (s16) ctxt->src.val; break; case 0xc3: /* movnti */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->op_bytes == 8) ? (u64) ctxt->src.val : (u32) ctxt->src.val; break; default: goto cannot_emulate; } threebyte_insn: if (rc != X86EMUL_CONTINUE) goto done; goto writeback; cannot_emulate: return EMULATION_FAILED; }
10,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_filesystem_object *intern; spl_filesystem_object *source; int index, skip_dots; old_object = zend_objects_get_address(zobject TSRMLS_CC); source = (spl_filesystem_object*)old_object; new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC); new_object = &intern->std; intern->flags = source->flags; switch (source->type) { case SPL_FS_INFO: intern->_path_len = source->_path_len; intern->_path = estrndup(source->_path, source->_path_len); intern->file_name_len = source->file_name_len; intern->file_name = estrndup(source->file_name, intern->file_name_len); break; case SPL_FS_DIR: spl_filesystem_dir_open(intern, source->_path TSRMLS_CC); /* read until we hit the position in which we were before */ skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS); for(index = 0; index < source->u.dir.index; ++index) { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } intern->u.dir.index = index; break; case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name); break; } intern->file_class = source->file_class; intern->info_class = source->info_class; intern->oth = source->oth; intern->oth_handler = source->oth_handler; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); if (intern->oth_handler && intern->oth_handler->clone) { intern->oth_handler->clone(source, intern TSRMLS_CC); } return new_obj_val; } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_filesystem_object *intern; spl_filesystem_object *source; int index, skip_dots; old_object = zend_objects_get_address(zobject TSRMLS_CC); source = (spl_filesystem_object*)old_object; new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC); new_object = &intern->std; intern->flags = source->flags; switch (source->type) { case SPL_FS_INFO: intern->_path_len = source->_path_len; intern->_path = estrndup(source->_path, source->_path_len); intern->file_name_len = source->file_name_len; intern->file_name = estrndup(source->file_name, intern->file_name_len); break; case SPL_FS_DIR: spl_filesystem_dir_open(intern, source->_path TSRMLS_CC); /* read until we hit the position in which we were before */ skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS); for(index = 0; index < source->u.dir.index; ++index) { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } intern->u.dir.index = index; break; case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name); break; } intern->file_class = source->file_class; intern->info_class = source->info_class; intern->oth = source->oth; intern->oth_handler = source->oth_handler; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); if (intern->oth_handler && intern->oth_handler->clone) { intern->oth_handler->clone(source, intern TSRMLS_CC); } return new_obj_val; }
28,916
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void RenderViewImpl::DidFocus() { WebFrame* main_frame = webview() ? webview()->MainFrame() : nullptr; bool is_processing_user_gesture = WebUserGestureIndicator::IsProcessingUserGesture( main_frame && main_frame->IsWebLocalFrame() ? main_frame->ToWebLocalFrame() : nullptr); if (is_processing_user_gesture && !RenderThreadImpl::current()->layout_test_mode()) { Send(new ViewHostMsg_Focus(GetRoutingID())); } } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID:
void RenderViewImpl::DidFocus() { void RenderViewImpl::DidFocus(blink::WebLocalFrame* calling_frame) { WebFrame* main_frame = webview() ? webview()->MainFrame() : nullptr; bool is_processing_user_gesture = WebUserGestureIndicator::IsProcessingUserGesture( main_frame && main_frame->IsWebLocalFrame() ? main_frame->ToWebLocalFrame() : nullptr); if (is_processing_user_gesture && !RenderThreadImpl::current()->layout_test_mode()) { Send(new ViewHostMsg_Focus(GetRoutingID())); // Tattle on the frame that called |window.focus()|. RenderFrameImpl* calling_render_frame = RenderFrameImpl::FromWebFrame(calling_frame); if (calling_render_frame) calling_render_frame->FrameDidCallFocus(); } }
4,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool ChangeInputMethodViaIBus(const std::string& input_method_id) { if (!initialized_successfully_) return false; std::string input_method_id_to_switch = input_method_id; if (!InputMethodIsActivated(input_method_id)) { scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); DCHECK(!input_methods->empty()); if (!input_methods->empty()) { input_method_id_to_switch = input_methods->at(0).id; LOG(INFO) << "Can't change the current input method to " << input_method_id << " since the engine is not preloaded. " << "Switch to " << input_method_id_to_switch << " instead."; } } if (chromeos::ChangeInputMethod(input_method_status_connection_, input_method_id_to_switch.c_str())) { return true; } LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch; return false; } 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
bool ChangeInputMethodViaIBus(const std::string& input_method_id) { if (!initialized_successfully_) return false; std::string input_method_id_to_switch = input_method_id; if (!InputMethodIsActivated(input_method_id)) { scoped_ptr<input_method::InputMethodDescriptors> input_methods( GetActiveInputMethods()); DCHECK(!input_methods->empty()); if (!input_methods->empty()) { input_method_id_to_switch = input_methods->at(0).id; LOG(INFO) << "Can't change the current input method to " << input_method_id << " since the engine is not preloaded. " << "Switch to " << input_method_id_to_switch << " instead."; } } if (ibus_controller_->ChangeInputMethod(input_method_id_to_switch)) { return true; } LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch; return false; }
3,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */ { char *cipher_dir_string; char *module_dir_string; int block_size, max_key_length, use_key_length, i, count, iv_size; unsigned long int data_size; int *key_length_sizes; char *key_s = NULL, *iv_s; char *data_s; MCRYPT td; MCRYPT_GET_INI td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } /* Checking for key-length */ max_key_length = mcrypt_enc_get_key_size(td); if (key_len > max_key_length) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm"); } key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count); if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */ use_key_length = key_len; key_s = emalloc(use_key_length); memset(key_s, 0, use_key_length); memcpy(key_s, key, use_key_length); } else if (count == 1) { /* only m_k_l = OK */ key_s = emalloc(key_length_sizes[0]); memset(key_s, 0, key_length_sizes[0]); memcpy(key_s, key, MIN(key_len, key_length_sizes[0])); use_key_length = key_length_sizes[0]; } else { /* dertermine smallest supported key > length of requested key */ use_key_length = max_key_length; /* start with max key length */ for (i = 0; i < count; i++) { if (key_length_sizes[i] >= key_len && key_length_sizes[i] < use_key_length) { use_key_length = key_length_sizes[i]; } } key_s = emalloc(use_key_length); memset(key_s, 0, use_key_length); memcpy(key_s, key, MIN(key_len, use_key_length)); } mcrypt_free (key_length_sizes); /* Check IV */ iv_s = NULL; iv_size = mcrypt_enc_get_iv_size (td); /* IV is required */ if (mcrypt_enc_mode_has_iv(td) == 1) { if (argc == 5) { if (iv_size != iv_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE); } else { iv_s = emalloc(iv_size + 1); memcpy(iv_s, iv, iv_size); } } else if (argc == 4) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend"); iv_s = emalloc(iv_size + 1); memset(iv_s, 0, iv_size + 1); } } /* Check blocksize */ if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed"); RETURN_FALSE; } if (dencrypt == MCRYPT_ENCRYPT) { mcrypt_generic(td, data_s, data_size); } else { mdecrypt_generic(td, data_s, data_size); } RETVAL_STRINGL(data_s, data_size, 1); /* freeing vars */ mcrypt_generic_end(td); if (key_s != NULL) { efree (key_s); } if (iv_s != NULL) { efree (iv_s); } efree (data_s); } /* }}} */ Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */ { char *cipher_dir_string; char *module_dir_string; int block_size, max_key_length, use_key_length, i, count, iv_size; unsigned long int data_size; int *key_length_sizes; char *key_s = NULL, *iv_s; char *data_s; MCRYPT td; MCRYPT_GET_INI td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } /* Checking for key-length */ max_key_length = mcrypt_enc_get_key_size(td); if (key_len > max_key_length) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm"); } key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count); if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */ use_key_length = key_len; key_s = emalloc(use_key_length); memset(key_s, 0, use_key_length); memcpy(key_s, key, use_key_length); } else if (count == 1) { /* only m_k_l = OK */ key_s = emalloc(key_length_sizes[0]); memset(key_s, 0, key_length_sizes[0]); memcpy(key_s, key, MIN(key_len, key_length_sizes[0])); use_key_length = key_length_sizes[0]; } else { /* dertermine smallest supported key > length of requested key */ use_key_length = max_key_length; /* start with max key length */ for (i = 0; i < count; i++) { if (key_length_sizes[i] >= key_len && key_length_sizes[i] < use_key_length) { use_key_length = key_length_sizes[i]; } } key_s = emalloc(use_key_length); memset(key_s, 0, use_key_length); memcpy(key_s, key, MIN(key_len, use_key_length)); } mcrypt_free (key_length_sizes); /* Check IV */ iv_s = NULL; iv_size = mcrypt_enc_get_iv_size (td); /* IV is required */ if (mcrypt_enc_mode_has_iv(td) == 1) { if (argc == 5) { if (iv_size != iv_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE); } else { iv_s = emalloc(iv_size + 1); memcpy(iv_s, iv, iv_size); } } else if (argc == 4) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend"); iv_s = emalloc(iv_size + 1); memset(iv_s, 0, iv_size + 1); } } /* Check blocksize */ if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed"); RETURN_FALSE; } if (dencrypt == MCRYPT_ENCRYPT) { mcrypt_generic(td, data_s, data_size); } else { mdecrypt_generic(td, data_s, data_size); } RETVAL_STRINGL(data_s, data_size, 1); /* freeing vars */ mcrypt_generic_end(td); if (key_s != NULL) { efree (key_s); } if (iv_s != NULL) { efree (iv_s); } efree (data_s); } /* }}} */
1,540
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() { return &shutdown_event_; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() {
22,996
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void PushMessagingServiceImpl::DidHandleMessage( const std::string& app_id, const base::Closure& message_handled_closure) { auto in_flight_iterator = in_flight_message_deliveries_.find(app_id); DCHECK(in_flight_iterator != in_flight_message_deliveries_.end()); in_flight_message_deliveries_.erase(in_flight_iterator); #if BUILDFLAG(ENABLE_BACKGROUND) if (in_flight_message_deliveries_.empty()) in_flight_keep_alive_.reset(); #endif message_handled_closure.Run(); if (push_messaging_service_observer_) push_messaging_service_observer_->OnMessageHandled(); } Commit Message: Remove some senseless indirection from the Push API code Four files to call one Java function. Let's just call it directly. BUG= Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6 Reviewed-on: https://chromium-review.googlesource.com/749147 Reviewed-by: Anita Woodruff <[email protected]> Commit-Queue: Peter Beverloo <[email protected]> Cr-Commit-Position: refs/heads/master@{#513464} CWE ID: CWE-119
void PushMessagingServiceImpl::DidHandleMessage( const std::string& app_id, const base::Closure& message_handled_closure) { auto in_flight_iterator = in_flight_message_deliveries_.find(app_id); DCHECK(in_flight_iterator != in_flight_message_deliveries_.end()); in_flight_message_deliveries_.erase(in_flight_iterator); #if BUILDFLAG(ENABLE_BACKGROUND) if (in_flight_message_deliveries_.empty()) in_flight_keep_alive_.reset(); #endif message_handled_closure.Run(); #if defined(OS_ANDROID) chrome::android::Java_PushMessagingServiceObserver_onMessageHandled( base::android::AttachCurrentThread()); #endif }
875
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) { WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); if (frame) { WebDataSource* data_source = frame->dataSource(); if (data_source) { DocumentState* document_state = DocumentState::FromDataSource(data_source); v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Object> load_times = v8::Object::New(isolate); load_times->Set( v8::String::NewFromUtf8(isolate, "requestTime"), v8::Number::New(isolate, document_state->request_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "startLoadTime"), v8::Number::New(isolate, document_state->start_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "commitLoadTime"), v8::Number::New(isolate, document_state->commit_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"), v8::Number::New( isolate, document_state->finish_document_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "finishLoadTime"), v8::Number::New(isolate, document_state->finish_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "firstPaintTime"), v8::Number::New(isolate, document_state->first_paint_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"), v8::Number::New( isolate, document_state->first_paint_after_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "navigationType"), v8::String::NewFromUtf8( isolate, GetNavigationType(data_source->navigationType()))); load_times->Set( v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"), v8::Boolean::New(isolate, document_state->was_fetched_via_spdy())); load_times->Set( v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"), v8::Boolean::New(isolate, document_state->was_npn_negotiated())); load_times->Set( v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"), v8::String::NewFromUtf8( isolate, document_state->npn_negotiated_protocol().c_str())); load_times->Set( v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"), v8::Boolean::New( isolate, document_state->was_alternate_protocol_available())); load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"), v8::String::NewFromUtf8( isolate, net::HttpResponseInfo::ConnectionInfoToString( document_state->connection_info()).c_str())); args.GetReturnValue().Set(load_times); return; } } args.GetReturnValue().SetNull(); } Commit Message: Cache all chrome.loadTimes info before passing them to setters. The setters can invalidate the pointers frame, data_source and document_state. BUG=549251 Review URL: https://codereview.chromium.org/1422753007 Cr-Commit-Position: refs/heads/master@{#357201} CWE ID:
static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) { WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); if (!frame) { args.GetReturnValue().SetNull(); return; } WebDataSource* data_source = frame->dataSource(); if (!data_source) { args.GetReturnValue().SetNull(); return; } DocumentState* document_state = DocumentState::FromDataSource(data_source); if (!document_state) { args.GetReturnValue().SetNull(); return; } double request_time = document_state->request_time().ToDoubleT(); double start_load_time = document_state->start_load_time().ToDoubleT(); double commit_load_time = document_state->commit_load_time().ToDoubleT(); double finish_document_load_time = document_state->finish_document_load_time().ToDoubleT(); double finish_load_time = document_state->finish_load_time().ToDoubleT(); double first_paint_time = document_state->first_paint_time().ToDoubleT(); double first_paint_after_load_time = document_state->first_paint_after_load_time().ToDoubleT(); std::string navigation_type = GetNavigationType(data_source->navigationType()); bool was_fetched_via_spdy = document_state->was_fetched_via_spdy(); bool was_npn_negotiated = document_state->was_npn_negotiated(); std::string npn_negotiated_protocol = document_state->npn_negotiated_protocol(); bool was_alternate_protocol_available = document_state->was_alternate_protocol_available(); std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString( document_state->connection_info()); // Important: |frame|, |data_source| and |document_state| should not be // referred to below this line, as JS setters below can invalidate these // pointers. v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Object> load_times = v8::Object::New(isolate); load_times->Set(v8::String::NewFromUtf8(isolate, "requestTime"), v8::Number::New(isolate, request_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "startLoadTime"), v8::Number::New(isolate, start_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "commitLoadTime"), v8::Number::New(isolate, commit_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"), v8::Number::New(isolate, finish_document_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "finishLoadTime"), v8::Number::New(isolate, finish_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintTime"), v8::Number::New(isolate, first_paint_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"), v8::Number::New(isolate, first_paint_after_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "navigationType"), v8::String::NewFromUtf8(isolate, navigation_type.c_str())); load_times->Set(v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"), v8::Boolean::New(isolate, was_fetched_via_spdy)); load_times->Set(v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"), v8::Boolean::New(isolate, was_npn_negotiated)); load_times->Set( v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"), v8::String::NewFromUtf8(isolate, npn_negotiated_protocol.c_str())); load_times->Set( v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"), v8::Boolean::New(isolate, was_alternate_protocol_available)); load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"), v8::String::NewFromUtf8(isolate, connection_info.c_str())); args.GetReturnValue().Set(load_times); }
21,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (is_swapped_out_) { if (request.url() != GURL("about:swappedout")) return WebKit::WebNavigationPolicyIgnore; return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (frame_url.GetOrigin() != url.GetOrigin()) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_top_level_requests = renderer_preferences_.browser_handles_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (browser_handles_top_level_requests || renderer_preferences_.browser_handles_all_requests) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool should_fork = content::GetContentClient()->HasWebUIScheme(url) || (cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || frame->isViewSourceModeEnabled(); if (!should_fork) { if (request.httpMethod() == "GET") { bool is_initial_navigation = page_id_ == -1; should_fork = content::GetContentClient()->renderer()->ShouldFork( frame, url, is_initial_navigation, &send_referrer); } } if (should_fork) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; } Commit Message: Use a new scheme for swapping out RenderViews. BUG=118664 TEST=none Review URL: http://codereview.chromium.org/9720004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (is_swapped_out_) { if (request.url() != GURL(chrome::kSwappedOutURL)) return WebKit::WebNavigationPolicyIgnore; // Allow chrome::kSwappedOutURL to complete. return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (frame_url.GetOrigin() != url.GetOrigin()) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_top_level_requests = renderer_preferences_.browser_handles_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (browser_handles_top_level_requests || renderer_preferences_.browser_handles_all_requests) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool should_fork = content::GetContentClient()->HasWebUIScheme(url) || (cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || frame->isViewSourceModeEnabled(); if (!should_fork) { if (request.httpMethod() == "GET") { bool is_initial_navigation = page_id_ == -1; should_fork = content::GetContentClient()->renderer()->ShouldFork( frame, url, is_initial_navigation, &send_referrer); } } if (should_fork) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; }
27,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool Cluster::EOS() const //// long long element_size) { return (m_pSegment == NULL); } 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
bool Cluster::EOS() const pEntry = NULL; if (index < 0) return -1; // generic error if (m_entries_count < 0) return E_BUFFER_NOT_FULL; assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (index < m_entries_count) { pEntry = m_entries[index]; assert(pEntry); return 1; // found entry } if (m_element_size < 0) // we don't know cluster end yet return E_BUFFER_NOT_FULL; // underflow const long long element_stop = m_element_start + m_element_size; if (m_pos >= element_stop) return 0; // nothing left to parse return E_BUFFER_NOT_FULL; // underflow, since more remains to be parsed } Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) //// long long element_size) { assert(pSegment); assert(off >= 0); const long long element_start = pSegment->m_start + off; Cluster* const pCluster = new Cluster(pSegment, idx, element_start); // element_size); assert(pCluster); return pCluster; }
14,820
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: begin_softmask(fz_context *ctx, pdf_run_processor *pr, softmask_save *save) { pdf_gstate *gstate = pr->gstate + pr->gtop; pdf_xobject *softmask = gstate->softmask; fz_rect mask_bbox; fz_matrix tos_save[2], save_ctm; fz_matrix mask_matrix; fz_colorspace *mask_colorspace; save->softmask = softmask; if (softmask == NULL) return gstate; save->page_resources = gstate->softmask_resources; save->ctm = gstate->softmask_ctm; save_ctm = gstate->ctm; pdf_xobject_bbox(ctx, softmask, &mask_bbox); pdf_xobject_matrix(ctx, softmask, &mask_matrix); pdf_tos_save(ctx, &pr->tos, tos_save); if (gstate->luminosity) mask_bbox = fz_infinite_rect; else { fz_transform_rect(&mask_bbox, &mask_matrix); fz_transform_rect(&mask_bbox, &gstate->softmask_ctm); } gstate->softmask = NULL; gstate->softmask_resources = NULL; gstate->ctm = gstate->softmask_ctm; mask_colorspace = pdf_xobject_colorspace(ctx, softmask); if (gstate->luminosity && !mask_colorspace) mask_colorspace = fz_device_gray(ctx); fz_try(ctx) { fz_begin_mask(ctx, pr->dev, &mask_bbox, gstate->luminosity, mask_colorspace, gstate->softmask_bc, &gstate->fill.color_params); pdf_run_xobject(ctx, pr, softmask, save->page_resources, &fz_identity, 1); } fz_always(ctx) fz_drop_colorspace(ctx, mask_colorspace); fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); /* FIXME: Ignore error - nasty, but if we throw from * here the clip stack would be messed up. */ /* TODO: pass cookie here to increase the cookie error count */ } fz_end_mask(ctx, pr->dev); pdf_tos_restore(ctx, &pr->tos, tos_save); gstate = pr->gstate + pr->gtop; gstate->ctm = save_ctm; return gstate; } Commit Message: CWE ID: CWE-416
begin_softmask(fz_context *ctx, pdf_run_processor *pr, softmask_save *save) { pdf_gstate *gstate = pr->gstate + pr->gtop; pdf_xobject *softmask = gstate->softmask; fz_rect mask_bbox; fz_matrix tos_save[2], save_ctm; fz_matrix mask_matrix; fz_colorspace *mask_colorspace; save->softmask = softmask; if (softmask == NULL) return gstate; save->page_resources = gstate->softmask_resources; save->ctm = gstate->softmask_ctm; save_ctm = gstate->ctm; pdf_xobject_bbox(ctx, softmask, &mask_bbox); pdf_xobject_matrix(ctx, softmask, &mask_matrix); pdf_tos_save(ctx, &pr->tos, tos_save); if (gstate->luminosity) mask_bbox = fz_infinite_rect; else { fz_transform_rect(&mask_bbox, &mask_matrix); fz_transform_rect(&mask_bbox, &gstate->softmask_ctm); } gstate->softmask = NULL; gstate->softmask_resources = NULL; gstate->ctm = gstate->softmask_ctm; mask_colorspace = pdf_xobject_colorspace(ctx, softmask); if (gstate->luminosity && !mask_colorspace) mask_colorspace = fz_keep_colorspace(ctx, fz_device_gray(ctx)); fz_try(ctx) { fz_begin_mask(ctx, pr->dev, &mask_bbox, gstate->luminosity, mask_colorspace, gstate->softmask_bc, &gstate->fill.color_params); pdf_run_xobject(ctx, pr, softmask, save->page_resources, &fz_identity, 1); } fz_always(ctx) fz_drop_colorspace(ctx, mask_colorspace); fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); /* FIXME: Ignore error - nasty, but if we throw from * here the clip stack would be messed up. */ /* TODO: pass cookie here to increase the cookie error count */ } fz_end_mask(ctx, pr->dev); pdf_tos_restore(ctx, &pr->tos, tos_save); gstate = pr->gstate + pr->gtop; gstate->ctm = save_ctm; return gstate; }
6,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: SiteInstanceTest() : ui_thread_(BrowserThread::UI, &message_loop_), old_browser_client_(NULL) { } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
SiteInstanceTest() : ui_thread_(BrowserThread::UI, &message_loop_), old_client_(NULL), old_browser_client_(NULL) { }
22,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { Stream_SetPosition(s, fields->BufferOffset); Stream_Write(s, fields->Buffer, fields->Len); } } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) static void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { Stream_SetPosition(s, fields->BufferOffset); Stream_Write(s, fields->Buffer, fields->Len); } }
9,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: NetworkThrottleManagerImpl::NetworkThrottleManagerImpl() : lifetime_median_estimate_(PercentileEstimator::kMedianPercentile, kInitialMedianInMs), outstanding_recomputation_timer_( base::MakeUnique<base::Timer>(false /* retain_user_task */, false /* is_repeating */)), tick_clock_(new base::DefaultTickClock()), weak_ptr_factory_(this) {} Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Bence Béky <[email protected]> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
NetworkThrottleManagerImpl::NetworkThrottleManagerImpl() : lifetime_median_estimate_(PercentileEstimator::kMedianPercentile, kInitialMedianInMs), outstanding_recomputation_timer_( std::make_unique<base::Timer>(false /* retain_user_task */, false /* is_repeating */)), tick_clock_(new base::DefaultTickClock()), weak_ptr_factory_(this) {}
28,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void UpdateProperty(IBusProperty* ibus_prop) { DLOG(INFO) << "UpdateProperty"; DCHECK(ibus_prop); ImePropertyList prop_list; // our representation. if (!FlattenProperty(ibus_prop, &prop_list)) { LOG(ERROR) << "Malformed properties are detected"; return; } if (!prop_list.empty()) { update_ime_property_(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 UpdateProperty(IBusProperty* ibus_prop) { FOR_EACH_OBSERVER(Observer, observers_, OnRegisterImeProperties(prop_list)); }
26,143
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int Equalizer_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int bMute = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; int32_t param2; char *name; switch (param) { case EQ_PARAM_NUM_BANDS: case EQ_PARAM_CUR_PRESET: case EQ_PARAM_GET_NUM_OF_PRESETS: case EQ_PARAM_BAND_LEVEL: case EQ_PARAM_GET_BAND: if (*pValueSize < sizeof(int16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; case EQ_PARAM_LEVEL_RANGE: if (*pValueSize < 2 * sizeof(int16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 2 %d", *pValueSize); return -EINVAL; } *pValueSize = 2 * sizeof(int16_t); break; case EQ_PARAM_BAND_FREQ_RANGE: if (*pValueSize < 2 * sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 3 %d", *pValueSize); return -EINVAL; } *pValueSize = 2 * sizeof(int32_t); break; case EQ_PARAM_CENTER_FREQ: if (*pValueSize < sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 5 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int32_t); break; case EQ_PARAM_GET_PRESET_NAME: break; case EQ_PARAM_PROPERTIES: if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t); break; default: ALOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param); return -EINVAL; } switch (param) { case EQ_PARAM_NUM_BANDS: *(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS; break; case EQ_PARAM_LEVEL_RANGE: *(int16_t *)pValue = -1500; *((int16_t *)pValue + 1) = 1500; break; case EQ_PARAM_BAND_LEVEL: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32438598"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_LEVEL band %d", param2); } break; } *(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2); break; case EQ_PARAM_CENTER_FREQ: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32436341"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_CENTER_FREQ band %d", param2); } break; } *(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2); break; case EQ_PARAM_BAND_FREQ_RANGE: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32247948"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_FREQ_RANGE band %d", param2); } break; } EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1)); break; case EQ_PARAM_GET_BAND: param2 = *pParamTemp; *(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2); break; case EQ_PARAM_CUR_PRESET: *(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext); break; case EQ_PARAM_GET_NUM_OF_PRESETS: *(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets(); break; case EQ_PARAM_GET_PRESET_NAME: param2 = *pParamTemp; if (param2 >= EqualizerGetNumPresets()) { status = -EINVAL; break; } name = (char *)pValue; strncpy(name, EqualizerGetPresetName(param2), *pValueSize - 1); name[*pValueSize - 1] = 0; *pValueSize = strlen(name) + 1; break; case EQ_PARAM_PROPERTIES: { int16_t *p = (int16_t *)pValue; ALOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES"); p[0] = (int16_t)EqualizerGetPreset(pContext); p[1] = (int16_t)FIVEBAND_NUMBANDS; for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i); } } break; default: ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Equalizer_getParameter */ int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){ int status = 0; int32_t preset; int32_t band; int32_t level; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; switch (param) { case EQ_PARAM_CUR_PRESET: preset = (int32_t)(*(uint16_t *)pValue); if ((preset >= EqualizerGetNumPresets())||(preset < 0)) { status = -EINVAL; break; } EqualizerSetPreset(pContext, preset); break; case EQ_PARAM_BAND_LEVEL: band = *pParamTemp; level = (int32_t)(*(int16_t *)pValue); if (band >= FIVEBAND_NUMBANDS) { status = -EINVAL; break; } EqualizerSetBandLevel(pContext, band, level); break; case EQ_PARAM_PROPERTIES: { int16_t *p = (int16_t *)pValue; if ((int)p[0] >= EqualizerGetNumPresets()) { status = -EINVAL; break; } if (p[0] >= 0) { EqualizerSetPreset(pContext, (int)p[0]); } else { if ((int)p[1] != FIVEBAND_NUMBANDS) { status = -EINVAL; break; } for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { EqualizerSetBandLevel(pContext, i, (int)p[2 + i]); } } } break; default: ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Equalizer_setParameter */ int Volume_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int bMute = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++;; char *name; switch (param){ case VOLUME_PARAM_LEVEL: case VOLUME_PARAM_MAXLEVEL: case VOLUME_PARAM_STEREOPOSITION: if (*pValueSize != sizeof(int16_t)){ ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; case VOLUME_PARAM_MUTE: case VOLUME_PARAM_ENABLESTEREOPOSITION: if (*pValueSize < sizeof(int32_t)){ ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 2 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int32_t); break; default: ALOGV("\tLVM_ERROR : Volume_getParameter unknown param %d", param); return -EINVAL; } switch (param){ case VOLUME_PARAM_LEVEL: status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue)); break; case VOLUME_PARAM_MAXLEVEL: *(int16_t *)pValue = 0; break; case VOLUME_PARAM_STEREOPOSITION: VolumeGetStereoPosition(pContext, (int16_t *)pValue); break; case VOLUME_PARAM_MUTE: status = VolumeGetMute(pContext, (uint32_t *)pValue); ALOGV("\tVolume_getParameter() VOLUME_PARAM_MUTE Value is %d", *(uint32_t *)pValue); break; case VOLUME_PARAM_ENABLESTEREOPOSITION: *(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled; break; default: ALOGV("\tLVM_ERROR : Volume_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Volume_getParameter */ int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){ int status = 0; int16_t level; int16_t position; uint32_t mute; uint32_t positionEnabled; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; switch (param){ case VOLUME_PARAM_LEVEL: level = *(int16_t *)pValue; status = VolumeSetVolumeLevel(pContext, (int16_t)level); break; case VOLUME_PARAM_MUTE: mute = *(uint32_t *)pValue; status = VolumeSetMute(pContext, mute); break; case VOLUME_PARAM_ENABLESTEREOPOSITION: positionEnabled = *(uint32_t *)pValue; status = VolumeEnableStereoPosition(pContext, positionEnabled); status = VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved); break; case VOLUME_PARAM_STEREOPOSITION: position = *(int16_t *)pValue; status = VolumeSetStereoPosition(pContext, (int16_t)position); break; default: ALOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param); break; } return status; } /* end Volume_setParameter */ /**************************************************************************************** * Name : LVC_ToDB_s32Tos16() * Input : Signed 32-bit integer * Output : Signed 16-bit integer * MSB (16) = sign bit * (15->05) = integer part * (04->01) = decimal part * Returns : Db value with respect to full scale * Description : * Remarks : ****************************************************************************************/ LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix) { LVM_INT16 db_fix; LVM_INT16 Shift; LVM_INT16 SmallRemainder; LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix; /* Count leading bits, 1 cycle in assembly*/ for (Shift = 0; Shift<32; Shift++) { if ((Remainder & 0x80000000U)!=0) { break; } Remainder = Remainder << 1; } /* * Based on the approximation equation (for Q11.4 format): * * dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2) */ db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/ SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24); db_fix = (LVM_INT16)(db_fix + SmallRemainder ); SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder); db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9)); /* Correct for small offset */ db_fix = (LVM_INT16)(db_fix - 5); return db_fix; } int Effect_setEnabled(EffectContext *pContext, bool enabled) { ALOGV("\tEffect_setEnabled() type %d, enabled %d", pContext->EffectType, enabled); if (enabled) { bool tempDisabled = false; switch (pContext->EffectType) { case LVM_BASS_BOOST: if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountBb <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountBb = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bBassEnabled = LVM_TRUE; tempDisabled = pContext->pBundledContext->bBassTempDisabled; break; case LVM_EQUALIZER: if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountEq <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountEq = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE; break; case LVM_VIRTUALIZER: if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountVirt = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE; tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled; break; case LVM_VOLUME: if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled"); return -EINVAL; } pContext->pBundledContext->NumberEffectsEnabled++; pContext->pBundledContext->bVolumeEnabled = LVM_TRUE; break; default: ALOGV("\tEffect_setEnabled() invalid effect type"); return -EINVAL; } if (!tempDisabled) { LvmEffect_enable(pContext); } } else { switch (pContext->EffectType) { case LVM_BASS_BOOST: if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled"); return -EINVAL; } pContext->pBundledContext->bBassEnabled = LVM_FALSE; break; case LVM_EQUALIZER: if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled"); return -EINVAL; } pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE; break; case LVM_VIRTUALIZER: if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled"); return -EINVAL; } pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE; break; case LVM_VOLUME: if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled"); return -EINVAL; } pContext->pBundledContext->bVolumeEnabled = LVM_FALSE; break; default: ALOGV("\tEffect_setEnabled() invalid effect type"); return -EINVAL; } LvmEffect_disable(pContext); } return 0; } int16_t LVC_Convert_VolToDb(uint32_t vol){ int16_t dB; dB = LVC_ToDB_s32Tos16(vol <<7); dB = (dB +8)>>4; dB = (dB <-96) ? -96 : dB ; return dB; } } // namespace Commit Message: Fix security vulnerability: Effect command might allow negative indexes Bug: 32448258 Bug: 32095626 Test: Use POC bug or cts security test Change-Id: I69f24eac5866f8d9090fc4c0ebe58c2c297b63df (cherry picked from commit 01183402d757f0c28bfd5e3b127b3809dfd67459) CWE ID: CWE-200
int Equalizer_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int bMute = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; int32_t param2; char *name; switch (param) { case EQ_PARAM_NUM_BANDS: case EQ_PARAM_CUR_PRESET: case EQ_PARAM_GET_NUM_OF_PRESETS: case EQ_PARAM_BAND_LEVEL: case EQ_PARAM_GET_BAND: if (*pValueSize < sizeof(int16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; case EQ_PARAM_LEVEL_RANGE: if (*pValueSize < 2 * sizeof(int16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 2 %d", *pValueSize); return -EINVAL; } *pValueSize = 2 * sizeof(int16_t); break; case EQ_PARAM_BAND_FREQ_RANGE: if (*pValueSize < 2 * sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 3 %d", *pValueSize); return -EINVAL; } *pValueSize = 2 * sizeof(int32_t); break; case EQ_PARAM_CENTER_FREQ: if (*pValueSize < sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 5 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int32_t); break; case EQ_PARAM_GET_PRESET_NAME: break; case EQ_PARAM_PROPERTIES: if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t); break; default: ALOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param); return -EINVAL; } switch (param) { case EQ_PARAM_NUM_BANDS: *(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS; break; case EQ_PARAM_LEVEL_RANGE: *(int16_t *)pValue = -1500; *((int16_t *)pValue + 1) = 1500; break; case EQ_PARAM_BAND_LEVEL: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32438598"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_LEVEL band %d", param2); } break; } *(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2); break; case EQ_PARAM_CENTER_FREQ: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32436341"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_CENTER_FREQ band %d", param2); } break; } *(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2); break; case EQ_PARAM_BAND_FREQ_RANGE: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32247948"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_FREQ_RANGE band %d", param2); } break; } EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1)); break; case EQ_PARAM_GET_BAND: param2 = *pParamTemp; *(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2); break; case EQ_PARAM_CUR_PRESET: *(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext); break; case EQ_PARAM_GET_NUM_OF_PRESETS: *(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets(); break; case EQ_PARAM_GET_PRESET_NAME: param2 = *pParamTemp; if ((param2 < 0 && param2 != PRESET_CUSTOM) || param2 >= EqualizerGetNumPresets()) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32448258"); ALOGE("\tERROR Equalizer_getParameter() EQ_PARAM_GET_PRESET_NAME preset %d", param2); } break; } name = (char *)pValue; strncpy(name, EqualizerGetPresetName(param2), *pValueSize - 1); name[*pValueSize - 1] = 0; *pValueSize = strlen(name) + 1; break; case EQ_PARAM_PROPERTIES: { int16_t *p = (int16_t *)pValue; ALOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES"); p[0] = (int16_t)EqualizerGetPreset(pContext); p[1] = (int16_t)FIVEBAND_NUMBANDS; for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i); } } break; default: ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Equalizer_getParameter */ int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){ int status = 0; int32_t preset; int32_t band; int32_t level; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; switch (param) { case EQ_PARAM_CUR_PRESET: preset = (int32_t)(*(uint16_t *)pValue); if ((preset >= EqualizerGetNumPresets())||(preset < 0)) { status = -EINVAL; break; } EqualizerSetPreset(pContext, preset); break; case EQ_PARAM_BAND_LEVEL: band = *pParamTemp; level = (int32_t)(*(int16_t *)pValue); if (band < 0 || band >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (band < 0) { android_errorWriteLog(0x534e4554, "32095626"); ALOGE("\tERROR Equalizer_setParameter() EQ_PARAM_BAND_LEVEL band %d", band); } break; } EqualizerSetBandLevel(pContext, band, level); break; case EQ_PARAM_PROPERTIES: { int16_t *p = (int16_t *)pValue; if ((int)p[0] >= EqualizerGetNumPresets()) { status = -EINVAL; break; } if (p[0] >= 0) { EqualizerSetPreset(pContext, (int)p[0]); } else { if ((int)p[1] != FIVEBAND_NUMBANDS) { status = -EINVAL; break; } for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { EqualizerSetBandLevel(pContext, i, (int)p[2 + i]); } } } break; default: ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Equalizer_setParameter */ int Volume_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int bMute = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++;; char *name; switch (param){ case VOLUME_PARAM_LEVEL: case VOLUME_PARAM_MAXLEVEL: case VOLUME_PARAM_STEREOPOSITION: if (*pValueSize != sizeof(int16_t)){ ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; case VOLUME_PARAM_MUTE: case VOLUME_PARAM_ENABLESTEREOPOSITION: if (*pValueSize < sizeof(int32_t)){ ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 2 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int32_t); break; default: ALOGV("\tLVM_ERROR : Volume_getParameter unknown param %d", param); return -EINVAL; } switch (param){ case VOLUME_PARAM_LEVEL: status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue)); break; case VOLUME_PARAM_MAXLEVEL: *(int16_t *)pValue = 0; break; case VOLUME_PARAM_STEREOPOSITION: VolumeGetStereoPosition(pContext, (int16_t *)pValue); break; case VOLUME_PARAM_MUTE: status = VolumeGetMute(pContext, (uint32_t *)pValue); ALOGV("\tVolume_getParameter() VOLUME_PARAM_MUTE Value is %d", *(uint32_t *)pValue); break; case VOLUME_PARAM_ENABLESTEREOPOSITION: *(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled; break; default: ALOGV("\tLVM_ERROR : Volume_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Volume_getParameter */ int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){ int status = 0; int16_t level; int16_t position; uint32_t mute; uint32_t positionEnabled; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; switch (param){ case VOLUME_PARAM_LEVEL: level = *(int16_t *)pValue; status = VolumeSetVolumeLevel(pContext, (int16_t)level); break; case VOLUME_PARAM_MUTE: mute = *(uint32_t *)pValue; status = VolumeSetMute(pContext, mute); break; case VOLUME_PARAM_ENABLESTEREOPOSITION: positionEnabled = *(uint32_t *)pValue; status = VolumeEnableStereoPosition(pContext, positionEnabled); status = VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved); break; case VOLUME_PARAM_STEREOPOSITION: position = *(int16_t *)pValue; status = VolumeSetStereoPosition(pContext, (int16_t)position); break; default: ALOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param); break; } return status; } /* end Volume_setParameter */ /**************************************************************************************** * Name : LVC_ToDB_s32Tos16() * Input : Signed 32-bit integer * Output : Signed 16-bit integer * MSB (16) = sign bit * (15->05) = integer part * (04->01) = decimal part * Returns : Db value with respect to full scale * Description : * Remarks : ****************************************************************************************/ LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix) { LVM_INT16 db_fix; LVM_INT16 Shift; LVM_INT16 SmallRemainder; LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix; /* Count leading bits, 1 cycle in assembly*/ for (Shift = 0; Shift<32; Shift++) { if ((Remainder & 0x80000000U)!=0) { break; } Remainder = Remainder << 1; } /* * Based on the approximation equation (for Q11.4 format): * * dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2) */ db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/ SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24); db_fix = (LVM_INT16)(db_fix + SmallRemainder ); SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder); db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9)); /* Correct for small offset */ db_fix = (LVM_INT16)(db_fix - 5); return db_fix; } int Effect_setEnabled(EffectContext *pContext, bool enabled) { ALOGV("\tEffect_setEnabled() type %d, enabled %d", pContext->EffectType, enabled); if (enabled) { bool tempDisabled = false; switch (pContext->EffectType) { case LVM_BASS_BOOST: if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountBb <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountBb = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bBassEnabled = LVM_TRUE; tempDisabled = pContext->pBundledContext->bBassTempDisabled; break; case LVM_EQUALIZER: if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountEq <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountEq = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE; break; case LVM_VIRTUALIZER: if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountVirt = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE; tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled; break; case LVM_VOLUME: if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled"); return -EINVAL; } pContext->pBundledContext->NumberEffectsEnabled++; pContext->pBundledContext->bVolumeEnabled = LVM_TRUE; break; default: ALOGV("\tEffect_setEnabled() invalid effect type"); return -EINVAL; } if (!tempDisabled) { LvmEffect_enable(pContext); } } else { switch (pContext->EffectType) { case LVM_BASS_BOOST: if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled"); return -EINVAL; } pContext->pBundledContext->bBassEnabled = LVM_FALSE; break; case LVM_EQUALIZER: if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled"); return -EINVAL; } pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE; break; case LVM_VIRTUALIZER: if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled"); return -EINVAL; } pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE; break; case LVM_VOLUME: if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled"); return -EINVAL; } pContext->pBundledContext->bVolumeEnabled = LVM_FALSE; break; default: ALOGV("\tEffect_setEnabled() invalid effect type"); return -EINVAL; } LvmEffect_disable(pContext); } return 0; } int16_t LVC_Convert_VolToDb(uint32_t vol){ int16_t dB; dB = LVC_ToDB_s32Tos16(vol <<7); dB = (dB +8)>>4; dB = (dB <-96) ? -96 : dB ; return dB; } } // namespace
27,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: transform_enable(PNG_CONST char *name) { /* Everything starts out enabled, so if we see an 'enable' disabled * everything else the first time round. */ static int all_disabled = 0; int found_it = 0; image_transform *list = image_transform_first; while (list != &image_transform_end) { if (strcmp(list->name, name) == 0) { list->enable = 1; found_it = 1; } else if (!all_disabled) list->enable = 0; list = list->list; } all_disabled = 1; if (!found_it) { fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n", name); exit(99); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
transform_enable(PNG_CONST char *name) image_transform_png_set_invert_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type & 4) that->alpha_inverted = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_invert_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* Only has an effect on pixels with alpha: */ return (colour_type & 4) != 0; } IT(invert_alpha); #undef PT #define PT ITSTRUCT(invert_alpha) #endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */ /* png_set_bgr */ #ifdef PNG_READ_BGR_SUPPORTED /* Swap R,G,B channels to order B,G,R. * * png_set_bgr(png_structrp png_ptr) * * This only has an effect on RGB and RGBA pixels. */ static void image_transform_png_set_bgr_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_bgr(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_bgr_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_RGB || that->colour_type == PNG_COLOR_TYPE_RGBA) that->swap_rgb = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_bgr_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_RGB || colour_type == PNG_COLOR_TYPE_RGBA; } IT(bgr); #undef PT #define PT ITSTRUCT(bgr) #endif /* PNG_READ_BGR_SUPPORTED */ /* png_set_swap_alpha */ #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED /* Put the alpha channel first. * * png_set_swap_alpha(png_structrp png_ptr) * * This only has an effect on GA and RGBA pixels. */ static void image_transform_png_set_swap_alpha_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_swap_alpha(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_swap_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_GA || that->colour_type == PNG_COLOR_TYPE_RGBA) that->alpha_first = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_swap_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_GA || colour_type == PNG_COLOR_TYPE_RGBA; } IT(swap_alpha); #undef PT #define PT ITSTRUCT(swap_alpha) #endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */ /* png_set_swap */ #ifdef PNG_READ_SWAP_SUPPORTED /* Byte swap 16-bit components. * * png_set_swap(png_structrp png_ptr) */ static void image_transform_png_set_swap_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_swap(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_swap_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth == 16) that->swap16 = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_swap_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth == 16; } IT(swap); #undef PT #define PT ITSTRUCT(swap) #endif /* PNG_READ_SWAP_SUPPORTED */ #ifdef PNG_READ_FILLER_SUPPORTED /* Add a filler byte to 8-bit Gray or 24-bit RGB images. * * png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags)); * * Flags: * * PNG_FILLER_BEFORE * PNG_FILLER_AFTER */ #define data ITDATA(filler) static struct { png_uint_32 filler; int flags; } data; static void image_transform_png_set_filler_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { /* Need a random choice for 'before' and 'after' as well as for the * filler. The 'filler' value has all 32 bits set, but only bit_depth * will be used. At this point we don't know bit_depth. */ RANDOMIZE(data.filler); data.flags = random_choice(); png_set_filler(pp, data.filler, data.flags); /* The standard display handling stuff also needs to know that * there is a filler, so set that here. */ that->this.filler = 1; this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_filler_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth >= 8 && (that->colour_type == PNG_COLOR_TYPE_RGB || that->colour_type == PNG_COLOR_TYPE_GRAY)) { const unsigned int max = (1U << that->bit_depth)-1; that->alpha = data.filler & max; that->alphaf = ((double)that->alpha) / max; that->alphae = 0; /* The filler has been stored in the alpha channel, we must record * that this has been done for the checking later on, the color * type is faked to have an alpha channel, but libpng won't report * this; the app has to know the extra channel is there and this * was recording in standard_display::filler above. */ that->colour_type |= 4; /* alpha added */ that->alpha_first = data.flags == PNG_FILLER_BEFORE; } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_filler_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { this->next = *that; *that = this; return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB || colour_type == PNG_COLOR_TYPE_GRAY); } #undef data IT(filler); #undef PT #define PT ITSTRUCT(filler) /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */ /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */ #define data ITDATA(add_alpha) static struct { png_uint_32 filler; int flags; } data; static void image_transform_png_set_add_alpha_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { /* Need a random choice for 'before' and 'after' as well as for the * filler. The 'filler' value has all 32 bits set, but only bit_depth * will be used. At this point we don't know bit_depth. */ RANDOMIZE(data.filler); data.flags = random_choice(); png_set_add_alpha(pp, data.filler, data.flags); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_add_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth >= 8 && (that->colour_type == PNG_COLOR_TYPE_RGB || that->colour_type == PNG_COLOR_TYPE_GRAY)) { const unsigned int max = (1U << that->bit_depth)-1; that->alpha = data.filler & max; that->alphaf = ((double)that->alpha) / max; that->alphae = 0; that->colour_type |= 4; /* alpha added */ that->alpha_first = data.flags == PNG_FILLER_BEFORE; } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_add_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { this->next = *that; *that = this; return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB || colour_type == PNG_COLOR_TYPE_GRAY); } #undef data IT(add_alpha); #undef PT #define PT ITSTRUCT(add_alpha) #endif /* PNG_READ_FILLER_SUPPORTED */ /* png_set_packing */ #ifdef PNG_READ_PACK_SUPPORTED /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. * * png_set_packing(png_structrp png_ptr) * * This should only affect grayscale and palette images with less than 8 bits * per pixel. */ static void image_transform_png_set_packing_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_packing(pp); that->unpacked = 1; this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_packing_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* The general expand case depends on what the colour type is, * low bit-depth pixel values are unpacked into bytes without * scaling, so sample_depth is not changed. */ if (that->bit_depth < 8) /* grayscale or palette */ that->bit_depth = 8; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_packing_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; /* Nothing should happen unless the bit depth is less than 8: */ return bit_depth < 8; } IT(packing); #undef PT #define PT ITSTRUCT(packing) #endif /* PNG_READ_PACK_SUPPORTED */ /* png_set_packswap */ #ifdef PNG_READ_PACKSWAP_SUPPORTED /* Swap pixels packed into bytes; reverses the order on screen so that * the high order bits correspond to the rightmost pixels. * * png_set_packswap(png_structrp png_ptr) */ static void image_transform_png_set_packswap_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_packswap(pp); that->this.littleendian = 1; this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_packswap_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth < 8) that->littleendian = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_packswap_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth < 8; } IT(packswap); #undef PT #define PT ITSTRUCT(packswap) #endif /* PNG_READ_PACKSWAP_SUPPORTED */ /* png_set_invert_mono */ #ifdef PNG_READ_INVERT_MONO_SUPPORTED /* Invert the gray channel * * png_set_invert_mono(png_structrp png_ptr) */ static void image_transform_png_set_invert_mono_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_invert_mono(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_invert_mono_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type & 4) that->mono_inverted = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_invert_mono_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* Only has an effect on pixels with no colour: */ return (colour_type & 2) == 0; } IT(invert_mono); #undef PT #define PT ITSTRUCT(invert_mono) #endif /* PNG_READ_INVERT_MONO_SUPPORTED */ #ifdef PNG_READ_SHIFT_SUPPORTED /* png_set_shift(png_structp, png_const_color_8p true_bits) * * The output pixels will be shifted by the given true_bits * values. */ #define data ITDATA(shift) static png_color_8 data; static void image_transform_png_set_shift_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { /* Get a random set of shifts. The shifts need to do something * to test the transform, so they are limited to the bit depth * of the input image. Notice that in the following the 'gray' * field is randomized independently. This acts as a check that * libpng does use the correct field. */ const unsigned int depth = that->this.bit_depth; data.red = (png_byte)/*SAFE*/(random_mod(depth)+1); data.green = (png_byte)/*SAFE*/(random_mod(depth)+1); data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1); data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1); data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1); png_set_shift(pp, &data); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_shift_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* Copy the correct values into the sBIT fields, libpng does not do * anything to palette data: */ if (that->colour_type != PNG_COLOR_TYPE_PALETTE) { that->sig_bits = 1; /* The sBIT fields are reset to the values previously sent to * png_set_shift according to the colour type. * does. */ if (that->colour_type & 2) /* RGB channels */ { that->red_sBIT = data.red; that->green_sBIT = data.green; that->blue_sBIT = data.blue; } else /* One grey channel */ that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray; that->alpha_sBIT = data.alpha; } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_shift_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type != PNG_COLOR_TYPE_PALETTE; } IT(shift); #undef PT #define PT ITSTRUCT(shift) #endif /* PNG_READ_SHIFT_SUPPORTED */ #ifdef THIS_IS_THE_PROFORMA static void image_transform_png_set_@_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_@(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_@_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_@_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { this->next = *that; *that = this; return 1; } IT(@); #endif /* This may just be 'end' if all the transforms are disabled! */ static image_transform *const image_transform_first = &PT; static void transform_enable(const char *name) { /* Everything starts out enabled, so if we see an 'enable' disabled * everything else the first time round. */ static int all_disabled = 0; int found_it = 0; image_transform *list = image_transform_first; while (list != &image_transform_end) { if (strcmp(list->name, name) == 0) { list->enable = 1; found_it = 1; } else if (!all_disabled) list->enable = 0; list = list->list; } all_disabled = 1; if (!found_it) { fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n", name); exit(99); } }
12,531