instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: init_ctx_new(OM_uint32 *minor_status,
spnego_gss_cred_id_t spcred,
gss_ctx_id_t *ctx,
send_token_flag *tokflag)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = NULL;
sc = create_spnego_ctx();
if (sc == NULL)
return GSS_S_FAILURE;
/* determine negotiation mech set */
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE,
&sc->mech_set);
if (ret != GSS_S_COMPLETE)
goto cleanup;
/* Set an initial internal mech to make the first context token. */
sc->internal_mech = &sc->mech_set->elements[0];
if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
/*
* The actual context is not yet determined, set the output
* context handle to refer to the spnego context itself.
*/
sc->ctx_handle = GSS_C_NO_CONTEXT;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
*tokflag = INIT_TOKEN_SEND;
ret = GSS_S_CONTINUE_NEEDED;
cleanup:
release_spnego_ctx(&sc);
return ret;
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | init_ctx_new(OM_uint32 *minor_status,
spnego_gss_cred_id_t spcred,
gss_ctx_id_t *ctx,
send_token_flag *tokflag)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = NULL;
sc = create_spnego_ctx(1);
if (sc == NULL)
return GSS_S_FAILURE;
/* determine negotiation mech set */
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE,
&sc->mech_set);
if (ret != GSS_S_COMPLETE)
goto cleanup;
/* Set an initial internal mech to make the first context token. */
sc->internal_mech = &sc->mech_set->elements[0];
if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
sc->ctx_handle = GSS_C_NO_CONTEXT;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
*tokflag = INIT_TOKEN_SEND;
ret = GSS_S_CONTINUE_NEEDED;
cleanup:
release_spnego_ctx(&sc);
return ret;
}
| 166,650 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int store_xauthority(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
Commit Message: security fix
CWE ID: CWE-269 | static int store_xauthority(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
| 168,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. Remember, I want response with just the fixed code only, No explanation. | Code: static int nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
{
ssize_t ret;
uint8_t *buffer = g_malloc(MIN(65536, size));
while (size > 0) {
size_t count = MIN(65536, size);
ret = nbd_negotiate_read(ioc, buffer, count);
if (ret < 0) {
g_free(buffer);
return ret;
}
size -= count;
}
g_free(buffer);
return 0;
}
Commit Message:
CWE ID: CWE-20 | static int nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
| 165,453 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content,
int content_len)
{
Packet *p = NULL;
int hlen = 20;
int ttl = 64;
uint8_t *pcontent;
IPV4Hdr ip4h;
p = SCCalloc(1, sizeof(*p) + default_packet_size);
if (unlikely(p == NULL))
return NULL;
PACKET_INITIALIZE(p);
gettimeofday(&p->ts, NULL);
ip4h.ip_verhl = 4 << 4;
ip4h.ip_verhl |= hlen >> 2;
ip4h.ip_len = htons(hlen + content_len);
ip4h.ip_id = htons(id);
ip4h.ip_off = htons(off);
if (mf)
ip4h.ip_off = htons(IP_MF | off);
else
ip4h.ip_off = htons(off);
ip4h.ip_ttl = ttl;
ip4h.ip_proto = IPPROTO_ICMP;
ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */
ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */
/* copy content_len crap, we need full length */
PacketCopyData(p, (uint8_t *)&ip4h, sizeof(ip4h));
p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p);
SET_IPV4_SRC_ADDR(p, &p->src);
SET_IPV4_DST_ADDR(p, &p->dst);
pcontent = SCCalloc(1, content_len);
if (unlikely(pcontent == NULL))
return NULL;
memset(pcontent, content, content_len);
PacketCopyDataOffset(p, hlen, pcontent, content_len);
SET_PKT_LEN(p, hlen + content_len);
SCFree(pcontent);
p->ip4h->ip_csum = IPV4CalculateChecksum((uint16_t *)GET_PKT_DATA(p), hlen);
/* Self test. */
if (IPV4_GET_VER(p) != 4)
goto error;
if (IPV4_GET_HLEN(p) != hlen)
goto error;
if (IPV4_GET_IPLEN(p) != hlen + content_len)
goto error;
if (IPV4_GET_IPID(p) != id)
goto error;
if (IPV4_GET_IPOFFSET(p) != off)
goto error;
if (IPV4_GET_MF(p) != mf)
goto error;
if (IPV4_GET_IPTTL(p) != ttl)
goto error;
if (IPV4_GET_IPPROTO(p) != IPPROTO_ICMP)
goto error;
return p;
error:
if (p != NULL)
SCFree(p);
return NULL;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content,
BuildTestPacket(uint8_t proto, uint16_t id, uint16_t off, int mf,
const char content, int content_len)
{
Packet *p = NULL;
int hlen = 20;
int ttl = 64;
uint8_t *pcontent;
IPV4Hdr ip4h;
p = SCCalloc(1, sizeof(*p) + default_packet_size);
if (unlikely(p == NULL))
return NULL;
PACKET_INITIALIZE(p);
gettimeofday(&p->ts, NULL);
ip4h.ip_verhl = 4 << 4;
ip4h.ip_verhl |= hlen >> 2;
ip4h.ip_len = htons(hlen + content_len);
ip4h.ip_id = htons(id);
ip4h.ip_off = htons(off);
if (mf)
ip4h.ip_off = htons(IP_MF | off);
else
ip4h.ip_off = htons(off);
ip4h.ip_ttl = ttl;
ip4h.ip_proto = proto;
ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */
ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */
/* copy content_len crap, we need full length */
PacketCopyData(p, (uint8_t *)&ip4h, sizeof(ip4h));
p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p);
SET_IPV4_SRC_ADDR(p, &p->src);
SET_IPV4_DST_ADDR(p, &p->dst);
pcontent = SCCalloc(1, content_len);
if (unlikely(pcontent == NULL))
return NULL;
memset(pcontent, content, content_len);
PacketCopyDataOffset(p, hlen, pcontent, content_len);
SET_PKT_LEN(p, hlen + content_len);
SCFree(pcontent);
p->ip4h->ip_csum = IPV4CalculateChecksum((uint16_t *)GET_PKT_DATA(p), hlen);
/* Self test. */
if (IPV4_GET_VER(p) != 4)
goto error;
if (IPV4_GET_HLEN(p) != hlen)
goto error;
if (IPV4_GET_IPLEN(p) != hlen + content_len)
goto error;
if (IPV4_GET_IPID(p) != id)
goto error;
if (IPV4_GET_IPOFFSET(p) != off)
goto error;
if (IPV4_GET_MF(p) != mf)
goto error;
if (IPV4_GET_IPTTL(p) != ttl)
goto error;
if (IPV4_GET_IPPROTO(p) != proto)
goto error;
return p;
error:
if (p != NULL)
SCFree(p);
return NULL;
}
| 168,294 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: chrand_principal_2_svc(chrand_arg *arg, struct svc_req *rqstp)
{
static chrand_ret ret;
krb5_keyblock *k;
int nkeys;
char *prime_arg, *funcname;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_chrand_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_randkey_principal";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) {
ret.code = randkey_principal_wrapper_3((void *)handle, arg->princ,
FALSE, 0, NULL, &k, &nkeys);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_randkey_principal((void *)handle, arg->princ,
&k, &nkeys);
} else {
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if(ret.code == KADM5_OK) {
ret.keys = k;
ret.n_keys = nkeys;
}
if(ret.code != KADM5_AUTH_CHANGEPW) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | chrand_principal_2_svc(chrand_arg *arg, struct svc_req *rqstp)
{
static chrand_ret ret;
krb5_keyblock *k;
int nkeys;
char *prime_arg, *funcname;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_chrand_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_randkey_principal";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) {
ret.code = randkey_principal_wrapper_3((void *)handle, arg->princ,
FALSE, 0, NULL, &k, &nkeys);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_randkey_principal((void *)handle, arg->princ,
&k, &nkeys);
} else {
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if(ret.code == KADM5_OK) {
ret.keys = k;
ret.n_keys = nkeys;
}
if(ret.code != KADM5_AUTH_CHANGEPW) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,507 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: FrameImpl::~FrameImpl() {
window_tree_host_->Hide();
window_tree_host_->compositor()->SetVisible(false);
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | FrameImpl::~FrameImpl() {
if (window_tree_host_) {
window_tree_host_->Hide();
window_tree_host_->compositor()->SetVisible(false);
}
}
zx::unowned_channel FrameImpl::GetBindingChannelForTest() const {
return zx::unowned_channel(binding_.channel());
}
| 172,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. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
MyObject *mobject;
mobject = MY_OBJECT (object);
switch (prop_id)
{
case PROP_THIS_IS_A_STRING:
g_value_set_string (value, mobject->this_is_a_string);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
Commit Message:
CWE ID: CWE-264 | my_object_get_property (GObject *object,
| 165,102 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
{
kiocb->ki_iovec = &kiocb->ki_inline_vec;
kiocb->ki_iovec->iov_base = kiocb->ki_buf;
kiocb->ki_iovec->iov_len = kiocb->ki_left;
kiocb->ki_nr_segs = 1;
kiocb->ki_cur_seg = 0;
return 0;
}
Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers
We had for some reason overlooked the AIO interface, and it didn't use
the proper rw_verify_area() helper function that checks (for example)
mandatory locking on the file, and that the size of the access doesn't
cause us to overflow the provided offset limits etc.
Instead, AIO did just the security_file_permission() thing (that
rw_verify_area() also does) directly.
This fixes it to do all the proper helper functions, which not only
means that now mandatory file locking works with AIO too, we can
actually remove lines of code.
Reported-by: Manish Honap <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
static ssize_t aio_setup_single_vector(int type, struct file * file, struct kiocb *kiocb)
{
int bytes;
bytes = rw_verify_area(type, file, &kiocb->ki_pos, kiocb->ki_left);
if (bytes < 0)
return bytes;
kiocb->ki_iovec = &kiocb->ki_inline_vec;
kiocb->ki_iovec->iov_base = kiocb->ki_buf;
kiocb->ki_iovec->iov_len = bytes;
kiocb->ki_nr_segs = 1;
kiocb->ki_cur_seg = 0;
return 0;
}
| 167,612 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen,
u8 *dst, unsigned int dlen)
{
return crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen);
}
Commit Message: crypto: rng - Remove old low-level rng interface
Now that all rng implementations have switched over to the new
interface, we can remove the old low-level interface.
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-476 | static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen,
| 167,733 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_blkcipher rblkcipher;
snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "blkcipher");
snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s",
alg->cra_blkcipher.geniv ?: "<default>");
rblkcipher.blocksize = alg->cra_blocksize;
rblkcipher.min_keysize = alg->cra_blkcipher.min_keysize;
rblkcipher.max_keysize = alg->cra_blkcipher.max_keysize;
rblkcipher.ivsize = alg->cra_blkcipher.ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
sizeof(struct crypto_report_blkcipher), &rblkcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310 | static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_blkcipher rblkcipher;
strncpy(rblkcipher.type, "blkcipher", sizeof(rblkcipher.type));
strncpy(rblkcipher.geniv, alg->cra_blkcipher.geniv ?: "<default>",
sizeof(rblkcipher.geniv));
rblkcipher.blocksize = alg->cra_blocksize;
rblkcipher.min_keysize = alg->cra_blkcipher.min_keysize;
rblkcipher.max_keysize = alg->cra_blkcipher.max_keysize;
rblkcipher.ivsize = alg->cra_blkcipher.ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
sizeof(struct crypto_report_blkcipher), &rblkcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 166,066 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: SendTabToSelfInfoBarDelegate::Create(const SendTabToSelfEntry* entry) {
return base::WrapUnique(new SendTabToSelfInfoBarDelegate(entry));
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
CWE ID: CWE-190 | SendTabToSelfInfoBarDelegate::Create(const SendTabToSelfEntry* entry) {
SendTabToSelfInfoBarDelegate::Create(content::WebContents* web_contents,
const SendTabToSelfEntry* entry) {
return base::WrapUnique(
new SendTabToSelfInfoBarDelegate(web_contents, entry));
}
| 172,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. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_strip_16_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_16(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_strip_16_set(PNG_CONST image_transform *this,
image_transform_png_set_strip_16_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_16(pp);
# if PNG_LIBPNG_VER < 10700
/* libpng will limit the gamma table size: */
that->max_gamma_8 = PNG_MAX_GAMMA_8;
# endif
this->next->set(this->next, that, pp, pi);
}
| 173,650 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: bool HTMLMediaElement::IsMediaDataCORSSameOrigin(
const SecurityOrigin* origin) const {
if (GetWebMediaPlayer() &&
GetWebMediaPlayer()->DidGetOpaqueResponseFromServiceWorker()) {
return false;
}
if (!HasSingleSecurityOrigin())
return false;
return (GetWebMediaPlayer() &&
GetWebMediaPlayer()->DidPassCORSAccessCheck()) ||
origin->CanReadContent(currentSrc());
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | bool HTMLMediaElement::IsMediaDataCORSSameOrigin(
const SecurityOrigin* origin) const {
if (!GetWebMediaPlayer())
return true;
const auto network_state = GetWebMediaPlayer()->GetNetworkState();
if (network_state == WebMediaPlayer::kNetworkStateNetworkError)
return false;
return !GetWebMediaPlayer()->WouldTaintOrigin();
}
| 172,632 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
{
const unsigned char *p;
int plen;
if (alg == NULL)
return NULL;
if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
return NULL;
if (alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
return d2i_X509_ALGOR(NULL, &p, plen);
}
Commit Message:
CWE ID: | static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
{
const unsigned char *p;
int plen;
if (alg == NULL || alg->parameter == NULL)
return NULL;
if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
return NULL;
if (alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
return d2i_X509_ALGOR(NULL, &p, plen);
}
| 164,720 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
{
struct session_state *state = ssh->state;
u_int padlen, need;
u_char *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
u_int maclen, aadlen = 0, authlen = 0, block_size;
struct sshenc *enc = NULL;
struct sshmac *mac = NULL;
struct sshcomp *comp = NULL;
int r;
*typep = SSH_MSG_NONE;
if (state->packet_discard)
return 0;
if (state->newkeys[MODE_IN] != NULL) {
enc = &state->newkeys[MODE_IN]->enc;
mac = &state->newkeys[MODE_IN]->mac;
comp = &state->newkeys[MODE_IN]->comp;
/* disable mac for authenticated encryption */
if ((authlen = cipher_authlen(enc->cipher)) != 0)
mac = NULL;
}
maclen = mac && mac->enabled ? mac->mac_len : 0;
block_size = enc ? enc->block_size : 8;
aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
if (aadlen && state->packlen == 0) {
if (cipher_get_length(&state->receive_context,
&state->packlen, state->p_read.seqnr,
sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
return 0;
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
sshbuf_dump(state->input, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
return r;
}
sshbuf_reset(state->incoming_packet);
} else if (state->packlen == 0) {
* check if input size is less than the cipher block size,
* decrypt first block and extract length of incoming packet
*/
if (sshbuf_len(state->input) < block_size)
return 0;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_reserve(state->incoming_packet, block_size,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(&state->receive_context,
state->p_send.seqnr, cp, sshbuf_ptr(state->input),
block_size, 0, 0)) != 0)
goto out;
state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
fprintf(stderr, "input: \n");
sshbuf_dump(state->input, stderr);
fprintf(stderr, "incoming_packet: \n");
sshbuf_dump(state->incoming_packet, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
return ssh_packet_start_discard(ssh, enc, mac,
state->packlen, PACKET_MAX_SIZE);
}
if ((r = sshbuf_consume(state->input, block_size)) != 0)
goto out;
}
DBG(debug("input: packet len %u", state->packlen+4));
if (aadlen) {
/* only the payload is encrypted */
need = state->packlen;
} else {
/*
* the payload size and the payload are encrypted, but we
* have a partial packet of block_size bytes
*/
need = 4 + state->packlen - block_size;
}
DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
" aadlen %d", block_size, need, maclen, authlen, aadlen));
if (need % block_size != 0) {
logit("padding error: need %d block %d mod %d",
need, block_size, need % block_size);
return ssh_packet_start_discard(ssh, enc, mac,
state->packlen, PACKET_MAX_SIZE - block_size);
}
/*
* check if the entire packet has been received and
* decrypt into incoming_packet:
* 'aadlen' bytes are unencrypted, but authenticated.
* 'need' bytes are encrypted, followed by either
* 'authlen' bytes of authentication tag or
* 'maclen' bytes of message authentication code.
*/
if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
return 0;
#ifdef PACKET_DEBUG
fprintf(stderr, "read_poll enc/full: ");
sshbuf_dump(state->input, stderr);
#endif
/* EtM: compute mac over encrypted input */
if (mac && mac->enabled && mac->etm) {
if ((r = mac_compute(mac, state->p_read.seqnr,
sshbuf_ptr(state->input), aadlen + need,
macbuf, sizeof(macbuf))) != 0)
goto out;
}
if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(&state->receive_context, state->p_read.seqnr, cp,
sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
goto out;
if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
goto out;
/*
* compute MAC over seqnr and packet,
* increment sequence number for incoming packet
*/
if (mac && mac->enabled) {
if (!mac->etm)
if ((r = mac_compute(mac, state->p_read.seqnr,
sshbuf_ptr(state->incoming_packet),
sshbuf_len(state->incoming_packet),
macbuf, sizeof(macbuf))) != 0)
goto out;
if (timingsafe_bcmp(macbuf, sshbuf_ptr(state->input),
mac->mac_len) != 0) {
logit("Corrupted MAC on input.");
if (need > PACKET_MAX_SIZE)
return SSH_ERR_INTERNAL_ERROR;
return ssh_packet_start_discard(ssh, enc, mac,
state->packlen, PACKET_MAX_SIZE - need);
}
DBG(debug("MAC #%d ok", state->p_read.seqnr));
if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
goto out;
}
if (seqnr_p != NULL)
*seqnr_p = state->p_read.seqnr;
if (++state->p_read.seqnr == 0)
logit("incoming seqnr wraps around");
if (++state->p_read.packets == 0)
if (!(ssh->compat & SSH_BUG_NOREKEY))
return SSH_ERR_NEED_REKEY;
state->p_read.blocks += (state->packlen + 4) / block_size;
state->p_read.bytes += state->packlen + 4;
/* get padlen */
padlen = sshbuf_ptr(state->incoming_packet)[4];
DBG(debug("input: padlen %d", padlen));
if (padlen < 4) {
if ((r = sshpkt_disconnect(ssh,
"Corrupted padlen %d on input.", padlen)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
/* skip packet size + padlen, discard padding */
if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
goto out;
DBG(debug("input: len before de-compress %zd",
sshbuf_len(state->incoming_packet)));
if (comp && comp->enabled) {
sshbuf_reset(state->compression_buffer);
if ((r = uncompress_buffer(ssh, state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_putb(state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
DBG(debug("input: len after de-compress %zd",
sshbuf_len(state->incoming_packet)));
}
/*
* get packet type, implies consume.
* return length of payload (without type field)
*/
if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
goto out;
if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
if ((r = sshpkt_disconnect(ssh,
"Invalid ssh2 packet type: %d", *typep)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_PROTOCOL_ERROR;
}
if (*typep == SSH2_MSG_NEWKEYS)
r = ssh_set_newkeys(ssh, MODE_IN);
else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
r = ssh_packet_enable_delayed_compress(ssh);
else
r = 0;
#ifdef PACKET_DEBUG
fprintf(stderr, "read/plain[%d]:\r\n", *typep);
sshbuf_dump(state->incoming_packet, stderr);
#endif
/* reset for next packet */
state->packlen = 0;
out:
return r;
}
Commit Message:
CWE ID: CWE-119 | ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
{
struct session_state *state = ssh->state;
u_int padlen, need;
u_char *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
u_int maclen, aadlen = 0, authlen = 0, block_size;
struct sshenc *enc = NULL;
struct sshmac *mac = NULL;
struct sshcomp *comp = NULL;
int r;
*typep = SSH_MSG_NONE;
if (state->packet_discard)
return 0;
if (state->newkeys[MODE_IN] != NULL) {
enc = &state->newkeys[MODE_IN]->enc;
mac = &state->newkeys[MODE_IN]->mac;
comp = &state->newkeys[MODE_IN]->comp;
/* disable mac for authenticated encryption */
if ((authlen = cipher_authlen(enc->cipher)) != 0)
mac = NULL;
}
maclen = mac && mac->enabled ? mac->mac_len : 0;
block_size = enc ? enc->block_size : 8;
aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
if (aadlen && state->packlen == 0) {
if (cipher_get_length(&state->receive_context,
&state->packlen, state->p_read.seqnr,
sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
return 0;
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
sshbuf_dump(state->input, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
sshbuf_reset(state->incoming_packet);
} else if (state->packlen == 0) {
* check if input size is less than the cipher block size,
* decrypt first block and extract length of incoming packet
*/
if (sshbuf_len(state->input) < block_size)
return 0;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_reserve(state->incoming_packet, block_size,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(&state->receive_context,
state->p_send.seqnr, cp, sshbuf_ptr(state->input),
block_size, 0, 0)) != 0)
goto out;
state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
fprintf(stderr, "input: \n");
sshbuf_dump(state->input, stderr);
fprintf(stderr, "incoming_packet: \n");
sshbuf_dump(state->incoming_packet, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
return ssh_packet_start_discard(ssh, enc, mac,
state->packlen, PACKET_MAX_SIZE);
}
if ((r = sshbuf_consume(state->input, block_size)) != 0)
goto out;
}
DBG(debug("input: packet len %u", state->packlen+4));
if (aadlen) {
/* only the payload is encrypted */
need = state->packlen;
} else {
/*
* the payload size and the payload are encrypted, but we
* have a partial packet of block_size bytes
*/
need = 4 + state->packlen - block_size;
}
DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
" aadlen %d", block_size, need, maclen, authlen, aadlen));
if (need % block_size != 0) {
logit("padding error: need %d block %d mod %d",
need, block_size, need % block_size);
return ssh_packet_start_discard(ssh, enc, mac,
state->packlen, PACKET_MAX_SIZE - block_size);
}
/*
* check if the entire packet has been received and
* decrypt into incoming_packet:
* 'aadlen' bytes are unencrypted, but authenticated.
* 'need' bytes are encrypted, followed by either
* 'authlen' bytes of authentication tag or
* 'maclen' bytes of message authentication code.
*/
if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
return 0;
#ifdef PACKET_DEBUG
fprintf(stderr, "read_poll enc/full: ");
sshbuf_dump(state->input, stderr);
#endif
/* EtM: compute mac over encrypted input */
if (mac && mac->enabled && mac->etm) {
if ((r = mac_compute(mac, state->p_read.seqnr,
sshbuf_ptr(state->input), aadlen + need,
macbuf, sizeof(macbuf))) != 0)
goto out;
}
if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(&state->receive_context, state->p_read.seqnr, cp,
sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
goto out;
if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
goto out;
/*
* compute MAC over seqnr and packet,
* increment sequence number for incoming packet
*/
if (mac && mac->enabled) {
if (!mac->etm)
if ((r = mac_compute(mac, state->p_read.seqnr,
sshbuf_ptr(state->incoming_packet),
sshbuf_len(state->incoming_packet),
macbuf, sizeof(macbuf))) != 0)
goto out;
if (timingsafe_bcmp(macbuf, sshbuf_ptr(state->input),
mac->mac_len) != 0) {
logit("Corrupted MAC on input.");
if (need > PACKET_MAX_SIZE)
return SSH_ERR_INTERNAL_ERROR;
return ssh_packet_start_discard(ssh, enc, mac,
state->packlen, PACKET_MAX_SIZE - need);
}
DBG(debug("MAC #%d ok", state->p_read.seqnr));
if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
goto out;
}
if (seqnr_p != NULL)
*seqnr_p = state->p_read.seqnr;
if (++state->p_read.seqnr == 0)
logit("incoming seqnr wraps around");
if (++state->p_read.packets == 0)
if (!(ssh->compat & SSH_BUG_NOREKEY))
return SSH_ERR_NEED_REKEY;
state->p_read.blocks += (state->packlen + 4) / block_size;
state->p_read.bytes += state->packlen + 4;
/* get padlen */
padlen = sshbuf_ptr(state->incoming_packet)[4];
DBG(debug("input: padlen %d", padlen));
if (padlen < 4) {
if ((r = sshpkt_disconnect(ssh,
"Corrupted padlen %d on input.", padlen)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
/* skip packet size + padlen, discard padding */
if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
goto out;
DBG(debug("input: len before de-compress %zd",
sshbuf_len(state->incoming_packet)));
if (comp && comp->enabled) {
sshbuf_reset(state->compression_buffer);
if ((r = uncompress_buffer(ssh, state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_putb(state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
DBG(debug("input: len after de-compress %zd",
sshbuf_len(state->incoming_packet)));
}
/*
* get packet type, implies consume.
* return length of payload (without type field)
*/
if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
goto out;
if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
if ((r = sshpkt_disconnect(ssh,
"Invalid ssh2 packet type: %d", *typep)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_PROTOCOL_ERROR;
}
if (*typep == SSH2_MSG_NEWKEYS)
r = ssh_set_newkeys(ssh, MODE_IN);
else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
r = ssh_packet_enable_delayed_compress(ssh);
else
r = 0;
#ifdef PACKET_DEBUG
fprintf(stderr, "read/plain[%d]:\r\n", *typep);
sshbuf_dump(state->incoming_packet, stderr);
#endif
/* reset for next packet */
state->packlen = 0;
out:
return r;
}
| 165,219 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
{
int i;
BIO *out = NULL, *btmp = NULL;
X509_ALGOR *xa = NULL;
const EVP_CIPHER *evp_cipher = NULL;
STACK_OF(X509_ALGOR) *md_sk = NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
X509_ALGOR *xalg = NULL;
PKCS7_RECIP_INFO *ri = NULL;
ASN1_OCTET_STRING *os = NULL;
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
goto err;
}
break;
case NID_pkcs7_digest:
xa = p7->d.digest->md;
os = PKCS7_get_octet_string(p7->d.digest->contents);
break;
case NID_pkcs7_data:
break;
default:
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
Commit Message:
CWE ID: | BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
{
int i;
BIO *out = NULL, *btmp = NULL;
X509_ALGOR *xa = NULL;
const EVP_CIPHER *evp_cipher = NULL;
STACK_OF(X509_ALGOR) *md_sk = NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
X509_ALGOR *xalg = NULL;
PKCS7_RECIP_INFO *ri = NULL;
ASN1_OCTET_STRING *os = NULL;
if (p7 == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_INVALID_NULL_POINTER);
return NULL;
}
/*
* The content field in the PKCS7 ContentInfo is optional, but that really
* only applies to inner content (precisely, detached signatures).
*
* When reading content, missing outer content is therefore treated as an
* error.
*
* When creating content, PKCS7_content_new() must be called before
* calling this method, so a NULL p7->d is always an error.
*/
if (p7->d.ptr == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_NO_CONTENT);
return NULL;
}
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
goto err;
}
break;
case NID_pkcs7_digest:
xa = p7->d.digest->md;
os = PKCS7_get_octet_string(p7->d.digest->contents);
break;
case NID_pkcs7_data:
break;
default:
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
| 164,807 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void rds6_inc_info_copy(struct rds_incoming *inc,
struct rds_info_iterator *iter,
struct in6_addr *saddr, struct in6_addr *daddr,
int flip)
{
struct rds6_info_message minfo6;
minfo6.seq = be64_to_cpu(inc->i_hdr.h_sequence);
minfo6.len = be32_to_cpu(inc->i_hdr.h_len);
if (flip) {
minfo6.laddr = *daddr;
minfo6.faddr = *saddr;
minfo6.lport = inc->i_hdr.h_dport;
minfo6.fport = inc->i_hdr.h_sport;
} else {
minfo6.laddr = *saddr;
minfo6.faddr = *daddr;
minfo6.lport = inc->i_hdr.h_sport;
minfo6.fport = inc->i_hdr.h_dport;
}
rds_info_copy(iter, &minfo6, sizeof(minfo6));
}
Commit Message: net/rds: Fix info leak in rds6_inc_info_copy()
The rds6_inc_info_copy() function has a couple struct members which
are leaking stack information. The ->tos field should hold actual
information and the ->flags field needs to be zeroed out.
Fixes: 3eb450367d08 ("rds: add type of service(tos) infrastructure")
Fixes: b7ff8b1036f0 ("rds: Extend RDS API for IPv6 support")
Reported-by: 黄ID蝴蝶 <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Ka-Cheong Poon <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | void rds6_inc_info_copy(struct rds_incoming *inc,
struct rds_info_iterator *iter,
struct in6_addr *saddr, struct in6_addr *daddr,
int flip)
{
struct rds6_info_message minfo6;
minfo6.seq = be64_to_cpu(inc->i_hdr.h_sequence);
minfo6.len = be32_to_cpu(inc->i_hdr.h_len);
minfo6.tos = inc->i_conn->c_tos;
if (flip) {
minfo6.laddr = *daddr;
minfo6.faddr = *saddr;
minfo6.lport = inc->i_hdr.h_dport;
minfo6.fport = inc->i_hdr.h_sport;
} else {
minfo6.laddr = *saddr;
minfo6.faddr = *daddr;
minfo6.lport = inc->i_hdr.h_sport;
minfo6.fport = inc->i_hdr.h_dport;
}
minfo6.flags = 0;
rds_info_copy(iter, &minfo6, sizeof(minfo6));
}
| 169,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. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {
const xmlChar *ptr;
xmlChar cur;
xmlChar *name;
xmlEntityPtr entity = NULL;
if ((str == NULL) || (*str == NULL)) return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '%')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringPEReference: no name\n");
*str = ptr;
return(NULL);
}
cur = *ptr;
if (cur != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData,
name);
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"%%%s; is not a parameter entity\n",
name, NULL);
}
}
ctxt->hasPErefs = 1;
xmlFree(name);
*str = ptr;
return(entity);
}
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 | xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {
const xmlChar *ptr;
xmlChar cur;
xmlChar *name;
xmlEntityPtr entity = NULL;
if ((str == NULL) || (*str == NULL)) return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '%')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringPEReference: no name\n");
*str = ptr;
return(NULL);
}
cur = *ptr;
if (cur != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(name);
return(NULL);
}
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"%%%s; is not a parameter entity\n",
name, NULL);
}
}
ctxt->hasPErefs = 1;
xmlFree(name);
*str = ptr;
return(entity);
}
| 171,305 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
switch (type)
{
case -1:
{
SetPixelAlpha(image,pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
if (image->depth == 1)
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit=0; bit < number_bits; bit++)
{
SetPixelIndex(image,(((unsigned char) pixel) &
(0x01 << (7-bit))) != 0 ? 0 : 255,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),
exception),q);
q+=GetPixelChannels(image);
x++;
}
x--;
continue;
}
}
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
return(SyncAuthenticPixels(image,exception));
}
Commit Message: Rewrite reading pixel values.
CWE ID: CWE-125 | static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);
q+=GetPixelChannels(image);
}
else
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit = 0; bit < number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : 255,q,exception);
q+=GetPixelChannels(image);
x++;
}
if (x != image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
| 170,117 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::sendCommand(
OMX_COMMANDTYPE cmd, OMX_S32 param) {
if (cmd == OMX_CommandStateSet) {
mSailed = true;
}
const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && cmd == OMX_CommandStateSet) {
if (param == OMX_StateIdle) {
bufferSource->omxIdle();
} else if (param == OMX_StateLoaded) {
bufferSource->omxLoaded();
setGraphicBufferSource(NULL);
}
}
Mutex::Autolock autoLock(mLock);
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
const char *paramString =
cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param);
CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL);
CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
return StatusFromOMXError(err);
}
Commit Message: IOMX: allow configuration after going to loaded state
This was disallowed recently but we still use it as MediaCodcec.stop
only goes to loaded state, and does not free component.
Bug: 31450460
Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d
(cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b)
CWE ID: CWE-200 | status_t OMXNodeInstance::sendCommand(
OMX_COMMANDTYPE cmd, OMX_S32 param) {
if (cmd == OMX_CommandStateSet) {
// There are no configurations past first StateSet command.
mSailed = true;
}
const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && cmd == OMX_CommandStateSet) {
if (param == OMX_StateIdle) {
bufferSource->omxIdle();
} else if (param == OMX_StateLoaded) {
bufferSource->omxLoaded();
setGraphicBufferSource(NULL);
}
}
Mutex::Autolock autoLock(mLock);
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
const char *paramString =
cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param);
CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL);
CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
return StatusFromOMXError(err);
}
| 173,380 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: UnacceleratedStaticBitmapImage::MakeAccelerated(
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_wrapper) {
if (!context_wrapper)
return nullptr; // Can happen if the context is lost.
GrContext* grcontext = context_wrapper->ContextProvider()->GetGrContext();
if (!grcontext)
return nullptr; // Can happen if the context is lost.
sk_sp<SkImage> sk_image = paint_image_.GetSkImage();
sk_sp<SkImage> gpu_skimage =
sk_image->makeTextureImage(grcontext, sk_image->colorSpace());
if (!gpu_skimage)
return nullptr;
return AcceleratedStaticBitmapImage::CreateFromSkImage(
std::move(gpu_skimage), std::move(context_wrapper));
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | UnacceleratedStaticBitmapImage::MakeAccelerated(
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_wrapper) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!context_wrapper)
return nullptr; // Can happen if the context is lost.
GrContext* grcontext = context_wrapper->ContextProvider()->GetGrContext();
if (!grcontext)
return nullptr; // Can happen if the context is lost.
sk_sp<SkImage> sk_image = paint_image_.GetSkImage();
sk_sp<SkImage> gpu_skimage =
sk_image->makeTextureImage(grcontext, sk_image->colorSpace());
if (!gpu_skimage)
return nullptr;
return AcceleratedStaticBitmapImage::CreateFromSkImage(
std::move(gpu_skimage), std::move(context_wrapper));
}
| 172,601 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
if (mHeadersDecoded) {
drainAllOutputBuffers(false /* eos */);
}
H264SwDecRet ret = H264SWDEC_PIC_RDY;
bool portWillReset = false;
while ((mEOSStatus != INPUT_DATA_AVAILABLE || !inQueue.empty())
&& outQueue.size() == kNumOutputBuffers) {
if (mEOSStatus == INPUT_EOS_SEEN) {
drainAllOutputBuffers(true /* eos */);
return;
}
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
++mPicId;
OMX_BUFFERHEADERTYPE *header = new OMX_BUFFERHEADERTYPE;
memset(header, 0, sizeof(OMX_BUFFERHEADERTYPE));
header->nTimeStamp = inHeader->nTimeStamp;
header->nFlags = inHeader->nFlags;
if (header->nFlags & OMX_BUFFERFLAG_EOS) {
mEOSStatus = INPUT_EOS_SEEN;
}
mPicToHeaderMap.add(mPicId, header);
inQueue.erase(inQueue.begin());
H264SwDecInput inPicture;
H264SwDecOutput outPicture;
memset(&inPicture, 0, sizeof(inPicture));
inPicture.dataLen = inHeader->nFilledLen;
inPicture.pStream = inHeader->pBuffer + inHeader->nOffset;
inPicture.picId = mPicId;
inPicture.intraConcealmentMethod = 1;
H264SwDecPicture decodedPicture;
while (inPicture.dataLen > 0) {
ret = H264SwDecDecode(mHandle, &inPicture, &outPicture);
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY ||
ret == H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY) {
inPicture.dataLen -= (u32)(outPicture.pStrmCurrPos - inPicture.pStream);
inPicture.pStream = outPicture.pStrmCurrPos;
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY) {
mHeadersDecoded = true;
H264SwDecInfo decoderInfo;
CHECK(H264SwDecGetInfo(mHandle, &decoderInfo) == H264SWDEC_OK);
SoftVideoDecoderOMXComponent::CropSettingsMode cropSettingsMode =
handleCropParams(decoderInfo);
handlePortSettingsChange(
&portWillReset, decoderInfo.picWidth, decoderInfo.picHeight,
cropSettingsMode);
}
} else {
if (portWillReset) {
if (H264SwDecNextPicture(mHandle, &decodedPicture, 0)
== H264SWDEC_PIC_RDY) {
saveFirstOutputBuffer(
decodedPicture.picId,
(uint8_t *)decodedPicture.pOutputPicture);
}
}
inPicture.dataLen = 0;
if (ret < 0) {
ALOGE("Decoder failed: %d", ret);
notify(OMX_EventError, OMX_ErrorUndefined,
ERROR_MALFORMED, NULL);
mSignalledError = true;
return;
}
}
}
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
if (portWillReset) {
return;
}
if (mFirstPicture && !outQueue.empty()) {
drainOneOutputBuffer(mFirstPictureId, mFirstPicture);
delete[] mFirstPicture;
mFirstPicture = NULL;
mFirstPictureId = -1;
}
drainAllOutputBuffers(false /* eos */);
}
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
CWE ID: CWE-20 | void SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
if (mHeadersDecoded) {
drainAllOutputBuffers(false /* eos */);
}
H264SwDecRet ret = H264SWDEC_PIC_RDY;
bool portWillReset = false;
while ((mEOSStatus != INPUT_DATA_AVAILABLE || !inQueue.empty())
&& outQueue.size() == kNumOutputBuffers) {
if (mEOSStatus == INPUT_EOS_SEEN) {
drainAllOutputBuffers(true /* eos */);
return;
}
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
++mPicId;
OMX_BUFFERHEADERTYPE *header = new OMX_BUFFERHEADERTYPE;
memset(header, 0, sizeof(OMX_BUFFERHEADERTYPE));
header->nTimeStamp = inHeader->nTimeStamp;
header->nFlags = inHeader->nFlags;
if (header->nFlags & OMX_BUFFERFLAG_EOS) {
mEOSStatus = INPUT_EOS_SEEN;
}
mPicToHeaderMap.add(mPicId, header);
inQueue.erase(inQueue.begin());
H264SwDecInput inPicture;
H264SwDecOutput outPicture;
memset(&inPicture, 0, sizeof(inPicture));
inPicture.dataLen = inHeader->nFilledLen;
inPicture.pStream = inHeader->pBuffer + inHeader->nOffset;
inPicture.picId = mPicId;
inPicture.intraConcealmentMethod = 1;
H264SwDecPicture decodedPicture;
while (inPicture.dataLen > 0) {
ret = H264SwDecDecode(mHandle, &inPicture, &outPicture);
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY ||
ret == H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY) {
inPicture.dataLen -= (u32)(outPicture.pStrmCurrPos - inPicture.pStream);
inPicture.pStream = outPicture.pStrmCurrPos;
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY) {
mHeadersDecoded = true;
H264SwDecInfo decoderInfo;
CHECK(H264SwDecGetInfo(mHandle, &decoderInfo) == H264SWDEC_OK);
SoftVideoDecoderOMXComponent::CropSettingsMode cropSettingsMode =
handleCropParams(decoderInfo);
handlePortSettingsChange(
&portWillReset, decoderInfo.picWidth, decoderInfo.picHeight,
cropSettingsMode);
}
} else {
if (portWillReset) {
if (H264SwDecNextPicture(mHandle, &decodedPicture, 0)
== H264SWDEC_PIC_RDY) {
saveFirstOutputBuffer(
decodedPicture.picId,
(uint8_t *)decodedPicture.pOutputPicture);
}
}
inPicture.dataLen = 0;
if (ret < 0) {
ALOGE("Decoder failed: %d", ret);
notify(OMX_EventError, OMX_ErrorUndefined,
ERROR_MALFORMED, NULL);
mSignalledError = true;
return;
}
}
}
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
if (portWillReset) {
return;
}
if (mFirstPicture && !outQueue.empty()) {
if (!drainOneOutputBuffer(mFirstPictureId, mFirstPicture)) {
ALOGE("Drain failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
delete[] mFirstPicture;
mFirstPicture = NULL;
mFirstPictureId = -1;
}
drainAllOutputBuffers(false /* eos */);
}
}
| 174,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int sco_sock_bind(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
struct sockaddr_sco *sa = (struct sockaddr_sco *) addr;
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_SEQPACKET) {
err = -EINVAL;
goto done;
}
bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr);
sk->sk_state = BT_BOUND;
done:
release_sock(sk);
return err;
}
Commit Message: bluetooth: Validate socket address length in sco_sock_bind().
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int sco_sock_bind(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
struct sockaddr_sco *sa = (struct sockaddr_sco *) addr;
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
if (addr_len < sizeof(struct sockaddr_sco))
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_SEQPACKET) {
err = -EINVAL;
goto done;
}
bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr);
sk->sk_state = BT_BOUND;
done:
release_sock(sk);
return err;
}
| 167,532 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl3_connect(SSL *s)
{
BUF_MEM *buf=NULL;
unsigned long Time=(unsigned long)time(NULL);
void (*cb)(const SSL *ssl,int type,int val)=NULL;
int ret= -1;
int new_state,state,skip=0;
RAND_add(&Time,sizeof(Time),0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb=s->info_callback;
else if (s->ctx->info_callback != NULL)
cb=s->ctx->info_callback;
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
#ifndef OPENSSL_NO_HEARTBEATS
/* If we're awaiting a HeartbeatResponse, pretend we
* already got and don't await it anymore, because
* Heartbeats don't make sense during handshakes anyway.
*/
if (s->tlsext_hb_pending)
{
s->tlsext_hb_pending = 0;
s->tlsext_hb_seq++;
}
#endif
for (;;)
{
state=s->state;
switch(s->state)
{
case SSL_ST_RENEGOTIATE:
s->renegotiate=1;
s->state=SSL_ST_CONNECT;
s->ctx->stats.sess_connect_renegotiate++;
/* break */
case SSL_ST_BEFORE:
case SSL_ST_CONNECT:
case SSL_ST_BEFORE|SSL_ST_CONNECT:
case SSL_ST_OK|SSL_ST_CONNECT:
s->server=0;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
if ((s->version & 0xff00 ) != 0x0300)
{
SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
ret = -1;
goto end;
}
/* s->version=SSL3_VERSION; */
s->type=SSL_ST_CONNECT;
if (s->init_buf == NULL)
{
if ((buf=BUF_MEM_new()) == NULL)
{
ret= -1;
goto end;
}
if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
{
ret= -1;
goto end;
}
s->init_buf=buf;
buf=NULL;
}
if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
/* setup buffing BIO */
if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
/* don't push the buffering BIO quite yet */
ssl3_init_finished_mac(s);
s->state=SSL3_ST_CW_CLNT_HELLO_A;
s->ctx->stats.sess_connect++;
s->init_num=0;
break;
case SSL3_ST_CW_CLNT_HELLO_A:
case SSL3_ST_CW_CLNT_HELLO_B:
s->shutdown=0;
ret=ssl3_client_hello(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_SRVR_HELLO_A;
s->init_num=0;
/* turn on buffering for the next lot of output */
if (s->bbio != s->wbio)
s->wbio=BIO_push(s->bbio,s->wbio);
break;
case SSL3_ST_CR_SRVR_HELLO_A:
case SSL3_ST_CR_SRVR_HELLO_B:
ret=ssl3_get_server_hello(s);
if (ret <= 0) goto end;
if (s->hit)
{
s->state=SSL3_ST_CR_FINISHED_A;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_ticket_expected)
{
/* receive renewed session ticket */
s->state=SSL3_ST_CR_SESSION_TICKET_A;
}
#endif
}
else
s->state=SSL3_ST_CR_CERT_A;
s->init_num=0;
break;
case SSL3_ST_CR_CERT_A:
case SSL3_ST_CR_CERT_B:
#ifndef OPENSSL_NO_TLSEXT
ret=ssl3_check_finished(s);
if (ret <= 0) goto end;
if (ret == 2)
{
s->hit = 1;
if (s->tlsext_ticket_expected)
s->state=SSL3_ST_CR_SESSION_TICKET_A;
else
s->state=SSL3_ST_CR_FINISHED_A;
s->init_num=0;
break;
}
#endif
/* Check if it is anon DH/ECDH */
/* or PSK */
if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
!(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
ret=ssl3_get_server_certificate(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_status_expected)
s->state=SSL3_ST_CR_CERT_STATUS_A;
else
s->state=SSL3_ST_CR_KEY_EXCH_A;
}
else
{
skip = 1;
s->state=SSL3_ST_CR_KEY_EXCH_A;
}
#else
}
else
skip=1;
s->state=SSL3_ST_CR_KEY_EXCH_A;
#endif
s->init_num=0;
break;
case SSL3_ST_CR_KEY_EXCH_A:
case SSL3_ST_CR_KEY_EXCH_B:
ret=ssl3_get_key_exchange(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_CERT_REQ_A;
s->init_num=0;
/* at this point we check that we have the
* required stuff from the server */
if (!ssl3_check_cert_and_algorithm(s))
{
ret= -1;
goto end;
}
break;
case SSL3_ST_CR_CERT_REQ_A:
case SSL3_ST_CR_CERT_REQ_B:
ret=ssl3_get_certificate_request(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_SRVR_DONE_A;
s->init_num=0;
break;
case SSL3_ST_CR_SRVR_DONE_A:
case SSL3_ST_CR_SRVR_DONE_B:
ret=ssl3_get_server_done(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_SRP
if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP)
{
if ((ret = SRP_Calc_A_param(s))<=0)
{
SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC);
ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
goto end;
}
}
#endif
if (s->s3->tmp.cert_req)
s->state=SSL3_ST_CW_CERT_A;
else
s->state=SSL3_ST_CW_KEY_EXCH_A;
s->init_num=0;
break;
case SSL3_ST_CW_CERT_A:
case SSL3_ST_CW_CERT_B:
case SSL3_ST_CW_CERT_C:
case SSL3_ST_CW_CERT_D:
ret=ssl3_send_client_certificate(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CW_KEY_EXCH_A;
s->init_num=0;
break;
case SSL3_ST_CW_KEY_EXCH_A:
case SSL3_ST_CW_KEY_EXCH_B:
ret=ssl3_send_client_key_exchange(s);
if (ret <= 0) goto end;
/* EAY EAY EAY need to check for DH fix cert
* sent back */
/* For TLS, cert_req is set to 2, so a cert chain
* of nothing is sent, but no verify packet is sent */
/* XXX: For now, we do not support client
* authentication in ECDH cipher suites with
* ECDH (rather than ECDSA) certificates.
* We need to skip the certificate verify
* message when client's ECDH public key is sent
* inside the client certificate.
*/
if (s->s3->tmp.cert_req == 1)
{
s->state=SSL3_ST_CW_CERT_VRFY_A;
}
else
{
s->state=SSL3_ST_CW_CHANGE_A;
s->s3->change_cipher_spec=0;
}
if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
{
s->state=SSL3_ST_CW_CHANGE_A;
s->s3->change_cipher_spec=0;
}
s->init_num=0;
break;
case SSL3_ST_CW_CERT_VRFY_A:
case SSL3_ST_CW_CERT_VRFY_B:
ret=ssl3_send_client_verify(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CW_CHANGE_A;
s->init_num=0;
s->s3->change_cipher_spec=0;
break;
case SSL3_ST_CW_CHANGE_A:
case SSL3_ST_CW_CHANGE_B:
ret=ssl3_send_change_cipher_spec(s,
SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
if (ret <= 0) goto end;
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_CW_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_CW_NEXT_PROTO_A;
else
s->state=SSL3_ST_CW_FINISHED_A;
#endif
s->init_num=0;
s->session->cipher=s->s3->tmp.new_cipher;
#ifdef OPENSSL_NO_COMP
s->session->compress_meth=0;
#else
if (s->s3->tmp.new_compression == NULL)
s->session->compress_meth=0;
else
s->session->compress_meth=
s->s3->tmp.new_compression->id;
#endif
if (!s->method->ssl3_enc->setup_key_block(s))
{
ret= -1;
goto end;
}
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_CLIENT_WRITE))
{
ret= -1;
goto end;
}
break;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
case SSL3_ST_CW_NEXT_PROTO_A:
case SSL3_ST_CW_NEXT_PROTO_B:
ret=ssl3_send_next_proto(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CW_FINISHED_A;
break;
#endif
case SSL3_ST_CW_FINISHED_A:
case SSL3_ST_CW_FINISHED_B:
ret=ssl3_send_finished(s,
SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
s->method->ssl3_enc->client_finished_label,
s->method->ssl3_enc->client_finished_label_len);
if (ret <= 0) goto end;
s->state=SSL3_ST_CW_FLUSH;
/* clear flags */
s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
if (s->hit)
{
s->s3->tmp.next_state=SSL_ST_OK;
if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
{
s->state=SSL_ST_OK;
s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
s->s3->delay_buf_pop_ret=0;
}
}
else
{
#ifndef OPENSSL_NO_TLSEXT
/* Allow NewSessionTicket if ticket expected */
if (s->tlsext_ticket_expected)
s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
else
#endif
s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
}
s->init_num=0;
break;
#ifndef OPENSSL_NO_TLSEXT
case SSL3_ST_CR_SESSION_TICKET_A:
case SSL3_ST_CR_SESSION_TICKET_B:
ret=ssl3_get_new_session_ticket(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_FINISHED_A;
s->init_num=0;
break;
case SSL3_ST_CR_CERT_STATUS_A:
case SSL3_ST_CR_CERT_STATUS_B:
ret=ssl3_get_cert_status(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_KEY_EXCH_A;
s->init_num=0;
break;
#endif
case SSL3_ST_CR_FINISHED_A:
case SSL3_ST_CR_FINISHED_B:
ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
SSL3_ST_CR_FINISHED_B);
if (ret <= 0) goto end;
if (s->hit)
s->state=SSL3_ST_CW_CHANGE_A;
else
s->state=SSL_ST_OK;
s->init_num=0;
break;
case SSL3_ST_CW_FLUSH:
s->rwstate=SSL_WRITING;
if (BIO_flush(s->wbio) <= 0)
{
ret= -1;
goto end;
}
s->rwstate=SSL_NOTHING;
s->state=s->s3->tmp.next_state;
break;
case SSL_ST_OK:
/* clean a few things up */
ssl3_cleanup_key_block(s);
if (s->init_buf != NULL)
{
BUF_MEM_free(s->init_buf);
s->init_buf=NULL;
}
/* If we are not 'joining' the last two packets,
* remove the buffering now */
if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
ssl_free_wbio_buffer(s);
/* else do it later in ssl3_write */
s->init_num=0;
s->renegotiate=0;
s->new_session=0;
ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
if (s->hit) s->ctx->stats.sess_hit++;
ret=1;
/* s->server=0; */
s->handshake_func=ssl3_connect;
s->ctx->stats.sess_connect_good++;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
goto end;
/* break; */
default:
SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
ret= -1;
goto end;
/* break; */
}
/* did we do anything */
if (!s->s3->tmp.reuse_message && !skip)
{
if (s->debug)
{
if ((ret=BIO_flush(s->wbio)) <= 0)
goto end;
}
if ((cb != NULL) && (s->state != state))
{
new_state=s->state;
s->state=state;
cb(s,SSL_CB_CONNECT_LOOP,1);
s->state=new_state;
}
}
skip=0;
}
Commit Message:
CWE ID: CWE-310 | int ssl3_connect(SSL *s)
{
BUF_MEM *buf=NULL;
unsigned long Time=(unsigned long)time(NULL);
void (*cb)(const SSL *ssl,int type,int val)=NULL;
int ret= -1;
int new_state,state,skip=0;
RAND_add(&Time,sizeof(Time),0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb=s->info_callback;
else if (s->ctx->info_callback != NULL)
cb=s->ctx->info_callback;
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
#ifndef OPENSSL_NO_HEARTBEATS
/* If we're awaiting a HeartbeatResponse, pretend we
* already got and don't await it anymore, because
* Heartbeats don't make sense during handshakes anyway.
*/
if (s->tlsext_hb_pending)
{
s->tlsext_hb_pending = 0;
s->tlsext_hb_seq++;
}
#endif
for (;;)
{
state=s->state;
switch(s->state)
{
case SSL_ST_RENEGOTIATE:
s->renegotiate=1;
s->state=SSL_ST_CONNECT;
s->ctx->stats.sess_connect_renegotiate++;
/* break */
case SSL_ST_BEFORE:
case SSL_ST_CONNECT:
case SSL_ST_BEFORE|SSL_ST_CONNECT:
case SSL_ST_OK|SSL_ST_CONNECT:
s->server=0;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
if ((s->version & 0xff00 ) != 0x0300)
{
SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
ret = -1;
goto end;
}
/* s->version=SSL3_VERSION; */
s->type=SSL_ST_CONNECT;
if (s->init_buf == NULL)
{
if ((buf=BUF_MEM_new()) == NULL)
{
ret= -1;
goto end;
}
if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
{
ret= -1;
goto end;
}
s->init_buf=buf;
buf=NULL;
}
if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
/* setup buffing BIO */
if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
/* don't push the buffering BIO quite yet */
ssl3_init_finished_mac(s);
s->state=SSL3_ST_CW_CLNT_HELLO_A;
s->ctx->stats.sess_connect++;
s->init_num=0;
break;
case SSL3_ST_CW_CLNT_HELLO_A:
case SSL3_ST_CW_CLNT_HELLO_B:
s->shutdown=0;
ret=ssl3_client_hello(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_SRVR_HELLO_A;
s->init_num=0;
/* turn on buffering for the next lot of output */
if (s->bbio != s->wbio)
s->wbio=BIO_push(s->bbio,s->wbio);
break;
case SSL3_ST_CR_SRVR_HELLO_A:
case SSL3_ST_CR_SRVR_HELLO_B:
ret=ssl3_get_server_hello(s);
if (ret <= 0) goto end;
if (s->hit)
{
s->state=SSL3_ST_CR_FINISHED_A;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_ticket_expected)
{
/* receive renewed session ticket */
s->state=SSL3_ST_CR_SESSION_TICKET_A;
}
#endif
}
else
s->state=SSL3_ST_CR_CERT_A;
s->init_num=0;
break;
case SSL3_ST_CR_CERT_A:
case SSL3_ST_CR_CERT_B:
#ifndef OPENSSL_NO_TLSEXT
ret=ssl3_check_finished(s);
if (ret <= 0) goto end;
if (ret == 2)
{
s->hit = 1;
if (s->tlsext_ticket_expected)
s->state=SSL3_ST_CR_SESSION_TICKET_A;
else
s->state=SSL3_ST_CR_FINISHED_A;
s->init_num=0;
break;
}
#endif
/* Check if it is anon DH/ECDH */
/* or PSK */
if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
!(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
ret=ssl3_get_server_certificate(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_status_expected)
s->state=SSL3_ST_CR_CERT_STATUS_A;
else
s->state=SSL3_ST_CR_KEY_EXCH_A;
}
else
{
skip = 1;
s->state=SSL3_ST_CR_KEY_EXCH_A;
}
#else
}
else
skip=1;
s->state=SSL3_ST_CR_KEY_EXCH_A;
#endif
s->init_num=0;
break;
case SSL3_ST_CR_KEY_EXCH_A:
case SSL3_ST_CR_KEY_EXCH_B:
ret=ssl3_get_key_exchange(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_CERT_REQ_A;
s->init_num=0;
/* at this point we check that we have the
* required stuff from the server */
if (!ssl3_check_cert_and_algorithm(s))
{
ret= -1;
goto end;
}
break;
case SSL3_ST_CR_CERT_REQ_A:
case SSL3_ST_CR_CERT_REQ_B:
ret=ssl3_get_certificate_request(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_SRVR_DONE_A;
s->init_num=0;
break;
case SSL3_ST_CR_SRVR_DONE_A:
case SSL3_ST_CR_SRVR_DONE_B:
ret=ssl3_get_server_done(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_SRP
if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP)
{
if ((ret = SRP_Calc_A_param(s))<=0)
{
SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC);
ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
goto end;
}
}
#endif
if (s->s3->tmp.cert_req)
s->state=SSL3_ST_CW_CERT_A;
else
s->state=SSL3_ST_CW_KEY_EXCH_A;
s->init_num=0;
break;
case SSL3_ST_CW_CERT_A:
case SSL3_ST_CW_CERT_B:
case SSL3_ST_CW_CERT_C:
case SSL3_ST_CW_CERT_D:
ret=ssl3_send_client_certificate(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CW_KEY_EXCH_A;
s->init_num=0;
break;
case SSL3_ST_CW_KEY_EXCH_A:
case SSL3_ST_CW_KEY_EXCH_B:
ret=ssl3_send_client_key_exchange(s);
if (ret <= 0) goto end;
/* EAY EAY EAY need to check for DH fix cert
* sent back */
/* For TLS, cert_req is set to 2, so a cert chain
* of nothing is sent, but no verify packet is sent */
/* XXX: For now, we do not support client
* authentication in ECDH cipher suites with
* ECDH (rather than ECDSA) certificates.
* We need to skip the certificate verify
* message when client's ECDH public key is sent
* inside the client certificate.
*/
if (s->s3->tmp.cert_req == 1)
{
s->state=SSL3_ST_CW_CERT_VRFY_A;
}
else
{
s->state=SSL3_ST_CW_CHANGE_A;
s->s3->change_cipher_spec=0;
}
if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
{
s->state=SSL3_ST_CW_CHANGE_A;
s->s3->change_cipher_spec=0;
}
s->init_num=0;
break;
case SSL3_ST_CW_CERT_VRFY_A:
case SSL3_ST_CW_CERT_VRFY_B:
ret=ssl3_send_client_verify(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CW_CHANGE_A;
s->init_num=0;
s->s3->change_cipher_spec=0;
break;
case SSL3_ST_CW_CHANGE_A:
case SSL3_ST_CW_CHANGE_B:
ret=ssl3_send_change_cipher_spec(s,
SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
if (ret <= 0) goto end;
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_CW_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_CW_NEXT_PROTO_A;
else
s->state=SSL3_ST_CW_FINISHED_A;
#endif
s->init_num=0;
s->session->cipher=s->s3->tmp.new_cipher;
#ifdef OPENSSL_NO_COMP
s->session->compress_meth=0;
#else
if (s->s3->tmp.new_compression == NULL)
s->session->compress_meth=0;
else
s->session->compress_meth=
s->s3->tmp.new_compression->id;
#endif
if (!s->method->ssl3_enc->setup_key_block(s))
{
ret= -1;
goto end;
}
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_CLIENT_WRITE))
{
ret= -1;
goto end;
}
break;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
case SSL3_ST_CW_NEXT_PROTO_A:
case SSL3_ST_CW_NEXT_PROTO_B:
ret=ssl3_send_next_proto(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CW_FINISHED_A;
break;
#endif
case SSL3_ST_CW_FINISHED_A:
case SSL3_ST_CW_FINISHED_B:
ret=ssl3_send_finished(s,
SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
s->method->ssl3_enc->client_finished_label,
s->method->ssl3_enc->client_finished_label_len);
if (ret <= 0) goto end;
s->state=SSL3_ST_CW_FLUSH;
/* clear flags */
s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
if (s->hit)
{
s->s3->tmp.next_state=SSL_ST_OK;
if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
{
s->state=SSL_ST_OK;
s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
s->s3->delay_buf_pop_ret=0;
}
}
else
{
#ifndef OPENSSL_NO_TLSEXT
/* Allow NewSessionTicket if ticket expected */
if (s->tlsext_ticket_expected)
s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
else
#endif
s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
}
s->init_num=0;
break;
#ifndef OPENSSL_NO_TLSEXT
case SSL3_ST_CR_SESSION_TICKET_A:
case SSL3_ST_CR_SESSION_TICKET_B:
ret=ssl3_get_new_session_ticket(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_FINISHED_A;
s->init_num=0;
break;
case SSL3_ST_CR_CERT_STATUS_A:
case SSL3_ST_CR_CERT_STATUS_B:
ret=ssl3_get_cert_status(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_CR_KEY_EXCH_A;
s->init_num=0;
break;
#endif
case SSL3_ST_CR_FINISHED_A:
case SSL3_ST_CR_FINISHED_B:
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
SSL3_ST_CR_FINISHED_B);
if (ret <= 0) goto end;
if (s->hit)
s->state=SSL3_ST_CW_CHANGE_A;
else
s->state=SSL_ST_OK;
s->init_num=0;
break;
case SSL3_ST_CW_FLUSH:
s->rwstate=SSL_WRITING;
if (BIO_flush(s->wbio) <= 0)
{
ret= -1;
goto end;
}
s->rwstate=SSL_NOTHING;
s->state=s->s3->tmp.next_state;
break;
case SSL_ST_OK:
/* clean a few things up */
ssl3_cleanup_key_block(s);
if (s->init_buf != NULL)
{
BUF_MEM_free(s->init_buf);
s->init_buf=NULL;
}
/* If we are not 'joining' the last two packets,
* remove the buffering now */
if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
ssl_free_wbio_buffer(s);
/* else do it later in ssl3_write */
s->init_num=0;
s->renegotiate=0;
s->new_session=0;
ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
if (s->hit) s->ctx->stats.sess_hit++;
ret=1;
/* s->server=0; */
s->handshake_func=ssl3_connect;
s->ctx->stats.sess_connect_good++;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
goto end;
/* break; */
default:
SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
ret= -1;
goto end;
/* break; */
}
/* did we do anything */
if (!s->s3->tmp.reuse_message && !skip)
{
if (s->debug)
{
if ((ret=BIO_flush(s->wbio)) <= 0)
goto end;
}
if ((cb != NULL) && (s->state != state))
{
new_state=s->state;
s->state=state;
cb(s,SSL_CB_CONNECT_LOOP,1);
s->state=new_state;
}
}
skip=0;
}
| 165,280 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void GM2TabStyle::PaintBackgroundStroke(gfx::Canvas* canvas,
bool active,
SkColor stroke_color) const {
SkPath outer_path =
GetPath(TabStyle::PathType::kBorder, canvas->image_scale(), active);
gfx::ScopedCanvas scoped_canvas(canvas);
float scale = canvas->UndoDeviceScaleFactor();
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setColor(stroke_color);
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(GetStrokeThickness(active) * scale);
canvas->DrawPath(outer_path, flags);
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20 | void GM2TabStyle::PaintBackgroundStroke(gfx::Canvas* canvas,
TabState active_state,
SkColor stroke_color) const {
SkPath outer_path =
GetPath(TabStyle::PathType::kBorder, canvas->image_scale(),
active_state == TAB_ACTIVE);
gfx::ScopedCanvas scoped_canvas(canvas);
float scale = canvas->UndoDeviceScaleFactor();
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setColor(stroke_color);
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(GetStrokeThickness(active_state == TAB_ACTIVE) * scale);
canvas->DrawPath(outer_path, flags);
}
| 172,522 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void SubpelVarianceTest<vp9_subp_avg_variance_fn_t>::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();
sec_[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, sec_));
const unsigned int var2 = subpel_avg_variance_ref(ref_, src_, sec_,
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<vp9_subp_avg_variance_fn_t>::RefTest() {
void SubpelVarianceTest<SubpixAvgVarMxNFunc>::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();
sec_[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_;
CONVERT_TO_SHORTPTR(sec_)[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, sec_));
const unsigned int var2 = subpel_avg_variance_ref(ref_, src_, sec_,
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;
}
}
}
| 174,588 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod5(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject());
impl->overloadedMethod(callback);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod5(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject());
impl->overloadedMethod(callback);
return JSValue::encode(jsUndefined());
}
| 170,604 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void __detach_mounts(struct dentry *dentry)
{
struct mountpoint *mp;
struct mount *mnt;
namespace_lock();
mp = lookup_mountpoint(dentry);
if (!mp)
goto out_unlock;
lock_mount_hash();
while (!hlist_empty(&mp->m_list)) {
mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
umount_tree(mnt, 0);
}
unlock_mount_hash();
put_mountpoint(mp);
out_unlock:
namespace_unlock();
}
Commit Message: mnt: Honor MNT_LOCKED when detaching mounts
Modify umount(MNT_DETACH) to keep mounts in the hash table that are
locked to their parent mounts, when the parent is lazily unmounted.
In mntput_no_expire detach the children from the hash table, depending
on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children.
In __detach_mounts if there are any mounts that have been unmounted
but still are on the list of mounts of a mountpoint, remove their
children from the mount hash table and those children to the unmounted
list so they won't linger potentially indefinitely waiting for their
final mntput, now that the mounts serve no purpose.
Cc: [email protected]
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-284 | void __detach_mounts(struct dentry *dentry)
{
struct mountpoint *mp;
struct mount *mnt;
namespace_lock();
mp = lookup_mountpoint(dentry);
if (!mp)
goto out_unlock;
lock_mount_hash();
while (!hlist_empty(&mp->m_list)) {
mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
hlist_add_head(&p->mnt_umount.s_list, &unmounted);
umount_mnt(p);
}
}
else umount_tree(mnt, 0);
}
unlock_mount_hash();
put_mountpoint(mp);
out_unlock:
namespace_unlock();
}
| 167,588 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
if (cp == NULL) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
Commit Message: (for 4.9.3) CVE-2018-14469/ISAKMP: Add a missing bounds check
In ikev1_n_print() check bounds before trying to fetch the replay detection
status.
This fixes a buffer over-read discovered by Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
if (cp == NULL) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_TCHECK_32BITS(cp);
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
| 169,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. Remember, I want response with just the fixed code only, No explanation. | Code: static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
if (copy_file("/etc/skel/.zshrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.zshrc");
}
}
else { //
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR);
fclose(fp);
fs_logger2("touch", fname);
}
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
if (copy_file("/etc/skel/.cshrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.cshrc");
}
}
else { //
/* coverity[toctou] */
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR);
fclose(fp);
fs_logger2("touch", fname);
}
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
if (copy_file("/etc/skel/.bashrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.bashrc");
}
}
free(fname);
}
}
Commit Message: replace copy_file with copy_file_as_user
CWE ID: CWE-269 | static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
| 170,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. Remember, I want response with just the fixed code only, No explanation. | Code: SchedulerObject::_continue(std::string key, std::string &/*reason*/, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
scheduler.enqueueActOnJobMyself(id,JA_CONTINUE_JOBS,true);
return true;
}
Commit Message:
CWE ID: CWE-20 | SchedulerObject::_continue(std::string key, std::string &/*reason*/, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster <= 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
scheduler.enqueueActOnJobMyself(id,JA_CONTINUE_JOBS,true);
return true;
}
| 164,831 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_MINIT_FUNCTION(spl_array)
{
REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
spl_handler_ArrayObject.get_properties = spl_array_get_properties;
spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
spl_handler_ArrayObject.read_property = spl_array_read_property;
spl_handler_ArrayObject.write_property = spl_array_write_property;
spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
spl_handler_ArrayObject.has_property = spl_array_has_property;
spl_handler_ArrayObject.unset_property = spl_array_unset_property;
spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
return SUCCESS;
}
Commit Message: Fixed ##72433: Use After Free Vulnerability in PHP's GC algorithm and unserialize
CWE ID: CWE-416 | PHP_MINIT_FUNCTION(spl_array)
{
REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
spl_handler_ArrayObject.get_properties = spl_array_get_properties;
spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
spl_handler_ArrayObject.get_gc = spl_array_get_gc;
spl_handler_ArrayObject.read_property = spl_array_read_property;
spl_handler_ArrayObject.write_property = spl_array_write_property;
spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
spl_handler_ArrayObject.has_property = spl_array_has_property;
spl_handler_ArrayObject.unset_property = spl_array_unset_property;
spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
return SUCCESS;
}
| 167,025 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID(
int window_id,
std::string* error) {
Browser* browser = NULL;
if (!GetBrowserFromWindowID(chrome_details_, window_id, &browser, error))
return nullptr;
WebContents* contents = browser->tab_strip_model()->GetActiveWebContents();
if (!contents) {
*error = "No active web contents to capture";
return nullptr;
}
if (!extension()->permissions_data()->CanCaptureVisiblePage(
SessionTabHelper::IdForTab(contents).id(), error)) {
return nullptr;
}
return contents;
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
CWE ID: CWE-20 | WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID(
int window_id,
std::string* error) {
Browser* browser = NULL;
if (!GetBrowserFromWindowID(chrome_details_, window_id, &browser, error))
return nullptr;
WebContents* contents = browser->tab_strip_model()->GetActiveWebContents();
if (!contents) {
*error = "No active web contents to capture";
return nullptr;
}
if (!extension()->permissions_data()->CanCaptureVisiblePage(
contents->GetLastCommittedURL(), extension(),
SessionTabHelper::IdForTab(contents).id(), error)) {
return nullptr;
}
return contents;
}
| 173,229 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void UsbFindDevicesFunction::OnGetDevicesComplete(
const std::vector<scoped_refptr<UsbDevice>>& devices) {
result_.reset(new base::ListValue());
barrier_ = base::BarrierClosure(
devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this));
for (const scoped_refptr<UsbDevice>& device : devices) {
if (device->vendor_id() != vendor_id_ ||
device->product_id() != product_id_) {
barrier_.Run();
} else {
device->OpenInterface(
interface_id_,
base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this));
}
}
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399 | void UsbFindDevicesFunction::OnGetDevicesComplete(
const std::vector<scoped_refptr<UsbDevice>>& devices) {
result_.reset(new base::ListValue());
barrier_ = base::BarrierClosure(
devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this));
for (const scoped_refptr<UsbDevice>& device : devices) {
if (device->vendor_id() != vendor_id_ ||
device->product_id() != product_id_) {
barrier_.Run();
} else {
device->Open(base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this));
}
}
}
| 171,703 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)
{
major = 1;
minor = 0;
build = 0;
revision = 27;
}
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 | void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)
| 174,379 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[]) {
p_fm_config_conx_hdlt hdl;
int instance = 0;
fm_mgr_config_errno_t res;
char *rem_addr = NULL;
char *community = "public";
char Opts[256];
int arg;
char *command;
int i;
/* Get options at the command line (overide default values) */
strcpy(Opts, "i:d:h-");
while ((arg = getopt(argc, argv, Opts)) != EOF) {
switch (arg) {
case 'h':
case '-':
usage(argv[0]);
return(0);
case 'i':
instance = atol(optarg);
break;
case 'd':
rem_addr = optarg;
break;
default:
usage(argv[0]);
return(-1);
}
}
if(optind >= argc){
fprintf(stderr, "Command required\n");
usage(argv[0]);
return -1;
}
command = argv[optind++];
printf("Connecting to %s FM instance %d\n", (rem_addr==NULL) ? "LOCAL":rem_addr, instance);
if((res = fm_mgr_config_init(&hdl,instance, rem_addr, community)) != FM_CONF_OK)
{
fprintf(stderr, "Failed to initialize the client handle: %d\n", res);
goto die_clean;
}
if((res = fm_mgr_config_connect(hdl)) != FM_CONF_OK)
{
fprintf(stderr, "Failed to connect: (%d) %s\n",res,fm_mgr_get_error_str(res));
goto die_clean;
}
for(i=0;i<commandListLen;i++){
if(strcmp(command,commandList[i].name) == 0){
return commandList[i].cmdPtr(hdl, commandList[i].mgr, (argc - optind), &argv[optind]);
}
}
fprintf(stderr, "Command (%s) is not valid\n",command);
usage(argv[0]);
res = -1;
die_clean:
if (hdl) free(hdl);
return res;
}
Commit Message: Fix scripts and code that use well-known tmp files.
CWE ID: CWE-362 | int main(int argc, char *argv[]) {
p_fm_config_conx_hdlt hdl = NULL;
int instance = 0;
fm_mgr_config_errno_t res;
char *rem_addr = NULL;
char *community = "public";
char Opts[256];
int arg;
char *command;
int i;
/* Get options at the command line (overide default values) */
strcpy(Opts, "i:d:h-");
while ((arg = getopt(argc, argv, Opts)) != EOF) {
switch (arg) {
case 'h':
case '-':
usage(argv[0]);
return(0);
case 'i':
instance = atol(optarg);
break;
case 'd':
rem_addr = optarg;
break;
default:
usage(argv[0]);
return(-1);
}
}
if(optind >= argc){
fprintf(stderr, "Command required\n");
usage(argv[0]);
return -1;
}
command = argv[optind++];
printf("Connecting to %s FM instance %d\n", (rem_addr==NULL) ? "LOCAL":rem_addr, instance);
if((res = fm_mgr_config_init(&hdl,instance, rem_addr, community)) != FM_CONF_OK)
{
fprintf(stderr, "Failed to initialize the client handle: %d\n", res);
goto cleanup;
}
if((res = fm_mgr_config_connect(hdl)) != FM_CONF_OK)
{
fprintf(stderr, "Failed to connect: (%d) %s\n",res,fm_mgr_get_error_str(res));
goto cleanup;
}
for(i=0;i<commandListLen;i++){
if(strcmp(command,commandList[i].name) == 0){
res = commandList[i].cmdPtr(hdl, commandList[i].mgr, (argc - optind), &argv[optind]);
goto cleanup;
}
}
fprintf(stderr, "Command (%s) is not valid\n",command);
usage(argv[0]);
res = -1;
cleanup:
if (hdl)
{
if (hdl->sm_hdl)
{
if (hdl->sm_hdl->c_path[0])
unlink(hdl->sm_hdl->c_path);
}
if (hdl->pm_hdl)
{
if (hdl->pm_hdl->c_path[0])
unlink(hdl->pm_hdl->c_path);
}
if (hdl->fe_hdl)
{
if (hdl->fe_hdl->c_path[0])
unlink(hdl->fe_hdl->c_path);
}
free(hdl);
}
return res;
}
| 170,127 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable(
const GURL& site_url) {
JNIEnv* env = AttachCurrentThread();
Java_MostVisitedURLsObserver_onIconMadeAvailable(
env, observer_, ConvertUTF8ToJavaString(env, site_url.spec()));
}
Commit Message: Rename MostVisitedSites.MostVisitedURLsObserver to Observer.
BUG=677672
Review-Url: https://codereview.chromium.org/2697543002
Cr-Commit-Position: refs/heads/master@{#449958}
CWE ID: CWE-17 | void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable(
const GURL& site_url) {
JNIEnv* env = AttachCurrentThread();
Java_Observer_onIconMadeAvailable(
env, observer_, ConvertUTF8ToJavaString(env, site_url.spec()));
}
| 172,034 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
sp<ABuffer> data = bufferMeta->getBuffer(
header, portIndex == kPortIndexInput /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
sp<ABuffer> data = bufferMeta->getBuffer(
header, false /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
| 174,142 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
if (ShowingInterstitialPage()) {
GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
return;
}
RenderWidgetHostView* const fullscreen_view =
GetFullscreenRenderWidgetHostView();
if (fullscreen_view) {
fullscreen_view->Focus();
return;
}
GetRenderViewHost()->SetInitialFocus(reverse);
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
if (ShowingInterstitialPage()) {
interstitial_page_->FocusThroughTabTraversal(reverse);
return;
}
RenderWidgetHostView* const fullscreen_view =
GetFullscreenRenderWidgetHostView();
if (fullscreen_view) {
fullscreen_view->Focus();
return;
}
GetRenderViewHost()->SetInitialFocus(reverse);
}
| 172,327 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int php_snmp_parse_oid(zval *object, int st, struct objid_query *objid_query, zval **oid, zval **type, zval **value TSRMLS_DC)
{
char *pptr;
HashPosition pos_oid, pos_type, pos_value;
zval **tmp_oid, **tmp_type, **tmp_value;
if (Z_TYPE_PP(oid) != IS_ARRAY) {
if (Z_ISREF_PP(oid)) {
SEPARATE_ZVAL(oid);
}
convert_to_string_ex(oid);
} else if (Z_TYPE_PP(oid) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
}
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) != IS_ARRAY) {
if (Z_ISREF_PP(type)) {
SEPARATE_ZVAL(type);
}
convert_to_string_ex(type);
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(type), &pos_type);
}
if (Z_TYPE_PP(value) != IS_ARRAY) {
if (Z_ISREF_PP(value)) {
SEPARATE_ZVAL(value);
}
convert_to_string_ex(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(value), &pos_value);
}
}
objid_query->count = 0;
objid_query->array_output = ((st & SNMP_CMD_WALK) ? TRUE : FALSE);
if (Z_TYPE_PP(oid) == IS_STRING) {
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING && Z_TYPE_PP(value) == IS_STRING) {
if (Z_STRLEN_PP(type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bogus type '%s', should be single char, got %u", Z_STRVAL_PP(type), Z_STRLEN_PP(type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Single objid and multiple type or values are not supported");
efree(objid_query->vars);
return FALSE;
}
}
objid_query->count++;
} else if (Z_TYPE_PP(oid) == IS_ARRAY) { /* we got objid array */
if (zend_hash_num_elements(Z_ARRVAL_PP(oid)) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Got empty OID array");
return FALSE;
}
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg) * zend_hash_num_elements(Z_ARRVAL_PP(oid)));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid array: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->array_output = ( (st & SNMP_CMD_SET) ? FALSE : TRUE );
for ( zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
zend_hash_get_current_data_ex(Z_ARRVAL_PP(oid), (void **) &tmp_oid, &pos_oid) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_PP(oid), &pos_oid) ) {
convert_to_string_ex(tmp_oid);
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(tmp_oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING) {
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(type), (void **) &tmp_type, &pos_type)) {
convert_to_string_ex(tmp_type);
if (Z_STRLEN_PP(tmp_type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': bogus type '%s', should be single char, got %u", Z_STRVAL_PP(tmp_oid), Z_STRVAL_PP(tmp_type), Z_STRLEN_PP(tmp_type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(tmp_type);
objid_query->vars[objid_query->count].type = *pptr;
zend_hash_move_forward_ex(Z_ARRVAL_PP(type), &pos_type);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no type set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
if (Z_TYPE_PP(value) == IS_STRING) {
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(value), (void **) &tmp_value, &pos_value)) {
convert_to_string_ex(tmp_value);
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(tmp_value);
zend_hash_move_forward_ex(Z_ARRVAL_PP(value), &pos_value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no value set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->count++;
}
}
/* now parse all OIDs */
if (st & SNMP_CMD_WALK) {
if (objid_query->count > 1) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Multi OID walks are not supported!");
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[0].name_length = MAX_NAME_LEN;
if (strlen(objid_query->vars[0].oid)) { /* on a walk, an empty string means top of tree - no error */
if (!snmp_parse_oid(objid_query->vars[0].oid, objid_query->vars[0].name, &(objid_query->vars[0].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[0].oid);
efree(objid_query->vars);
return FALSE;
}
} else {
memmove((char *)objid_query->vars[0].name, (char *)objid_mib, sizeof(objid_mib));
objid_query->vars[0].name_length = sizeof(objid_mib) / sizeof(oid);
}
} else {
for (objid_query->offset = 0; objid_query->offset < objid_query->count; objid_query->offset++) {
objid_query->vars[objid_query->offset].name_length = MAX_OID_LEN;
if (!snmp_parse_oid(objid_query->vars[objid_query->offset].oid, objid_query->vars[objid_query->offset].name, &(objid_query->vars[objid_query->offset].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[objid_query->offset].oid);
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->offset = 0;
objid_query->step = objid_query->count;
return (objid_query->count > 0);
}
Commit Message:
CWE ID: CWE-416 | static int php_snmp_parse_oid(zval *object, int st, struct objid_query *objid_query, zval **oid, zval **type, zval **value TSRMLS_DC)
{
char *pptr;
HashPosition pos_oid, pos_type, pos_value;
zval **tmp_oid, **tmp_type, **tmp_value;
if (Z_TYPE_PP(oid) != IS_ARRAY) {
if (Z_ISREF_PP(oid)) {
SEPARATE_ZVAL(oid);
}
convert_to_string_ex(oid);
} else if (Z_TYPE_PP(oid) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
}
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) != IS_ARRAY) {
if (Z_ISREF_PP(type)) {
SEPARATE_ZVAL(type);
}
convert_to_string_ex(type);
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(type), &pos_type);
}
if (Z_TYPE_PP(value) != IS_ARRAY) {
if (Z_ISREF_PP(value)) {
SEPARATE_ZVAL(value);
}
convert_to_string_ex(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(value), &pos_value);
}
}
objid_query->count = 0;
objid_query->array_output = ((st & SNMP_CMD_WALK) ? TRUE : FALSE);
if (Z_TYPE_PP(oid) == IS_STRING) {
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING && Z_TYPE_PP(value) == IS_STRING) {
if (Z_STRLEN_PP(type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bogus type '%s', should be single char, got %u", Z_STRVAL_PP(type), Z_STRLEN_PP(type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Single objid and multiple type or values are not supported");
efree(objid_query->vars);
return FALSE;
}
}
objid_query->count++;
} else if (Z_TYPE_PP(oid) == IS_ARRAY) { /* we got objid array */
if (zend_hash_num_elements(Z_ARRVAL_PP(oid)) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Got empty OID array");
return FALSE;
}
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg) * zend_hash_num_elements(Z_ARRVAL_PP(oid)));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid array: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->array_output = ( (st & SNMP_CMD_SET) ? FALSE : TRUE );
for ( zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
zend_hash_get_current_data_ex(Z_ARRVAL_PP(oid), (void **) &tmp_oid, &pos_oid) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_PP(oid), &pos_oid) ) {
convert_to_string_ex(tmp_oid);
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(tmp_oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING) {
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(type), (void **) &tmp_type, &pos_type)) {
convert_to_string_ex(tmp_type);
if (Z_STRLEN_PP(tmp_type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': bogus type '%s', should be single char, got %u", Z_STRVAL_PP(tmp_oid), Z_STRVAL_PP(tmp_type), Z_STRLEN_PP(tmp_type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(tmp_type);
objid_query->vars[objid_query->count].type = *pptr;
zend_hash_move_forward_ex(Z_ARRVAL_PP(type), &pos_type);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no type set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
if (Z_TYPE_PP(value) == IS_STRING) {
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(value), (void **) &tmp_value, &pos_value)) {
convert_to_string_ex(tmp_value);
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(tmp_value);
zend_hash_move_forward_ex(Z_ARRVAL_PP(value), &pos_value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no value set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->count++;
}
}
/* now parse all OIDs */
if (st & SNMP_CMD_WALK) {
if (objid_query->count > 1) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Multi OID walks are not supported!");
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[0].name_length = MAX_NAME_LEN;
if (strlen(objid_query->vars[0].oid)) { /* on a walk, an empty string means top of tree - no error */
if (!snmp_parse_oid(objid_query->vars[0].oid, objid_query->vars[0].name, &(objid_query->vars[0].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[0].oid);
efree(objid_query->vars);
return FALSE;
}
} else {
memmove((char *)objid_query->vars[0].name, (char *)objid_mib, sizeof(objid_mib));
objid_query->vars[0].name_length = sizeof(objid_mib) / sizeof(oid);
}
} else {
for (objid_query->offset = 0; objid_query->offset < objid_query->count; objid_query->offset++) {
objid_query->vars[objid_query->offset].name_length = MAX_OID_LEN;
if (!snmp_parse_oid(objid_query->vars[objid_query->offset].oid, objid_query->vars[objid_query->offset].name, &(objid_query->vars[objid_query->offset].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[objid_query->offset].oid);
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->offset = 0;
objid_query->step = objid_query->count;
return (objid_query->count > 0);
}
| 164,979 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> overloadedMethod4Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod4");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
imp->overloadedMethod(intArg);
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> overloadedMethod4Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod4");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
imp->overloadedMethod(intArg);
return v8::Handle<v8::Value>();
}
| 171,100 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: base::string16 GetApplicationNameForProtocol(const GURL& url) {
base::string16 application_name;
if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
application_name = GetAppForProtocolUsingAssocQuery(url);
if (!application_name.empty())
return application_name;
}
return GetAppForProtocolUsingRegistry(url);
}
Commit Message: Validate external protocols before launching on Windows
Bug: 889459
Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef
Reviewed-on: https://chromium-review.googlesource.com/c/1256208
Reviewed-by: Greg Thompson <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597611}
CWE ID: CWE-20 | base::string16 GetApplicationNameForProtocol(const GURL& url) {
if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
base::string16 application_name = GetAppForProtocolUsingAssocQuery(url);
if (!application_name.empty())
return application_name;
}
return GetAppForProtocolUsingRegistry(url);
}
| 172,637 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: report_error (const char *format, ...)
#else
report_error (format, va_alist)
const char *format;
va_dcl
#endif
{
va_list args;
error_prolog (1);
SH_VA_START (args, format);
vfprintf (stderr, format, args);
fprintf (stderr, "\n");
va_end (args);
if (exit_immediately_on_error)
exit_shell (1);
}
Commit Message:
CWE ID: CWE-119 | report_error (const char *format, ...)
#else
report_error (format, va_alist)
const char *format;
va_dcl
#endif
{
va_list args;
error_prolog (1);
SH_VA_START (args, format);
vfprintf (stderr, format, args);
fprintf (stderr, "\n");
va_end (args);
if (exit_immediately_on_error)
{
if (last_command_exit_value == 0)
last_command_exit_value = 1;
exit_shell (last_command_exit_value);
}
}
| 165,430 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: main(void)
{
fprintf(stderr, "pngfix does not work without read support\n");
return 77;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | main(void)
{
fprintf(stderr, "pngfix does not work without read deinterlace support\n");
return 77;
}
| 173,735 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: views::View* CardUnmaskPromptViews::CreateFootnoteView() {
if (!controller_->CanStoreLocally())
return nullptr;
storage_row_ = new FadeOutView();
views::BoxLayout* storage_row_layout = new views::BoxLayout(
views::BoxLayout::kHorizontal, kEdgePadding, kEdgePadding, 0);
storage_row_->SetLayoutManager(storage_row_layout);
storage_row_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
storage_row_->set_background(
views::Background::CreateSolidBackground(kShadingColor));
storage_checkbox_ = new views::Checkbox(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX));
storage_checkbox_->SetChecked(controller_->GetStoreLocallyStartState());
storage_row_->AddChildView(storage_checkbox_);
storage_row_layout->SetFlexForView(storage_checkbox_, 1);
storage_row_->AddChildView(new TooltipIcon(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_TOOLTIP)));
return storage_row_;
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20 | views::View* CardUnmaskPromptViews::CreateFootnoteView() {
if (!controller_->CanStoreLocally())
return nullptr;
storage_row_ = new FadeOutView();
views::BoxLayout* storage_row_layout = new views::BoxLayout(
views::BoxLayout::kHorizontal, kEdgePadding, kEdgePadding, 0);
storage_row_->SetLayoutManager(storage_row_layout);
storage_row_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
storage_row_->set_background(
views::Background::CreateSolidBackground(kLightShadingColor));
storage_checkbox_ = new views::Checkbox(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX));
storage_checkbox_->SetChecked(controller_->GetStoreLocallyStartState());
storage_row_->AddChildView(storage_checkbox_);
storage_row_layout->SetFlexForView(storage_checkbox_, 1);
storage_row_->AddChildView(new TooltipIcon(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_TOOLTIP)));
return storage_row_;
}
| 171,141 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void SendStatus(struct mg_connection* connection,
const struct mg_request_info* request_info,
void* user_data) {
std::string response = "HTTP/1.1 200 OK\r\n"
"Content-Length:2\r\n\r\n"
"ok";
mg_write(connection, response.data(), response.length());
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void SendStatus(struct mg_connection* connection,
void SendOkWithBody(struct mg_connection* connection,
const std::string& content) {
const char* response_fmt = "HTTP/1.1 200 OK\r\n"
"Content-Length:%d\r\n\r\n"
"%s";
std::string response = base::StringPrintf(
response_fmt, content.length(), content.c_str());
mg_write(connection, response.data(), response.length());
}
| 170,458 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int find_source_vc(char **ret_path, unsigned *ret_idx) {
_cleanup_free_ char *path = NULL;
int r, err = 0;
unsigned i;
path = new(char, sizeof("/dev/tty63"));
if (!path)
return log_oom();
for (i = 1; i <= 63; i++) {
_cleanup_close_ int fd = -1;
r = verify_vc_allocation(i);
if (r < 0) {
if (!err)
err = -r;
continue;
}
sprintf(path, "/dev/tty%u", i);
fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (fd < 0) {
if (!err)
err = -fd;
continue;
}
r = verify_vc_kbmode(fd);
if (r < 0) {
if (!err)
err = -r;
continue;
}
/* all checks passed, return this one as a source console */
*ret_idx = i;
*ret_path = TAKE_PTR(path);
return TAKE_FD(fd);
}
return log_error_errno(err, "No usable source console found: %m");
}
Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check
VT kbd reset check
CWE ID: CWE-255 | static int find_source_vc(char **ret_path, unsigned *ret_idx) {
_cleanup_free_ char *path = NULL;
int r, err = 0;
unsigned i;
path = new(char, sizeof("/dev/tty63"));
if (!path)
return log_oom();
for (i = 1; i <= 63; i++) {
_cleanup_close_ int fd = -1;
r = verify_vc_allocation(i);
if (r < 0) {
if (!err)
err = -r;
continue;
}
sprintf(path, "/dev/tty%u", i);
fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (fd < 0) {
if (!err)
err = -fd;
continue;
}
r = vt_verify_kbmode(fd);
if (r < 0) {
if (!err)
err = -r;
continue;
}
/* all checks passed, return this one as a source console */
*ret_idx = i;
*ret_path = TAKE_PTR(path);
return TAKE_FD(fd);
}
return log_error_errno(err, "No usable source console found: %m");
}
| 169,777 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: cib_recv_tls(gnutls_session * session)
{
char *buf = NULL;
int rc = 0;
int len = 0;
int chunk_size = 1024;
if (session == NULL) {
return NULL;
}
buf = calloc(1, chunk_size);
while (TRUE) {
errno = 0;
rc = gnutls_record_recv(*session, buf + len, chunk_size);
crm_trace("Got %d more bytes. errno=%d", rc, errno);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_trace("Retry");
} else if (rc == GNUTLS_E_UNEXPECTED_PACKET_LENGTH) {
crm_trace("Session disconnected");
goto bail;
} else if (rc < 0) {
crm_err("Error receiving message: %s (%d)", gnutls_strerror(rc), rc);
goto bail;
} else if (rc == chunk_size) {
len += rc;
chunk_size *= 2;
buf = realloc(buf, len + chunk_size);
crm_trace("Retry with %d more bytes", (int)chunk_size);
CRM_ASSERT(buf != NULL);
} else if (buf[len + rc - 1] != 0) {
crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]);
crm_trace("Retry with %d more bytes", (int)chunk_size);
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
} else {
crm_trace("Got %d more bytes", (int)rc);
return buf;
}
}
bail:
free(buf);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_recv_tls(gnutls_session * session)
crm_recv_tls(gnutls_session * session, size_t max_size, size_t *recv_len, int *disconnected)
{
char *buf = NULL;
int rc = 0;
size_t len = 0;
size_t chunk_size = max_size ? max_size : 1024;
size_t buf_size = 0;
size_t read_size = 0;
if (session == NULL) {
if (disconnected) {
*disconnected = 1;
}
goto done;
}
buf = calloc(1, chunk_size + 1);
buf_size = chunk_size;
while (TRUE) {
read_size = buf_size - len;
/* automatically grow the buffer when needed if max_size is not set.*/
if (!max_size && (read_size < (chunk_size / 2))) {
buf_size += chunk_size;
crm_trace("Grow buffer by %d more bytes. buf is now %d bytes", (int)chunk_size, buf_size);
buf = realloc(buf, buf_size + 1);
CRM_ASSERT(buf != NULL);
read_size = buf_size - len;
}
rc = gnutls_record_recv(*session, buf + len, read_size);
if (rc > 0) {
crm_trace("Got %d more bytes.", rc);
len += rc;
/* always null terminate buffer, the +1 to alloc always allows for this.*/
buf[len] = '\0';
}
if (max_size && (max_size == read_size)) {
crm_trace("Buffer max read size %d met" , max_size);
goto done;
}
/* process any errors. */
if (rc == GNUTLS_E_INTERRUPTED) {
crm_trace("EINTR encoutered, retry tls read");
} else if (rc == GNUTLS_E_AGAIN) {
crm_trace("non-blocking, exiting read on rc = %d", rc);
goto done;
} else if (rc <= 0) {
if (rc == 0) {
crm_debug("EOF encoutered during TLS read");
} else {
crm_debug("Error receiving message: %s (%d)", gnutls_strerror(rc), rc);
}
if (disconnected) {
*disconnected = 1;
}
goto done;
}
}
done:
if (recv_len) {
*recv_len = len;
}
if (!len) {
free(buf);
buf = NULL;
}
return buf;
}
| 166,159 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: error::Error GLES2DecoderPassthroughImpl::ProcessQueries(bool did_finish) {
while (!pending_queries_.empty()) {
const PendingQuery& query = pending_queries_.front();
GLuint result_available = GL_FALSE;
GLuint64 result = 0;
switch (query.target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
DCHECK(query.commands_completed_fence != nullptr);
result_available =
did_finish || query.commands_completed_fence->HasCompleted();
result = result_available;
break;
case GL_COMMANDS_ISSUED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
break;
case GL_LATENCY_QUERY_CHROMIUM:
result_available = GL_TRUE;
result = (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
break;
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
for (const PendingReadPixels& pending_read_pixels :
pending_read_pixels_) {
if (pending_read_pixels.waiting_async_pack_queries.count(
query.service_id) > 0) {
DCHECK(!did_finish);
result_available = GL_FALSE;
result = GL_FALSE;
break;
}
}
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
DCHECK(query.buffer_shadow_update_fence);
if (did_finish || query.buffer_shadow_update_fence->HasCompleted()) {
ReadBackBuffersIntoShadowCopies(query.buffer_shadow_updates);
result_available = GL_TRUE;
result = 0;
}
break;
case GL_GET_ERROR_QUERY_CHROMIUM:
result_available = GL_TRUE;
FlushErrors();
result = PopError();
break;
default:
DCHECK(!IsEmulatedQueryTarget(query.target));
if (did_finish) {
result_available = GL_TRUE;
} else {
api()->glGetQueryObjectuivFn(
query.service_id, GL_QUERY_RESULT_AVAILABLE, &result_available);
}
if (result_available == GL_TRUE) {
if (feature_info_->feature_flags().ext_disjoint_timer_query) {
api()->glGetQueryObjectui64vFn(query.service_id, GL_QUERY_RESULT,
&result);
} else {
GLuint temp_result = 0;
api()->glGetQueryObjectuivFn(query.service_id, GL_QUERY_RESULT,
&temp_result);
result = temp_result;
}
}
break;
}
if (!result_available) {
break;
}
query.sync->result = result;
base::subtle::Release_Store(&query.sync->process_count, query.submit_count);
pending_queries_.pop_front();
}
DCHECK(!did_finish || pending_queries_.empty());
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | error::Error GLES2DecoderPassthroughImpl::ProcessQueries(bool did_finish) {
bool program_completion_query_deferred = false;
while (!pending_queries_.empty()) {
PendingQuery& query = pending_queries_.front();
GLuint result_available = GL_FALSE;
GLuint64 result = 0;
switch (query.target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
DCHECK(query.commands_completed_fence != nullptr);
result_available =
did_finish || query.commands_completed_fence->HasCompleted();
result = result_available;
break;
case GL_COMMANDS_ISSUED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
break;
case GL_LATENCY_QUERY_CHROMIUM:
result_available = GL_TRUE;
result = (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
break;
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
for (const PendingReadPixels& pending_read_pixels :
pending_read_pixels_) {
if (pending_read_pixels.waiting_async_pack_queries.count(
query.service_id) > 0) {
DCHECK(!did_finish);
result_available = GL_FALSE;
result = GL_FALSE;
break;
}
}
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
DCHECK(query.buffer_shadow_update_fence);
if (did_finish || query.buffer_shadow_update_fence->HasCompleted()) {
ReadBackBuffersIntoShadowCopies(query.buffer_shadow_updates);
result_available = GL_TRUE;
result = 0;
}
break;
case GL_GET_ERROR_QUERY_CHROMIUM:
result_available = GL_TRUE;
FlushErrors();
result = PopError();
break;
case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM:
GLint status;
if (!api()->glIsProgramFn(query.program_service_id)) {
status = GL_TRUE;
} else {
api()->glGetProgramivFn(query.program_service_id,
GL_COMPLETION_STATUS_KHR, &status);
}
result_available = (status == GL_TRUE);
if (!result_available) {
// Move the query to the end of queue, so that other queries may have
// chance to be processed.
auto temp = std::move(query);
pending_queries_.pop_front();
pending_queries_.emplace_back(std::move(temp));
if (did_finish && !OnlyHasPendingProgramCompletionQueries()) {
continue;
} else {
program_completion_query_deferred = true;
}
}
result = 0;
break;
default:
DCHECK(!IsEmulatedQueryTarget(query.target));
if (did_finish) {
result_available = GL_TRUE;
} else {
api()->glGetQueryObjectuivFn(
query.service_id, GL_QUERY_RESULT_AVAILABLE, &result_available);
}
if (result_available == GL_TRUE) {
if (feature_info_->feature_flags().ext_disjoint_timer_query) {
api()->glGetQueryObjectui64vFn(query.service_id, GL_QUERY_RESULT,
&result);
} else {
GLuint temp_result = 0;
api()->glGetQueryObjectuivFn(query.service_id, GL_QUERY_RESULT,
&temp_result);
result = temp_result;
}
}
break;
}
if (!result_available) {
break;
}
query.sync->result = result;
base::subtle::Release_Store(&query.sync->process_count, query.submit_count);
pending_queries_.pop_front();
}
DCHECK(!did_finish || pending_queries_.empty() ||
program_completion_query_deferred);
return error::kNoError;
}
| 172,531 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: long Chapters::Atom::Parse(
IMkvReader* pReader,
long long pos,
long long size)
{
const long long stop = pos + size;
while (pos < stop)
{
long long id, size;
long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x00) // Display ID
{
status = ParseDisplay(pReader, pos, size);
if (status < 0) // error
return status;
}
else if (id == 0x1654) // StringUID ID
{
status = UnserializeString(pReader, pos, size, m_string_uid);
if (status < 0) // error
return status;
}
else if (id == 0x33C4) // UID ID
{
long long val;
status = UnserializeInt(pReader, pos, size, val);
if (status < 0) // error
return status;
m_uid = val;
}
else if (id == 0x11) // TimeStart ID
{
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_start_timecode = val;
}
else if (id == 0x12) // TimeEnd ID
{
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_stop_timecode = val;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Chapters::Atom::Parse(
| 174,402 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void AppControllerImpl::OnAppUpdate(const apps::AppUpdate& update) {
if (!update.StateIsNull() && !update.NameChanged() &&
!update.ReadinessChanged()) {
return;
}
if (client_) {
client_->OnAppChanged(CreateAppPtr(update));
}
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | void AppControllerImpl::OnAppUpdate(const apps::AppUpdate& update) {
void AppControllerService::OnAppUpdate(const apps::AppUpdate& update) {
if (!update.StateIsNull() && !update.NameChanged() &&
!update.ReadinessChanged()) {
return;
}
if (client_) {
client_->OnAppChanged(CreateAppPtr(update));
}
}
| 172,087 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static void TearDownTestCase() {
vpx_free(source_data_);
source_data_ = NULL;
vpx_free(reference_data_);
reference_data_ = NULL;
}
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 | static void TearDownTestCase() {
vpx_free(source_data8_);
source_data8_ = NULL;
vpx_free(reference_data8_);
reference_data8_ = NULL;
vpx_free(second_pred8_);
second_pred8_ = NULL;
vpx_free(source_data16_);
source_data16_ = NULL;
vpx_free(reference_data16_);
reference_data16_ = NULL;
vpx_free(second_pred16_);
second_pred16_ = NULL;
}
| 174,579 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: const SeekHead::Entry* SeekHead::GetEntry(int idx) const
{
if (idx < 0)
return 0;
if (idx >= m_entry_count)
return 0;
return m_entries + idx;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const SeekHead::Entry* SeekHead::GetEntry(int idx) const
| 174,317 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int msg_flags)
{
struct sock *sk = sock->sk;
struct rds_sock *rs = rds_sk_to_rs(sk);
long timeo;
int ret = 0, nonblock = msg_flags & MSG_DONTWAIT;
struct sockaddr_in *sin;
struct rds_incoming *inc = NULL;
/* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */
timeo = sock_rcvtimeo(sk, nonblock);
rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo);
msg->msg_namelen = 0;
if (msg_flags & MSG_OOB)
goto out;
while (1) {
/* If there are pending notifications, do those - and nothing else */
if (!list_empty(&rs->rs_notify_queue)) {
ret = rds_notify_queue_get(rs, msg);
break;
}
if (rs->rs_cong_notify) {
ret = rds_notify_cong(rs, msg);
break;
}
if (!rds_next_incoming(rs, &inc)) {
if (nonblock) {
ret = -EAGAIN;
break;
}
timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
(!list_empty(&rs->rs_notify_queue) ||
rs->rs_cong_notify ||
rds_next_incoming(rs, &inc)), timeo);
rdsdebug("recvmsg woke inc %p timeo %ld\n", inc,
timeo);
if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
continue;
ret = timeo;
if (ret == 0)
ret = -ETIMEDOUT;
break;
}
rdsdebug("copying inc %p from %pI4:%u to user\n", inc,
&inc->i_conn->c_faddr,
ntohs(inc->i_hdr.h_sport));
ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov,
size);
if (ret < 0)
break;
/*
* if the message we just copied isn't at the head of the
* recv queue then someone else raced us to return it, try
* to get the next message.
*/
if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) {
rds_inc_put(inc);
inc = NULL;
rds_stats_inc(s_recv_deliver_raced);
continue;
}
if (ret < be32_to_cpu(inc->i_hdr.h_len)) {
if (msg_flags & MSG_TRUNC)
ret = be32_to_cpu(inc->i_hdr.h_len);
msg->msg_flags |= MSG_TRUNC;
}
if (rds_cmsg_recv(inc, msg)) {
ret = -EFAULT;
goto out;
}
rds_stats_inc(s_recv_delivered);
sin = (struct sockaddr_in *)msg->msg_name;
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = inc->i_hdr.h_sport;
sin->sin_addr.s_addr = inc->i_saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
msg->msg_namelen = sizeof(*sin);
}
break;
}
if (inc)
rds_inc_put(inc);
out:
return ret;
}
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 | int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int msg_flags)
{
struct sock *sk = sock->sk;
struct rds_sock *rs = rds_sk_to_rs(sk);
long timeo;
int ret = 0, nonblock = msg_flags & MSG_DONTWAIT;
struct sockaddr_in *sin;
struct rds_incoming *inc = NULL;
/* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */
timeo = sock_rcvtimeo(sk, nonblock);
rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo);
if (msg_flags & MSG_OOB)
goto out;
while (1) {
/* If there are pending notifications, do those - and nothing else */
if (!list_empty(&rs->rs_notify_queue)) {
ret = rds_notify_queue_get(rs, msg);
break;
}
if (rs->rs_cong_notify) {
ret = rds_notify_cong(rs, msg);
break;
}
if (!rds_next_incoming(rs, &inc)) {
if (nonblock) {
ret = -EAGAIN;
break;
}
timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
(!list_empty(&rs->rs_notify_queue) ||
rs->rs_cong_notify ||
rds_next_incoming(rs, &inc)), timeo);
rdsdebug("recvmsg woke inc %p timeo %ld\n", inc,
timeo);
if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
continue;
ret = timeo;
if (ret == 0)
ret = -ETIMEDOUT;
break;
}
rdsdebug("copying inc %p from %pI4:%u to user\n", inc,
&inc->i_conn->c_faddr,
ntohs(inc->i_hdr.h_sport));
ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov,
size);
if (ret < 0)
break;
/*
* if the message we just copied isn't at the head of the
* recv queue then someone else raced us to return it, try
* to get the next message.
*/
if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) {
rds_inc_put(inc);
inc = NULL;
rds_stats_inc(s_recv_deliver_raced);
continue;
}
if (ret < be32_to_cpu(inc->i_hdr.h_len)) {
if (msg_flags & MSG_TRUNC)
ret = be32_to_cpu(inc->i_hdr.h_len);
msg->msg_flags |= MSG_TRUNC;
}
if (rds_cmsg_recv(inc, msg)) {
ret = -EFAULT;
goto out;
}
rds_stats_inc(s_recv_delivered);
sin = (struct sockaddr_in *)msg->msg_name;
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = inc->i_hdr.h_sport;
sin->sin_addr.s_addr = inc->i_saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
msg->msg_namelen = sizeof(*sin);
}
break;
}
if (inc)
rds_inc_put(inc);
out:
return ret;
}
| 166,512 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl3_get_key_exchange(SSL *s)
{
#ifndef OPENSSL_NO_RSA
unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
#endif
EVP_MD_CTX md_ctx;
unsigned char *param,*p;
int al,j,ok;
long i,param_len,n,alg_k,alg_a;
EVP_PKEY *pkey=NULL;
const EVP_MD *md = NULL;
#ifndef OPENSSL_NO_RSA
RSA *rsa=NULL;
#endif
#ifndef OPENSSL_NO_DH
DH *dh=NULL;
#endif
#ifndef OPENSSL_NO_ECDH
EC_KEY *ecdh = NULL;
BN_CTX *bn_ctx = NULL;
EC_POINT *srvr_ecpoint = NULL;
int curve_nid = 0;
int encoded_pt_len = 0;
#endif
EVP_MD_CTX_init(&md_ctx);
/* use same message size as in ssl3_get_certificate_request()
* as ServerKeyExchange message may be skipped */
n=s->method->ssl_get_message(s,
SSL3_ST_CR_KEY_EXCH_A,
SSL3_ST_CR_KEY_EXCH_B,
-1,
s->max_cert_list,
&ok);
if (!ok) return((int)n);
alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
{
/*
* Can't skip server key exchange if this is an ephemeral
* ciphersuite.
*/
if (alg_k & (SSL_kDHE|SSL_kECDHE))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
al = SSL_AD_UNEXPECTED_MESSAGE;
goto f_err;
}
#ifndef OPENSSL_NO_PSK
/* In plain PSK ciphersuite, ServerKeyExchange can be
omitted if no identity hint is sent. Set
session->sess_cert anyway to avoid problems
later.*/
if (alg_k & SSL_kPSK)
{
s->session->sess_cert=ssl_sess_cert_new();
if (s->ctx->psk_identity_hint)
OPENSSL_free(s->ctx->psk_identity_hint);
s->ctx->psk_identity_hint = NULL;
}
#endif
s->s3->tmp.reuse_message=1;
return(1);
}
param=p=(unsigned char *)s->init_msg;
if (s->session->sess_cert != NULL)
{
#ifndef OPENSSL_NO_RSA
if (s->session->sess_cert->peer_rsa_tmp != NULL)
{
RSA_free(s->session->sess_cert->peer_rsa_tmp);
s->session->sess_cert->peer_rsa_tmp=NULL;
}
#endif
#ifndef OPENSSL_NO_DH
if (s->session->sess_cert->peer_dh_tmp)
{
DH_free(s->session->sess_cert->peer_dh_tmp);
s->session->sess_cert->peer_dh_tmp=NULL;
}
#endif
#ifndef OPENSSL_NO_ECDH
if (s->session->sess_cert->peer_ecdh_tmp)
{
EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
s->session->sess_cert->peer_ecdh_tmp=NULL;
}
#endif
}
else
{
s->session->sess_cert=ssl_sess_cert_new();
}
/* Total length of the parameters including the length prefix */
param_len=0;
alg_a=s->s3->tmp.new_cipher->algorithm_auth;
al=SSL_AD_DECODE_ERROR;
#ifndef OPENSSL_NO_PSK
if (alg_k & SSL_kPSK)
{
char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];
param_len = 2;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
/* Store PSK identity hint for later use, hint is used
* in ssl3_send_client_key_exchange. Assume that the
* maximum length of a PSK identity hint can be as
* long as the maximum length of a PSK identity. */
if (i > PSK_MAX_IDENTITY_LEN)
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto f_err;
}
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
goto f_err;
}
param_len += i;
/* If received PSK identity hint contains NULL
* characters, the hint is truncated from the first
* NULL. p may not be ending with NULL, so create a
* NULL-terminated string. */
memcpy(tmp_id_hint, p, i);
memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
if (s->ctx->psk_identity_hint != NULL)
OPENSSL_free(s->ctx->psk_identity_hint);
s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
if (s->ctx->psk_identity_hint == NULL)
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto f_err;
}
p+=i;
n-=param_len;
}
else
#endif /* !OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
if (alg_k & SSL_kSRP)
{
param_len = 2;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (1 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 1;
i = (unsigned int)(p[0]);
p++;
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
n-=param_len;
if (!srp_verify_server_param(s, &al))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
goto f_err;
}
/* We must check if there is a certificate */
#ifndef OPENSSL_NO_RSA
if (alg_a & SSL_aRSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
#else
if (0)
;
#endif
#ifndef OPENSSL_NO_DSA
else if (alg_a & SSL_aDSS)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
#endif
}
else
#endif /* !OPENSSL_NO_SRP */
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA)
{
if ((rsa=RSA_new()) == NULL)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
goto err;
}
param_len = 2;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
goto f_err;
}
param_len += i;
if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
goto f_err;
}
param_len += i;
if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
n-=param_len;
/* this should be because we are using an export cipher */
if (alg_a & SSL_aRSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
else
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
goto err;
}
s->session->sess_cert->peer_rsa_tmp=rsa;
rsa=NULL;
}
#else /* OPENSSL_NO_RSA */
if (0)
;
#endif
#ifndef OPENSSL_NO_DH
else if (alg_k & SSL_kDHE)
{
if ((dh=DH_new()) == NULL)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
goto err;
}
param_len = 2;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->p=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->g=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
n-=param_len;
if (!ssl_security(s, SSL_SECOP_TMP_DH,
DH_security_bits(dh), 0, dh))
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);
goto f_err;
}
#ifndef OPENSSL_NO_RSA
if (alg_a & SSL_aRSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
#else
if (0)
;
#endif
#ifndef OPENSSL_NO_DSA
else if (alg_a & SSL_aDSS)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
#endif
/* else anonymous DH, so no certificate or pkey. */
s->session->sess_cert->peer_dh_tmp=dh;
dh=NULL;
}
else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
goto f_err;
}
#endif /* !OPENSSL_NO_DH */
#ifndef OPENSSL_NO_ECDH
else if (alg_k & SSL_kECDHE)
{
EC_GROUP *ngroup;
const EC_GROUP *group;
if ((ecdh=EC_KEY_new()) == NULL)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
goto err;
}
/* Extract elliptic curve parameters and the
* server's ephemeral ECDH public key.
* Keep accumulating lengths of various components in
* param_len and make sure it never exceeds n.
*/
/* XXX: For now we only support named (not generic) curves
* and the ECParameters in this case is just three bytes. We
* also need one byte for the length of the encoded point
*/
param_len=4;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
/* Check curve is one of our preferences, if not server has
* sent an invalid curve. ECParameters is 3 bytes.
*/
if (!tls1_check_curve(s, p, 3))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE);
goto f_err;
}
if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0)
{
al=SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
goto f_err;
}
ngroup = EC_GROUP_new_by_curve_name(curve_nid);
if (ngroup == NULL)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
goto err;
}
if (EC_KEY_set_group(ecdh, ngroup) == 0)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
goto err;
}
EC_GROUP_free(ngroup);
group = EC_KEY_get0_group(ecdh);
if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
(EC_GROUP_get_degree(group) > 163))
{
al=SSL_AD_EXPORT_RESTRICTION;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
goto f_err;
}
p+=3;
/* Next, get the encoded ECPoint */
if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
((bn_ctx = BN_CTX_new()) == NULL))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
goto err;
}
encoded_pt_len = *p; /* length of encoded point */
p+=1;
if ((encoded_pt_len > n - param_len) ||
(EC_POINT_oct2point(group, srvr_ecpoint,
p, encoded_pt_len, bn_ctx) == 0))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
goto f_err;
}
param_len += encoded_pt_len;
n-=param_len;
p+=encoded_pt_len;
/* The ECC/TLS specification does not mention
* the use of DSA to sign ECParameters in the server
* key exchange message. We do support RSA and ECDSA.
*/
if (0) ;
#ifndef OPENSSL_NO_RSA
else if (alg_a & SSL_aRSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
#endif
#ifndef OPENSSL_NO_ECDSA
else if (alg_a & SSL_aECDSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
#endif
/* else anonymous ECDH, so no certificate or pkey. */
EC_KEY_set_public_key(ecdh, srvr_ecpoint);
s->session->sess_cert->peer_ecdh_tmp=ecdh;
ecdh=NULL;
BN_CTX_free(bn_ctx);
bn_ctx = NULL;
EC_POINT_free(srvr_ecpoint);
srvr_ecpoint = NULL;
}
else if (alg_k)
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
#endif /* !OPENSSL_NO_ECDH */
/* p points to the next byte, there are 'n' bytes left */
/* if it was signed, check the signature */
if (pkey != NULL)
{
if (SSL_USE_SIGALGS(s))
{
int rv;
if (2 > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
rv = tls12_check_peer_sigalg(&md, s, p, pkey);
if (rv == -1)
goto err;
else if (rv == 0)
{
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
#endif
p += 2;
n -= 2;
}
else
md = EVP_sha1();
if (2 > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
n-=2;
j=EVP_PKEY_size(pkey);
/* Check signature length. If n is 0 then signature is empty */
if ((i != n) || (n > j) || (n <= 0))
{
/* wrong packet length */
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
goto f_err;
}
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
{
int num;
unsigned int size;
j=0;
q=md_buf;
for (num=2; num > 0; num--)
{
EVP_MD_CTX_set_flags(&md_ctx,
EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
EVP_DigestInit_ex(&md_ctx,(num == 2)
?s->ctx->md5:s->ctx->sha1, NULL);
EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
EVP_DigestUpdate(&md_ctx,param,param_len);
EVP_DigestFinal_ex(&md_ctx,q,&size);
q+=size;
j+=size;
}
i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
pkey->pkey.rsa);
if (i < 0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
goto f_err;
}
if (i == 0)
{
/* bad signature */
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
goto f_err;
}
}
else
#endif
{
EVP_VerifyInit_ex(&md_ctx, md, NULL);
EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
EVP_VerifyUpdate(&md_ctx,param,param_len);
if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)
{
/* bad signature */
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
goto f_err;
}
}
}
else
{
/* aNULL, aSRP or kPSK do not need public keys */
if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK))
{
/* Might be wrong key type, check it */
if (ssl3_check_cert_and_algorithm(s))
/* Otherwise this shouldn't happen */
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
goto err;
}
/* still data left over */
if (n != 0)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
goto f_err;
}
}
EVP_PKEY_free(pkey);
EVP_MD_CTX_cleanup(&md_ctx);
return(1);
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
err:
EVP_PKEY_free(pkey);
#ifndef OPENSSL_NO_RSA
if (rsa != NULL)
RSA_free(rsa);
#endif
#ifndef OPENSSL_NO_DH
if (dh != NULL)
DH_free(dh);
#endif
#ifndef OPENSSL_NO_ECDH
BN_CTX_free(bn_ctx);
EC_POINT_free(srvr_ecpoint);
if (ecdh != NULL)
EC_KEY_free(ecdh);
#endif
EVP_MD_CTX_cleanup(&md_ctx);
return(-1);
}
Commit Message: Only allow ephemeral RSA keys in export ciphersuites.
OpenSSL clients would tolerate temporary RSA keys in non-export
ciphersuites. It also had an option SSL_OP_EPHEMERAL_RSA which
enabled this server side. Remove both options as they are a
protocol violation.
Thanks to Karthikeyan Bhargavan for reporting this issue.
(CVE-2015-0204)
Reviewed-by: Matt Caswell <[email protected]>
CWE ID: CWE-310 | int ssl3_get_key_exchange(SSL *s)
{
#ifndef OPENSSL_NO_RSA
unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
#endif
EVP_MD_CTX md_ctx;
unsigned char *param,*p;
int al,j,ok;
long i,param_len,n,alg_k,alg_a;
EVP_PKEY *pkey=NULL;
const EVP_MD *md = NULL;
#ifndef OPENSSL_NO_RSA
RSA *rsa=NULL;
#endif
#ifndef OPENSSL_NO_DH
DH *dh=NULL;
#endif
#ifndef OPENSSL_NO_ECDH
EC_KEY *ecdh = NULL;
BN_CTX *bn_ctx = NULL;
EC_POINT *srvr_ecpoint = NULL;
int curve_nid = 0;
int encoded_pt_len = 0;
#endif
EVP_MD_CTX_init(&md_ctx);
/* use same message size as in ssl3_get_certificate_request()
* as ServerKeyExchange message may be skipped */
n=s->method->ssl_get_message(s,
SSL3_ST_CR_KEY_EXCH_A,
SSL3_ST_CR_KEY_EXCH_B,
-1,
s->max_cert_list,
&ok);
if (!ok) return((int)n);
alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
{
/*
* Can't skip server key exchange if this is an ephemeral
* ciphersuite.
*/
if (alg_k & (SSL_kDHE|SSL_kECDHE))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
al = SSL_AD_UNEXPECTED_MESSAGE;
goto f_err;
}
#ifndef OPENSSL_NO_PSK
/* In plain PSK ciphersuite, ServerKeyExchange can be
omitted if no identity hint is sent. Set
session->sess_cert anyway to avoid problems
later.*/
if (alg_k & SSL_kPSK)
{
s->session->sess_cert=ssl_sess_cert_new();
if (s->ctx->psk_identity_hint)
OPENSSL_free(s->ctx->psk_identity_hint);
s->ctx->psk_identity_hint = NULL;
}
#endif
s->s3->tmp.reuse_message=1;
return(1);
}
param=p=(unsigned char *)s->init_msg;
if (s->session->sess_cert != NULL)
{
#ifndef OPENSSL_NO_RSA
if (s->session->sess_cert->peer_rsa_tmp != NULL)
{
RSA_free(s->session->sess_cert->peer_rsa_tmp);
s->session->sess_cert->peer_rsa_tmp=NULL;
}
#endif
#ifndef OPENSSL_NO_DH
if (s->session->sess_cert->peer_dh_tmp)
{
DH_free(s->session->sess_cert->peer_dh_tmp);
s->session->sess_cert->peer_dh_tmp=NULL;
}
#endif
#ifndef OPENSSL_NO_ECDH
if (s->session->sess_cert->peer_ecdh_tmp)
{
EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
s->session->sess_cert->peer_ecdh_tmp=NULL;
}
#endif
}
else
{
s->session->sess_cert=ssl_sess_cert_new();
}
/* Total length of the parameters including the length prefix */
param_len=0;
alg_a=s->s3->tmp.new_cipher->algorithm_auth;
al=SSL_AD_DECODE_ERROR;
#ifndef OPENSSL_NO_PSK
if (alg_k & SSL_kPSK)
{
char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];
param_len = 2;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
/* Store PSK identity hint for later use, hint is used
* in ssl3_send_client_key_exchange. Assume that the
* maximum length of a PSK identity hint can be as
* long as the maximum length of a PSK identity. */
if (i > PSK_MAX_IDENTITY_LEN)
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto f_err;
}
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
goto f_err;
}
param_len += i;
/* If received PSK identity hint contains NULL
* characters, the hint is truncated from the first
* NULL. p may not be ending with NULL, so create a
* NULL-terminated string. */
memcpy(tmp_id_hint, p, i);
memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
if (s->ctx->psk_identity_hint != NULL)
OPENSSL_free(s->ctx->psk_identity_hint);
s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
if (s->ctx->psk_identity_hint == NULL)
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto f_err;
}
p+=i;
n-=param_len;
}
else
#endif /* !OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
if (alg_k & SSL_kSRP)
{
param_len = 2;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (1 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 1;
i = (unsigned int)(p[0]);
p++;
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
n-=param_len;
if (!srp_verify_server_param(s, &al))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
goto f_err;
}
/* We must check if there is a certificate */
#ifndef OPENSSL_NO_RSA
if (alg_a & SSL_aRSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
#else
if (0)
;
#endif
#ifndef OPENSSL_NO_DSA
else if (alg_a & SSL_aDSS)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
#endif
}
else
#endif /* !OPENSSL_NO_SRP */
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA)
{
/* Temporary RSA keys only allowed in export ciphersuites */
if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher))
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
if ((rsa=RSA_new()) == NULL)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
goto err;
}
param_len = 2;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
goto f_err;
}
param_len += i;
if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
goto f_err;
}
param_len += i;
if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
n-=param_len;
/* this should be because we are using an export cipher */
if (alg_a & SSL_aRSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
else
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
goto err;
}
s->session->sess_cert->peer_rsa_tmp=rsa;
rsa=NULL;
}
#else /* OPENSSL_NO_RSA */
if (0)
;
#endif
#ifndef OPENSSL_NO_DH
else if (alg_k & SSL_kDHE)
{
if ((dh=DH_new()) == NULL)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
goto err;
}
param_len = 2;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->p=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->g=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
if (2 > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p,i);
if (i > n - param_len)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
goto err;
}
p+=i;
n-=param_len;
if (!ssl_security(s, SSL_SECOP_TMP_DH,
DH_security_bits(dh), 0, dh))
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);
goto f_err;
}
#ifndef OPENSSL_NO_RSA
if (alg_a & SSL_aRSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
#else
if (0)
;
#endif
#ifndef OPENSSL_NO_DSA
else if (alg_a & SSL_aDSS)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
#endif
/* else anonymous DH, so no certificate or pkey. */
s->session->sess_cert->peer_dh_tmp=dh;
dh=NULL;
}
else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
goto f_err;
}
#endif /* !OPENSSL_NO_DH */
#ifndef OPENSSL_NO_ECDH
else if (alg_k & SSL_kECDHE)
{
EC_GROUP *ngroup;
const EC_GROUP *group;
if ((ecdh=EC_KEY_new()) == NULL)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
goto err;
}
/* Extract elliptic curve parameters and the
* server's ephemeral ECDH public key.
* Keep accumulating lengths of various components in
* param_len and make sure it never exceeds n.
*/
/* XXX: For now we only support named (not generic) curves
* and the ECParameters in this case is just three bytes. We
* also need one byte for the length of the encoded point
*/
param_len=4;
if (param_len > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
/* Check curve is one of our preferences, if not server has
* sent an invalid curve. ECParameters is 3 bytes.
*/
if (!tls1_check_curve(s, p, 3))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE);
goto f_err;
}
if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0)
{
al=SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
goto f_err;
}
ngroup = EC_GROUP_new_by_curve_name(curve_nid);
if (ngroup == NULL)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
goto err;
}
if (EC_KEY_set_group(ecdh, ngroup) == 0)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
goto err;
}
EC_GROUP_free(ngroup);
group = EC_KEY_get0_group(ecdh);
if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
(EC_GROUP_get_degree(group) > 163))
{
al=SSL_AD_EXPORT_RESTRICTION;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
goto f_err;
}
p+=3;
/* Next, get the encoded ECPoint */
if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
((bn_ctx = BN_CTX_new()) == NULL))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
goto err;
}
encoded_pt_len = *p; /* length of encoded point */
p+=1;
if ((encoded_pt_len > n - param_len) ||
(EC_POINT_oct2point(group, srvr_ecpoint,
p, encoded_pt_len, bn_ctx) == 0))
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
goto f_err;
}
param_len += encoded_pt_len;
n-=param_len;
p+=encoded_pt_len;
/* The ECC/TLS specification does not mention
* the use of DSA to sign ECParameters in the server
* key exchange message. We do support RSA and ECDSA.
*/
if (0) ;
#ifndef OPENSSL_NO_RSA
else if (alg_a & SSL_aRSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
#endif
#ifndef OPENSSL_NO_ECDSA
else if (alg_a & SSL_aECDSA)
pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
#endif
/* else anonymous ECDH, so no certificate or pkey. */
EC_KEY_set_public_key(ecdh, srvr_ecpoint);
s->session->sess_cert->peer_ecdh_tmp=ecdh;
ecdh=NULL;
BN_CTX_free(bn_ctx);
bn_ctx = NULL;
EC_POINT_free(srvr_ecpoint);
srvr_ecpoint = NULL;
}
else if (alg_k)
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
#endif /* !OPENSSL_NO_ECDH */
/* p points to the next byte, there are 'n' bytes left */
/* if it was signed, check the signature */
if (pkey != NULL)
{
if (SSL_USE_SIGALGS(s))
{
int rv;
if (2 > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
rv = tls12_check_peer_sigalg(&md, s, p, pkey);
if (rv == -1)
goto err;
else if (rv == 0)
{
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
#endif
p += 2;
n -= 2;
}
else
md = EVP_sha1();
if (2 > n)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p,i);
n-=2;
j=EVP_PKEY_size(pkey);
/* Check signature length. If n is 0 then signature is empty */
if ((i != n) || (n > j) || (n <= 0))
{
/* wrong packet length */
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
goto f_err;
}
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
{
int num;
unsigned int size;
j=0;
q=md_buf;
for (num=2; num > 0; num--)
{
EVP_MD_CTX_set_flags(&md_ctx,
EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
EVP_DigestInit_ex(&md_ctx,(num == 2)
?s->ctx->md5:s->ctx->sha1, NULL);
EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
EVP_DigestUpdate(&md_ctx,param,param_len);
EVP_DigestFinal_ex(&md_ctx,q,&size);
q+=size;
j+=size;
}
i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
pkey->pkey.rsa);
if (i < 0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
goto f_err;
}
if (i == 0)
{
/* bad signature */
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
goto f_err;
}
}
else
#endif
{
EVP_VerifyInit_ex(&md_ctx, md, NULL);
EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
EVP_VerifyUpdate(&md_ctx,param,param_len);
if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)
{
/* bad signature */
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
goto f_err;
}
}
}
else
{
/* aNULL, aSRP or kPSK do not need public keys */
if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK))
{
/* Might be wrong key type, check it */
if (ssl3_check_cert_and_algorithm(s))
/* Otherwise this shouldn't happen */
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
goto err;
}
/* still data left over */
if (n != 0)
{
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
goto f_err;
}
}
EVP_PKEY_free(pkey);
EVP_MD_CTX_cleanup(&md_ctx);
return(1);
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
err:
EVP_PKEY_free(pkey);
#ifndef OPENSSL_NO_RSA
if (rsa != NULL)
RSA_free(rsa);
#endif
#ifndef OPENSSL_NO_DH
if (dh != NULL)
DH_free(dh);
#endif
#ifndef OPENSSL_NO_ECDH
BN_CTX_free(bn_ctx);
EC_POINT_free(srvr_ecpoint);
if (ecdh != NULL)
EC_KEY_free(ecdh);
#endif
EVP_MD_CTX_cleanup(&md_ctx);
return(-1);
}
| 166,752 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: PHPAPI char *php_escape_html_entities_ex(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset, zend_bool double_encode TSRMLS_DC)
{
size_t cursor, maxlen, len;
char *replaced;
enum entity_charset charset = determine_charset(hint_charset TSRMLS_CC);
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
entity_table_opt entity_table;
const enc_to_uni *to_uni_table = NULL;
const entity_ht *inv_map = NULL; /* used for !double_encode */
/* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */
const unsigned char *replacement = NULL;
size_t replacement_len = 0;
if (all) { /* replace with all named entities */
if (CHARSET_PARTIAL_SUPPORT(charset)) {
php_error_docref0(NULL TSRMLS_CC, E_STRICT, "Only basic entities "
"substitution is supported for multi-byte encodings other than UTF-8; "
"functionality is equivalent to htmlspecialchars");
}
LIMIT_ALL(all, doctype, charset);
}
entity_table = determine_entity_table(all, doctype);
if (all && !CHARSET_UNICODE_COMPAT(charset)) {
to_uni_table = enc_to_uni_index[charset];
}
if (!double_encode) {
/* first arg is 1 because we want to identify valid named entities
* even if we are only encoding the basic ones */
inv_map = unescape_inverse_map(1, flags);
}
if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) {
if (charset == cs_utf_8) {
replacement = (const unsigned char*)"\xEF\xBF\xBD";
replacement_len = sizeof("\xEF\xBF\xBD") - 1;
} else {
replacement = (const unsigned char*)"�";
replacement_len = sizeof("�") - 1;
}
}
/* initial estimate */
if (oldlen < 64) {
maxlen = 128;
} else {
maxlen = 2 * oldlen;
if (maxlen < oldlen) {
zend_error_noreturn(E_ERROR, "Input string is too long");
return NULL;
}
}
replaced = emalloc(maxlen + 1); /* adding 1 is safe: maxlen is even */
len = 0;
cursor = 0;
while (cursor < oldlen) {
const unsigned char *mbsequence = NULL;
size_t mbseqlen = 0,
cursor_before = cursor;
int status = SUCCESS;
unsigned int this_char = get_next_char(charset, old, oldlen, &cursor, &status);
/* guarantee we have at least 40 bytes to write.
* In HTML5, entities may take up to 33 bytes */
if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */
replaced = safe_erealloc(replaced, maxlen , 1, 128 + 1);
maxlen += 128;
}
if (status == FAILURE) {
/* invalid MB sequence */
if (flags & ENT_HTML_IGNORE_ERRORS) {
continue;
} else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) {
memcpy(&replaced[len], replacement, replacement_len);
len += replacement_len;
continue;
} else {
efree(replaced);
*newlen = 0;
return STR_EMPTY_ALLOC();
}
} else { /* SUCCESS */
mbsequence = &old[cursor_before];
mbseqlen = cursor - cursor_before;
}
if (this_char != '&') { /* no entity on this position */
const unsigned char *rep = NULL;
size_t rep_len = 0;
if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
goto pass_char_through;
if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */
if (to_uni_table != NULL) {
/* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8
* is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT,
* we're using a single byte encoding */
map_to_unicode(this_char, to_uni_table, &this_char);
if (this_char == 0xFFFF) /* no mapping; pass through */
goto pass_char_through;
}
/* the cursor may advance */
find_entity_for_char(this_char, charset, entity_table.ms_table, &rep,
&rep_len, old, oldlen, &cursor);
} else {
find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len);
}
if (rep != NULL) {
replaced[len++] = '&';
memcpy(&replaced[len], rep, rep_len);
len += rep_len;
replaced[len++] = ';';
} else {
/* we did not find an entity for this char.
* check for its validity, if its valid pass it unchanged */
if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
if (CHARSET_UNICODE_COMPAT(charset)) {
if (!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
} else if (to_uni_table) {
if (!all) /* otherwise we already did this */
map_to_unicode(this_char, to_uni_table, &this_char);
if (!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
} else {
/* not a unicode code point, unless, coincidentally, it's in
* the 0x20..0x7D range (except 0x5C in sjis). We know nothing
* about other code points, because we have no tables. Since
* Unicode code points in that range are not disallowed in any
* document type, we could do nothing. However, conversion
* tables frequently map 0x00-0x1F to the respective C0 code
* points. Let's play it safe and admit that's the case */
if (this_char <= 0x7D &&
!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
}
}
pass_char_through:
if (mbseqlen > 1) {
memcpy(replaced + len, mbsequence, mbseqlen);
len += mbseqlen;
} else {
replaced[len++] = mbsequence[0];
}
}
} else { /* this_char == '&' */
if (double_encode) {
encode_amp:
memcpy(&replaced[len], "&", sizeof("&") - 1);
len += sizeof("&") - 1;
} else { /* no double encode */
/* check if entity is valid */
size_t ent_len; /* not counting & or ; */
/* peek at next char */
if (old[cursor] == '#') { /* numeric entity */
unsigned code_point;
int valid;
char *pos = (char*)&old[cursor+1];
valid = process_numeric_entity((const char **)&pos, &code_point);
if (valid == FAILURE)
goto encode_amp;
if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
if (!numeric_entity_is_allowed(code_point, doctype))
goto encode_amp;
}
ent_len = pos - (char*)&old[cursor];
} else { /* named entity */
/* check for vality of named entity */
const char *start = &old[cursor],
*next = start;
unsigned dummy1, dummy2;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto encode_amp;
if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) {
if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's')) {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
goto encode_amp;
}
}
}
/* checks passed; copy entity to result */
/* entity size is unbounded, we may need more memory */
/* at this point maxlen - len >= 40 */
if (maxlen - len < ent_len + 2 /* & and ; */) {
/* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */
replaced = safe_erealloc(replaced, maxlen, 1, ent_len + 128 + 1);
maxlen += ent_len + 128;
}
replaced[len++] = '&';
memcpy(&replaced[len], &old[cursor], ent_len);
len += ent_len;
replaced[len++] = ';';
cursor += ent_len + 1;
}
}
}
replaced[len] = '\0';
*newlen = len;
return replaced;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | PHPAPI char *php_escape_html_entities_ex(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset, zend_bool double_encode TSRMLS_DC)
{
size_t cursor, maxlen, len;
char *replaced;
enum entity_charset charset = determine_charset(hint_charset TSRMLS_CC);
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
entity_table_opt entity_table;
const enc_to_uni *to_uni_table = NULL;
const entity_ht *inv_map = NULL; /* used for !double_encode */
/* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */
const unsigned char *replacement = NULL;
size_t replacement_len = 0;
if (all) { /* replace with all named entities */
if (CHARSET_PARTIAL_SUPPORT(charset)) {
php_error_docref0(NULL TSRMLS_CC, E_STRICT, "Only basic entities "
"substitution is supported for multi-byte encodings other than UTF-8; "
"functionality is equivalent to htmlspecialchars");
}
LIMIT_ALL(all, doctype, charset);
}
entity_table = determine_entity_table(all, doctype);
if (all && !CHARSET_UNICODE_COMPAT(charset)) {
to_uni_table = enc_to_uni_index[charset];
}
if (!double_encode) {
/* first arg is 1 because we want to identify valid named entities
* even if we are only encoding the basic ones */
inv_map = unescape_inverse_map(1, flags);
}
if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) {
if (charset == cs_utf_8) {
replacement = (const unsigned char*)"\xEF\xBF\xBD";
replacement_len = sizeof("\xEF\xBF\xBD") - 1;
} else {
replacement = (const unsigned char*)"�";
replacement_len = sizeof("�") - 1;
}
}
/* initial estimate */
if (oldlen < 64) {
maxlen = 128;
} else {
maxlen = 2 * oldlen;
if (maxlen < oldlen) {
zend_error_noreturn(E_ERROR, "Input string is too long");
return NULL;
}
}
replaced = emalloc(maxlen + 1); /* adding 1 is safe: maxlen is even */
len = 0;
cursor = 0;
while (cursor < oldlen) {
const unsigned char *mbsequence = NULL;
size_t mbseqlen = 0,
cursor_before = cursor;
int status = SUCCESS;
unsigned int this_char = get_next_char(charset, old, oldlen, &cursor, &status);
/* guarantee we have at least 40 bytes to write.
* In HTML5, entities may take up to 33 bytes */
if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */
replaced = safe_erealloc(replaced, maxlen , 1, 128 + 1);
maxlen += 128;
}
if (status == FAILURE) {
/* invalid MB sequence */
if (flags & ENT_HTML_IGNORE_ERRORS) {
continue;
} else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) {
memcpy(&replaced[len], replacement, replacement_len);
len += replacement_len;
continue;
} else {
efree(replaced);
*newlen = 0;
return STR_EMPTY_ALLOC();
}
} else { /* SUCCESS */
mbsequence = &old[cursor_before];
mbseqlen = cursor - cursor_before;
}
if (this_char != '&') { /* no entity on this position */
const unsigned char *rep = NULL;
size_t rep_len = 0;
if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
goto pass_char_through;
if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */
if (to_uni_table != NULL) {
/* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8
* is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT,
* we're using a single byte encoding */
map_to_unicode(this_char, to_uni_table, &this_char);
if (this_char == 0xFFFF) /* no mapping; pass through */
goto pass_char_through;
}
/* the cursor may advance */
find_entity_for_char(this_char, charset, entity_table.ms_table, &rep,
&rep_len, old, oldlen, &cursor);
} else {
find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len);
}
if (rep != NULL) {
replaced[len++] = '&';
memcpy(&replaced[len], rep, rep_len);
len += rep_len;
replaced[len++] = ';';
} else {
/* we did not find an entity for this char.
* check for its validity, if its valid pass it unchanged */
if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
if (CHARSET_UNICODE_COMPAT(charset)) {
if (!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
} else if (to_uni_table) {
if (!all) /* otherwise we already did this */
map_to_unicode(this_char, to_uni_table, &this_char);
if (!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
} else {
/* not a unicode code point, unless, coincidentally, it's in
* the 0x20..0x7D range (except 0x5C in sjis). We know nothing
* about other code points, because we have no tables. Since
* Unicode code points in that range are not disallowed in any
* document type, we could do nothing. However, conversion
* tables frequently map 0x00-0x1F to the respective C0 code
* points. Let's play it safe and admit that's the case */
if (this_char <= 0x7D &&
!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
}
}
pass_char_through:
if (mbseqlen > 1) {
memcpy(replaced + len, mbsequence, mbseqlen);
len += mbseqlen;
} else {
replaced[len++] = mbsequence[0];
}
}
} else { /* this_char == '&' */
if (double_encode) {
encode_amp:
memcpy(&replaced[len], "&", sizeof("&") - 1);
len += sizeof("&") - 1;
} else { /* no double encode */
/* check if entity is valid */
size_t ent_len; /* not counting & or ; */
/* peek at next char */
if (old[cursor] == '#') { /* numeric entity */
unsigned code_point;
int valid;
char *pos = (char*)&old[cursor+1];
valid = process_numeric_entity((const char **)&pos, &code_point);
if (valid == FAILURE)
goto encode_amp;
if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
if (!numeric_entity_is_allowed(code_point, doctype))
goto encode_amp;
}
ent_len = pos - (char*)&old[cursor];
} else { /* named entity */
/* check for vality of named entity */
const char *start = &old[cursor],
*next = start;
unsigned dummy1, dummy2;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto encode_amp;
if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) {
if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's')) {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
goto encode_amp;
}
}
}
/* checks passed; copy entity to result */
/* entity size is unbounded, we may need more memory */
/* at this point maxlen - len >= 40 */
if (maxlen - len < ent_len + 2 /* & and ; */) {
/* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */
replaced = safe_erealloc(replaced, maxlen, 1, ent_len + 128 + 1);
maxlen += ent_len + 128;
}
replaced[len++] = '&';
memcpy(&replaced[len], &old[cursor], ent_len);
len += ent_len;
replaced[len++] = ';';
cursor += ent_len + 1;
}
}
}
replaced[len] = '\0';
*newlen = len;
return replaced;
}
| 167,174 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext)
{
if (!executionContext)
return;
v8::HandleScope handleScope(toIsolate(executionContext));
v8::Local<v8::Context> v8Context = toV8Context(executionContext, world());
if (v8Context.IsEmpty())
return;
ScriptState* scriptState = ScriptState::from(v8Context);
if (!scriptState->contextIsValid())
return;
if (executionContext->isDocument() && !toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) {
clearListenerObject();
return;
}
if (hasExistingListenerObject())
return;
ASSERT(executionContext->isDocument());
ScriptState::Scope scope(scriptState);
String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName);
String code = "(function() {"
"with (this[2]) {"
"with (this[1]) {"
"with (this[0]) {"
"return function(" + m_eventParameterName + ") {" +
listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler.
"};"
"}}}})";
v8::Handle<v8::String> codeExternalString = v8String(isolate(), code);
v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position);
if (result.IsEmpty())
return;
ASSERT(result->IsFunction());
v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>();
HTMLFormElement* formElement = 0;
if (m_node && m_node->isHTMLElement())
formElement = toHTMLElement(m_node)->formOwner();
v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState);
v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState);
v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState);
v8::Local<v8::Object> thisObject = v8::Object::New(isolate());
if (thisObject.IsEmpty())
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper))
return;
v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate());
if (innerValue.IsEmpty() || !innerValue->IsFunction())
return;
v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>();
v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString);
ASSERT(!toStringFunction.IsEmpty());
String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}";
V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString));
wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction);
wrappedFunction->SetName(v8String(isolate(), m_functionName));
setListenerObject(wrappedFunction);
}
Commit Message: Turn a bunch of ASSERTs into graceful failures when compiling listeners
BUG=456192
[email protected]
Review URL: https://codereview.chromium.org/906193002
git-svn-id: svn://svn.chromium.org/blink/trunk@189796 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-17 | void V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext)
{
if (!executionContext)
return;
v8::HandleScope handleScope(toIsolate(executionContext));
v8::Local<v8::Context> v8Context = toV8Context(executionContext, world());
if (v8Context.IsEmpty())
return;
ScriptState* scriptState = ScriptState::from(v8Context);
if (!scriptState->contextIsValid())
return;
if (!executionContext->isDocument())
return;
if (!toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) {
clearListenerObject();
return;
}
if (hasExistingListenerObject())
return;
ScriptState::Scope scope(scriptState);
String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName);
String code = "(function() {"
"with (this[2]) {"
"with (this[1]) {"
"with (this[0]) {"
"return function(" + m_eventParameterName + ") {" +
listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler.
"};"
"}}}})";
v8::Handle<v8::String> codeExternalString = v8String(isolate(), code);
v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position);
if (result.IsEmpty())
return;
if (!result->IsFunction())
return;
v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>();
HTMLFormElement* formElement = 0;
if (m_node && m_node->isHTMLElement())
formElement = toHTMLElement(m_node)->formOwner();
v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState);
v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState);
v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState);
v8::Local<v8::Object> thisObject = v8::Object::New(isolate());
if (thisObject.IsEmpty())
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper))
return;
v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate());
if (innerValue.IsEmpty() || !innerValue->IsFunction())
return;
v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>();
v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString);
ASSERT(!toStringFunction.IsEmpty());
String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}";
V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString));
wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction);
wrappedFunction->SetName(v8String(isolate(), m_functionName));
setListenerObject(wrappedFunction);
}
| 172,025 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_emit_frobnicate (MyObject *obj, GError **error)
{
g_signal_emit (obj, signals[FROBNICATE], 0, 42);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_emit_frobnicate (MyObject *obj, GError **error)
| 165,094 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int LELib_Create(const effect_uuid_t *uuid,
int32_t sessionId,
int32_t ioId,
effect_handle_t *pHandle) {
ALOGV("LELib_Create()");
int ret;
int i;
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) {
return -EINVAL;
}
LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext;
pContext->mItfe = &gLEInterface;
pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;
pContext->mCompressor = NULL;
ret = LE_init(pContext);
if (ret < 0) {
ALOGW("LELib_Create() init failed");
delete pContext;
return ret;
}
*pHandle = (effect_handle_t)pContext;
pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;
ALOGV(" LELib_Create context is %p", pContext);
return 0;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119 | int LELib_Create(const effect_uuid_t *uuid,
int32_t sessionId __unused,
int32_t ioId __unused,
effect_handle_t *pHandle) {
ALOGV("LELib_Create()");
int ret;
int i;
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) {
return -EINVAL;
}
LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext;
pContext->mItfe = &gLEInterface;
pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;
pContext->mCompressor = NULL;
ret = LE_init(pContext);
if (ret < 0) {
ALOGW("LELib_Create() init failed");
delete pContext;
return ret;
}
*pHandle = (effect_handle_t)pContext;
pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;
ALOGV(" LELib_Create context is %p", pContext);
return 0;
}
| 173,346 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const PixelPacket
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1)
? MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/348
CWE ID: CWE-787 | static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const PixelPacket
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1)
? MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
| 170,102 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static void nfs4_close_prepare(struct rpc_task *task, void *data)
{
struct nfs4_closedata *calldata = data;
struct nfs4_state *state = calldata->state;
int clear_rd, clear_wr, clear_rdwr;
if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0)
return;
clear_rd = clear_wr = clear_rdwr = 0;
spin_lock(&state->owner->so_lock);
/* Calculate the change in open mode */
if (state->n_rdwr == 0) {
if (state->n_rdonly == 0) {
clear_rd |= test_and_clear_bit(NFS_O_RDONLY_STATE, &state->flags);
clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags);
}
if (state->n_wronly == 0) {
clear_wr |= test_and_clear_bit(NFS_O_WRONLY_STATE, &state->flags);
clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags);
}
}
spin_unlock(&state->owner->so_lock);
if (!clear_rd && !clear_wr && !clear_rdwr) {
/* Note: exit _without_ calling nfs4_close_done */
task->tk_action = NULL;
return;
}
nfs_fattr_init(calldata->res.fattr);
if (test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE];
calldata->arg.open_flags = FMODE_READ;
} else if (test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE];
calldata->arg.open_flags = FMODE_WRITE;
}
calldata->timestamp = jiffies;
rpc_call_start(task);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void nfs4_close_prepare(struct rpc_task *task, void *data)
{
struct nfs4_closedata *calldata = data;
struct nfs4_state *state = calldata->state;
int clear_rd, clear_wr, clear_rdwr;
if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0)
return;
clear_rd = clear_wr = clear_rdwr = 0;
spin_lock(&state->owner->so_lock);
/* Calculate the change in open mode */
if (state->n_rdwr == 0) {
if (state->n_rdonly == 0) {
clear_rd |= test_and_clear_bit(NFS_O_RDONLY_STATE, &state->flags);
clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags);
}
if (state->n_wronly == 0) {
clear_wr |= test_and_clear_bit(NFS_O_WRONLY_STATE, &state->flags);
clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags);
}
}
spin_unlock(&state->owner->so_lock);
if (!clear_rd && !clear_wr && !clear_rdwr) {
/* Note: exit _without_ calling nfs4_close_done */
task->tk_action = NULL;
return;
}
nfs_fattr_init(calldata->res.fattr);
if (test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE];
calldata->arg.fmode = FMODE_READ;
} else if (test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE];
calldata->arg.fmode = FMODE_WRITE;
}
calldata->timestamp = jiffies;
rpc_call_start(task);
}
| 165,690 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int ttusbdecfe_dvbs_diseqc_send_master_cmd(struct dvb_frontend* fe, struct dvb_diseqc_master_cmd *cmd)
{
struct ttusbdecfe_state* state = (struct ttusbdecfe_state*) fe->demodulator_priv;
u8 b[] = { 0x00, 0xff, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00 };
memcpy(&b[4], cmd->msg, cmd->msg_len);
state->config->send_command(fe, 0x72,
sizeof(b) - (6 - cmd->msg_len), b,
NULL, NULL);
return 0;
}
Commit Message: [media] ttusb-dec: buffer overflow in ioctl
We need to add a limit check here so we don't overflow the buffer.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | static int ttusbdecfe_dvbs_diseqc_send_master_cmd(struct dvb_frontend* fe, struct dvb_diseqc_master_cmd *cmd)
{
struct ttusbdecfe_state* state = (struct ttusbdecfe_state*) fe->demodulator_priv;
u8 b[] = { 0x00, 0xff, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00 };
if (cmd->msg_len > sizeof(b) - 4)
return -EINVAL;
memcpy(&b[4], cmd->msg, cmd->msg_len);
state->config->send_command(fe, 0x72,
sizeof(b) - (6 - cmd->msg_len), b,
NULL, NULL);
return 0;
}
| 166,241 |
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. Remember, I want response with just the fixed code only, No explanation. | 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) {}
| 173,266 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
uint8_t i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %d, RES: %d, Sel: %d",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07)));
ND_PRINT((ndo, "Protocol ID: %d", EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
Commit Message: CVE-2017-12997/LLDP: Don't use an 8-bit loop counter.
If you have a
for (i = 0; i < N; i++)
loop, you'd better make sure that i is big enough to hold N - not N-1,
N.
The TLV length here is 9 bits long, not 8 bits long, so an 8-bit loop
counter will overflow and you can loop infinitely.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add tests using the capture files supplied by the reporter(s).
Clean up the output a bit while we're at it.
CWE ID: CWE-835 | lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
u_int i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %u, RES: %u, Sel: %u, Protocol ID: %u",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07),
EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
| 167,910 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: krb5_gss_export_sec_context(minor_status, context_handle, interprocess_token)
OM_uint32 *minor_status;
gss_ctx_id_t *context_handle;
gss_buffer_t interprocess_token;
{
krb5_context context = NULL;
krb5_error_code kret;
OM_uint32 retval;
size_t bufsize, blen;
krb5_gss_ctx_id_t ctx;
krb5_octet *obuffer, *obp;
/* Assume a tragic failure */
obuffer = (krb5_octet *) NULL;
retval = GSS_S_FAILURE;
*minor_status = 0;
ctx = (krb5_gss_ctx_id_t) *context_handle;
context = ctx->k5_context;
kret = krb5_gss_ser_init(context);
if (kret)
goto error_out;
/* Determine size needed for externalization of context */
bufsize = 0;
if ((kret = kg_ctx_size(context, (krb5_pointer) ctx,
&bufsize)))
goto error_out;
/* Allocate the buffer */
if ((obuffer = gssalloc_malloc(bufsize)) == NULL) {
kret = ENOMEM;
goto error_out;
}
obp = obuffer;
blen = bufsize;
/* Externalize the context */
if ((kret = kg_ctx_externalize(context,
(krb5_pointer) ctx, &obp, &blen)))
goto error_out;
/* Success! Return the buffer */
interprocess_token->length = bufsize - blen;
interprocess_token->value = obuffer;
*minor_status = 0;
retval = GSS_S_COMPLETE;
/* Now, clean up the context state */
(void)krb5_gss_delete_sec_context(minor_status, context_handle, NULL);
*context_handle = GSS_C_NO_CONTEXT;
return (GSS_S_COMPLETE);
error_out:
if (retval != GSS_S_COMPLETE)
if (kret != 0 && context != 0)
save_error_info((OM_uint32)kret, context);
if (obuffer && bufsize) {
memset(obuffer, 0, bufsize);
xfree(obuffer);
}
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | krb5_gss_export_sec_context(minor_status, context_handle, interprocess_token)
OM_uint32 *minor_status;
gss_ctx_id_t *context_handle;
gss_buffer_t interprocess_token;
{
krb5_context context = NULL;
krb5_error_code kret;
OM_uint32 retval;
size_t bufsize, blen;
krb5_gss_ctx_id_t ctx;
krb5_octet *obuffer, *obp;
/* Assume a tragic failure */
obuffer = (krb5_octet *) NULL;
retval = GSS_S_FAILURE;
*minor_status = 0;
ctx = (krb5_gss_ctx_id_t) *context_handle;
if (ctx->terminated) {
*minor_status = KG_CTX_INCOMPLETE;
return (GSS_S_NO_CONTEXT);
}
context = ctx->k5_context;
kret = krb5_gss_ser_init(context);
if (kret)
goto error_out;
/* Determine size needed for externalization of context */
bufsize = 0;
if ((kret = kg_ctx_size(context, (krb5_pointer) ctx,
&bufsize)))
goto error_out;
/* Allocate the buffer */
if ((obuffer = gssalloc_malloc(bufsize)) == NULL) {
kret = ENOMEM;
goto error_out;
}
obp = obuffer;
blen = bufsize;
/* Externalize the context */
if ((kret = kg_ctx_externalize(context,
(krb5_pointer) ctx, &obp, &blen)))
goto error_out;
/* Success! Return the buffer */
interprocess_token->length = bufsize - blen;
interprocess_token->value = obuffer;
*minor_status = 0;
retval = GSS_S_COMPLETE;
/* Now, clean up the context state */
(void)krb5_gss_delete_sec_context(minor_status, context_handle, NULL);
*context_handle = GSS_C_NO_CONTEXT;
return (GSS_S_COMPLETE);
error_out:
if (retval != GSS_S_COMPLETE)
if (kret != 0 && context != 0)
save_error_info((OM_uint32)kret, context);
if (obuffer && bufsize) {
memset(obuffer, 0, bufsize);
xfree(obuffer);
}
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
| 166,814 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static grub_err_t read_foo (struct grub_disk *disk, grub_disk_addr_t sector, grub_size_t size, char *buf) {
if (disk != NULL) {
const int blocksize = 512; // unhardcode 512
int ret;
RIOBind *iob = disk->data;
if (bio) iob = bio;
ret = iob->read_at (iob->io, delta+(blocksize*sector),
(ut8*)buf, size*blocksize);
if (ret == -1)
return 1;
} else eprintf ("oops. no disk\n");
return 0; // 0 is ok
}
Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack
CWE ID: CWE-119 | static grub_err_t read_foo (struct grub_disk *disk, grub_disk_addr_t sector, grub_size_t size, char *buf) {
if (!disk) {
eprintf ("oops. no disk\n");
return 1;
}
const int blocksize = 512; // TODO unhardcode 512
RIOBind *iob = disk->data;
if (bio) {
iob = bio;
}
//printf ("io %p\n", file->root->iob.io);
if (iob->read_at (iob->io, delta+(blocksize*sector), (ut8*)buf, size*blocksize) == -1) {
return 1;
}
return 0;
}
| 168,091 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
u32 __user *uaddr2, int nr_wake, int nr_requeue,
u32 *cmpval, int requeue_pi)
{
union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
int drop_count = 0, task_count = 0, ret;
struct futex_pi_state *pi_state = NULL;
struct futex_hash_bucket *hb1, *hb2;
struct futex_q *this, *next;
DEFINE_WAKE_Q(wake_q);
/*
* When PI not supported: return -ENOSYS if requeue_pi is true,
* consequently the compiler knows requeue_pi is always false past
* this point which will optimize away all the conditional code
* further down.
*/
if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
return -ENOSYS;
if (requeue_pi) {
/*
* Requeue PI only works on two distinct uaddrs. This
* check is only valid for private futexes. See below.
*/
if (uaddr1 == uaddr2)
return -EINVAL;
/*
* requeue_pi requires a pi_state, try to allocate it now
* without any locks in case it fails.
*/
if (refill_pi_state_cache())
return -ENOMEM;
/*
* requeue_pi must wake as many tasks as it can, up to nr_wake
* + nr_requeue, since it acquires the rt_mutex prior to
* returning to userspace, so as to not leave the rt_mutex with
* waiters and no owner. However, second and third wake-ups
* cannot be predicted as they involve race conditions with the
* first wake and a fault while looking up the pi_state. Both
* pthread_cond_signal() and pthread_cond_broadcast() should
* use nr_wake=1.
*/
if (nr_wake != 1)
return -EINVAL;
}
retry:
ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
if (unlikely(ret != 0))
goto out;
ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
requeue_pi ? VERIFY_WRITE : VERIFY_READ);
if (unlikely(ret != 0))
goto out_put_key1;
/*
* The check above which compares uaddrs is not sufficient for
* shared futexes. We need to compare the keys:
*/
if (requeue_pi && match_futex(&key1, &key2)) {
ret = -EINVAL;
goto out_put_keys;
}
hb1 = hash_futex(&key1);
hb2 = hash_futex(&key2);
retry_private:
hb_waiters_inc(hb2);
double_lock_hb(hb1, hb2);
if (likely(cmpval != NULL)) {
u32 curval;
ret = get_futex_value_locked(&curval, uaddr1);
if (unlikely(ret)) {
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
ret = get_user(curval, uaddr1);
if (ret)
goto out_put_keys;
if (!(flags & FLAGS_SHARED))
goto retry_private;
put_futex_key(&key2);
put_futex_key(&key1);
goto retry;
}
if (curval != *cmpval) {
ret = -EAGAIN;
goto out_unlock;
}
}
if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
/*
* Attempt to acquire uaddr2 and wake the top waiter. If we
* intend to requeue waiters, force setting the FUTEX_WAITERS
* bit. We force this here where we are able to easily handle
* faults rather in the requeue loop below.
*/
ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
&key2, &pi_state, nr_requeue);
/*
* At this point the top_waiter has either taken uaddr2 or is
* waiting on it. If the former, then the pi_state will not
* exist yet, look it up one more time to ensure we have a
* reference to it. If the lock was taken, ret contains the
* vpid of the top waiter task.
* If the lock was not taken, we have pi_state and an initial
* refcount on it. In case of an error we have nothing.
*/
if (ret > 0) {
WARN_ON(pi_state);
drop_count++;
task_count++;
/*
* If we acquired the lock, then the user space value
* of uaddr2 should be vpid. It cannot be changed by
* the top waiter as it is blocked on hb2 lock if it
* tries to do so. If something fiddled with it behind
* our back the pi state lookup might unearth it. So
* we rather use the known value than rereading and
* handing potential crap to lookup_pi_state.
*
* If that call succeeds then we have pi_state and an
* initial refcount on it.
*/
ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state);
}
switch (ret) {
case 0:
/* We hold a reference on the pi state. */
break;
/* If the above failed, then pi_state is NULL */
case -EFAULT:
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
put_futex_key(&key2);
put_futex_key(&key1);
ret = fault_in_user_writeable(uaddr2);
if (!ret)
goto retry;
goto out;
case -EAGAIN:
/*
* Two reasons for this:
* - Owner is exiting and we just wait for the
* exit to complete.
* - The user space value changed.
*/
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
put_futex_key(&key2);
put_futex_key(&key1);
cond_resched();
goto retry;
default:
goto out_unlock;
}
}
plist_for_each_entry_safe(this, next, &hb1->chain, list) {
if (task_count - nr_wake >= nr_requeue)
break;
if (!match_futex(&this->key, &key1))
continue;
/*
* FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
* be paired with each other and no other futex ops.
*
* We should never be requeueing a futex_q with a pi_state,
* which is awaiting a futex_unlock_pi().
*/
if ((requeue_pi && !this->rt_waiter) ||
(!requeue_pi && this->rt_waiter) ||
this->pi_state) {
ret = -EINVAL;
break;
}
/*
* Wake nr_wake waiters. For requeue_pi, if we acquired the
* lock, we already woke the top_waiter. If not, it will be
* woken by futex_unlock_pi().
*/
if (++task_count <= nr_wake && !requeue_pi) {
mark_wake_futex(&wake_q, this);
continue;
}
/* Ensure we requeue to the expected futex for requeue_pi. */
if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
ret = -EINVAL;
break;
}
/*
* Requeue nr_requeue waiters and possibly one more in the case
* of requeue_pi if we couldn't acquire the lock atomically.
*/
if (requeue_pi) {
/*
* Prepare the waiter to take the rt_mutex. Take a
* refcount on the pi_state and store the pointer in
* the futex_q object of the waiter.
*/
get_pi_state(pi_state);
this->pi_state = pi_state;
ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
this->rt_waiter,
this->task);
if (ret == 1) {
/*
* We got the lock. We do neither drop the
* refcount on pi_state nor clear
* this->pi_state because the waiter needs the
* pi_state for cleaning up the user space
* value. It will drop the refcount after
* doing so.
*/
requeue_pi_wake_futex(this, &key2, hb2);
drop_count++;
continue;
} else if (ret) {
/*
* rt_mutex_start_proxy_lock() detected a
* potential deadlock when we tried to queue
* that waiter. Drop the pi_state reference
* which we took above and remove the pointer
* to the state from the waiters futex_q
* object.
*/
this->pi_state = NULL;
put_pi_state(pi_state);
/*
* We stop queueing more waiters and let user
* space deal with the mess.
*/
break;
}
}
requeue_futex(this, hb1, hb2, &key2);
drop_count++;
}
/*
* We took an extra initial reference to the pi_state either
* in futex_proxy_trylock_atomic() or in lookup_pi_state(). We
* need to drop it here again.
*/
put_pi_state(pi_state);
out_unlock:
double_unlock_hb(hb1, hb2);
wake_up_q(&wake_q);
hb_waiters_dec(hb2);
/*
* drop_futex_key_refs() must be called outside the spinlocks. During
* the requeue we moved futex_q's from the hash bucket at key1 to the
* one at key2 and updated their key pointer. We no longer need to
* hold the references to key1.
*/
while (--drop_count >= 0)
drop_futex_key_refs(&key1);
out_put_keys:
put_futex_key(&key2);
out_put_key1:
put_futex_key(&key1);
out:
return ret ? ret : task_count;
}
Commit Message: futex: Prevent overflow by strengthen input validation
UBSAN reports signed integer overflow in kernel/futex.c:
UBSAN: Undefined behaviour in kernel/futex.c:2041:18
signed integer overflow:
0 - -2147483648 cannot be represented in type 'int'
Add a sanity check to catch negative values of nr_wake and nr_requeue.
Signed-off-by: Li Jinyue <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Link: https://lkml.kernel.org/r/[email protected]
CWE ID: CWE-190 | static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
u32 __user *uaddr2, int nr_wake, int nr_requeue,
u32 *cmpval, int requeue_pi)
{
union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
int drop_count = 0, task_count = 0, ret;
struct futex_pi_state *pi_state = NULL;
struct futex_hash_bucket *hb1, *hb2;
struct futex_q *this, *next;
DEFINE_WAKE_Q(wake_q);
if (nr_wake < 0 || nr_requeue < 0)
return -EINVAL;
/*
* When PI not supported: return -ENOSYS if requeue_pi is true,
* consequently the compiler knows requeue_pi is always false past
* this point which will optimize away all the conditional code
* further down.
*/
if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
return -ENOSYS;
if (requeue_pi) {
/*
* Requeue PI only works on two distinct uaddrs. This
* check is only valid for private futexes. See below.
*/
if (uaddr1 == uaddr2)
return -EINVAL;
/*
* requeue_pi requires a pi_state, try to allocate it now
* without any locks in case it fails.
*/
if (refill_pi_state_cache())
return -ENOMEM;
/*
* requeue_pi must wake as many tasks as it can, up to nr_wake
* + nr_requeue, since it acquires the rt_mutex prior to
* returning to userspace, so as to not leave the rt_mutex with
* waiters and no owner. However, second and third wake-ups
* cannot be predicted as they involve race conditions with the
* first wake and a fault while looking up the pi_state. Both
* pthread_cond_signal() and pthread_cond_broadcast() should
* use nr_wake=1.
*/
if (nr_wake != 1)
return -EINVAL;
}
retry:
ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
if (unlikely(ret != 0))
goto out;
ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
requeue_pi ? VERIFY_WRITE : VERIFY_READ);
if (unlikely(ret != 0))
goto out_put_key1;
/*
* The check above which compares uaddrs is not sufficient for
* shared futexes. We need to compare the keys:
*/
if (requeue_pi && match_futex(&key1, &key2)) {
ret = -EINVAL;
goto out_put_keys;
}
hb1 = hash_futex(&key1);
hb2 = hash_futex(&key2);
retry_private:
hb_waiters_inc(hb2);
double_lock_hb(hb1, hb2);
if (likely(cmpval != NULL)) {
u32 curval;
ret = get_futex_value_locked(&curval, uaddr1);
if (unlikely(ret)) {
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
ret = get_user(curval, uaddr1);
if (ret)
goto out_put_keys;
if (!(flags & FLAGS_SHARED))
goto retry_private;
put_futex_key(&key2);
put_futex_key(&key1);
goto retry;
}
if (curval != *cmpval) {
ret = -EAGAIN;
goto out_unlock;
}
}
if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
/*
* Attempt to acquire uaddr2 and wake the top waiter. If we
* intend to requeue waiters, force setting the FUTEX_WAITERS
* bit. We force this here where we are able to easily handle
* faults rather in the requeue loop below.
*/
ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
&key2, &pi_state, nr_requeue);
/*
* At this point the top_waiter has either taken uaddr2 or is
* waiting on it. If the former, then the pi_state will not
* exist yet, look it up one more time to ensure we have a
* reference to it. If the lock was taken, ret contains the
* vpid of the top waiter task.
* If the lock was not taken, we have pi_state and an initial
* refcount on it. In case of an error we have nothing.
*/
if (ret > 0) {
WARN_ON(pi_state);
drop_count++;
task_count++;
/*
* If we acquired the lock, then the user space value
* of uaddr2 should be vpid. It cannot be changed by
* the top waiter as it is blocked on hb2 lock if it
* tries to do so. If something fiddled with it behind
* our back the pi state lookup might unearth it. So
* we rather use the known value than rereading and
* handing potential crap to lookup_pi_state.
*
* If that call succeeds then we have pi_state and an
* initial refcount on it.
*/
ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state);
}
switch (ret) {
case 0:
/* We hold a reference on the pi state. */
break;
/* If the above failed, then pi_state is NULL */
case -EFAULT:
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
put_futex_key(&key2);
put_futex_key(&key1);
ret = fault_in_user_writeable(uaddr2);
if (!ret)
goto retry;
goto out;
case -EAGAIN:
/*
* Two reasons for this:
* - Owner is exiting and we just wait for the
* exit to complete.
* - The user space value changed.
*/
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
put_futex_key(&key2);
put_futex_key(&key1);
cond_resched();
goto retry;
default:
goto out_unlock;
}
}
plist_for_each_entry_safe(this, next, &hb1->chain, list) {
if (task_count - nr_wake >= nr_requeue)
break;
if (!match_futex(&this->key, &key1))
continue;
/*
* FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
* be paired with each other and no other futex ops.
*
* We should never be requeueing a futex_q with a pi_state,
* which is awaiting a futex_unlock_pi().
*/
if ((requeue_pi && !this->rt_waiter) ||
(!requeue_pi && this->rt_waiter) ||
this->pi_state) {
ret = -EINVAL;
break;
}
/*
* Wake nr_wake waiters. For requeue_pi, if we acquired the
* lock, we already woke the top_waiter. If not, it will be
* woken by futex_unlock_pi().
*/
if (++task_count <= nr_wake && !requeue_pi) {
mark_wake_futex(&wake_q, this);
continue;
}
/* Ensure we requeue to the expected futex for requeue_pi. */
if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
ret = -EINVAL;
break;
}
/*
* Requeue nr_requeue waiters and possibly one more in the case
* of requeue_pi if we couldn't acquire the lock atomically.
*/
if (requeue_pi) {
/*
* Prepare the waiter to take the rt_mutex. Take a
* refcount on the pi_state and store the pointer in
* the futex_q object of the waiter.
*/
get_pi_state(pi_state);
this->pi_state = pi_state;
ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
this->rt_waiter,
this->task);
if (ret == 1) {
/*
* We got the lock. We do neither drop the
* refcount on pi_state nor clear
* this->pi_state because the waiter needs the
* pi_state for cleaning up the user space
* value. It will drop the refcount after
* doing so.
*/
requeue_pi_wake_futex(this, &key2, hb2);
drop_count++;
continue;
} else if (ret) {
/*
* rt_mutex_start_proxy_lock() detected a
* potential deadlock when we tried to queue
* that waiter. Drop the pi_state reference
* which we took above and remove the pointer
* to the state from the waiters futex_q
* object.
*/
this->pi_state = NULL;
put_pi_state(pi_state);
/*
* We stop queueing more waiters and let user
* space deal with the mess.
*/
break;
}
}
requeue_futex(this, hb1, hb2, &key2);
drop_count++;
}
/*
* We took an extra initial reference to the pi_state either
* in futex_proxy_trylock_atomic() or in lookup_pi_state(). We
* need to drop it here again.
*/
put_pi_state(pi_state);
out_unlock:
double_unlock_hb(hb1, hb2);
wake_up_q(&wake_q);
hb_waiters_dec(hb2);
/*
* drop_futex_key_refs() must be called outside the spinlocks. During
* the requeue we moved futex_q's from the hash bucket at key1 to the
* one at key2 and updated their key pointer. We no longer need to
* hold the references to key1.
*/
while (--drop_count >= 0)
drop_futex_key_refs(&key1);
out_put_keys:
put_futex_key(&key2);
out_put_key1:
put_futex_key(&key1);
out:
return ret ? ret : task_count;
}
| 169,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. Remember, I want response with just the fixed code only, No explanation. | Code: static void parse_hid_report_descriptor(struct gtco *device, char * report,
int length)
{
struct device *ddev = &device->intf->dev;
int x, i = 0;
/* Tag primitive vars */
__u8 prefix;
__u8 size;
__u8 tag;
__u8 type;
__u8 data = 0;
__u16 data16 = 0;
__u32 data32 = 0;
/* For parsing logic */
int inputnum = 0;
__u32 usage = 0;
/* Global Values, indexed by TAG */
__u32 globalval[TAG_GLOB_MAX];
__u32 oldval[TAG_GLOB_MAX];
/* Debug stuff */
char maintype = 'x';
char globtype[12];
int indent = 0;
char indentstr[10] = "";
dev_dbg(ddev, "======>>>>>>PARSE<<<<<<======\n");
/* Walk this report and pull out the info we need */
while (i < length) {
prefix = report[i];
/* Skip over prefix */
i++;
/* Determine data size and save the data in the proper variable */
size = PREF_SIZE(prefix);
switch (size) {
case 1:
data = report[i];
break;
case 2:
data16 = get_unaligned_le16(&report[i]);
break;
case 3:
size = 4;
data32 = get_unaligned_le32(&report[i]);
break;
}
/* Skip size of data */
i += size;
/* What we do depends on the tag type */
tag = PREF_TAG(prefix);
type = PREF_TYPE(prefix);
switch (type) {
case TYPE_MAIN:
strcpy(globtype, "");
switch (tag) {
case TAG_MAIN_INPUT:
/*
* The INPUT MAIN tag signifies this is
* information from a report. We need to
* figure out what it is and store the
* min/max values
*/
maintype = 'I';
if (data == 2)
strcpy(globtype, "Variable");
else if (data == 3)
strcpy(globtype, "Var|Const");
dev_dbg(ddev, "::::: Saving Report: %d input #%d Max: 0x%X(%d) Min:0x%X(%d) of %d bits\n",
globalval[TAG_GLOB_REPORT_ID], inputnum,
globalval[TAG_GLOB_LOG_MAX], globalval[TAG_GLOB_LOG_MAX],
globalval[TAG_GLOB_LOG_MIN], globalval[TAG_GLOB_LOG_MIN],
globalval[TAG_GLOB_REPORT_SZ] * globalval[TAG_GLOB_REPORT_CNT]);
/*
We can assume that the first two input items
are always the X and Y coordinates. After
that, we look for everything else by
local usage value
*/
switch (inputnum) {
case 0: /* X coord */
dev_dbg(ddev, "GER: X Usage: 0x%x\n", usage);
if (device->max_X == 0) {
device->max_X = globalval[TAG_GLOB_LOG_MAX];
device->min_X = globalval[TAG_GLOB_LOG_MIN];
}
break;
case 1: /* Y coord */
dev_dbg(ddev, "GER: Y Usage: 0x%x\n", usage);
if (device->max_Y == 0) {
device->max_Y = globalval[TAG_GLOB_LOG_MAX];
device->min_Y = globalval[TAG_GLOB_LOG_MIN];
}
break;
default:
/* Tilt X */
if (usage == DIGITIZER_USAGE_TILT_X) {
if (device->maxtilt_X == 0) {
device->maxtilt_X = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_X = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Tilt Y */
if (usage == DIGITIZER_USAGE_TILT_Y) {
if (device->maxtilt_Y == 0) {
device->maxtilt_Y = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_Y = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Pressure */
if (usage == DIGITIZER_USAGE_TIP_PRESSURE) {
if (device->maxpressure == 0) {
device->maxpressure = globalval[TAG_GLOB_LOG_MAX];
device->minpressure = globalval[TAG_GLOB_LOG_MIN];
}
}
break;
}
inputnum++;
break;
case TAG_MAIN_OUTPUT:
maintype = 'O';
break;
case TAG_MAIN_FEATURE:
maintype = 'F';
break;
case TAG_MAIN_COL_START:
maintype = 'S';
if (data == 0) {
dev_dbg(ddev, "======>>>>>> Physical\n");
strcpy(globtype, "Physical");
} else
dev_dbg(ddev, "======>>>>>>\n");
/* Indent the debug output */
indent++;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Save global tags */
for (x = 0; x < TAG_GLOB_MAX; x++)
oldval[x] = globalval[x];
break;
case TAG_MAIN_COL_END:
dev_dbg(ddev, "<<<<<<======\n");
maintype = 'E';
indent--;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Copy global tags back */
for (x = 0; x < TAG_GLOB_MAX; x++)
globalval[x] = oldval[x];
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data);
break;
case 2:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data16);
break;
case 4:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data32);
break;
}
break;
case TYPE_GLOBAL:
switch (tag) {
case TAG_GLOB_USAGE:
/*
* First time we hit the global usage tag,
* it should tell us the type of device
*/
if (device->usage == 0)
device->usage = data;
strcpy(globtype, "USAGE");
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "LOG_MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "LOG_MAX");
break;
case TAG_GLOB_PHYS_MIN:
strcpy(globtype, "PHYS_MIN");
break;
case TAG_GLOB_PHYS_MAX:
strcpy(globtype, "PHYS_MAX");
break;
case TAG_GLOB_UNIT_EXP:
strcpy(globtype, "EXP");
break;
case TAG_GLOB_UNIT:
strcpy(globtype, "UNIT");
break;
case TAG_GLOB_REPORT_SZ:
strcpy(globtype, "REPORT_SZ");
break;
case TAG_GLOB_REPORT_ID:
strcpy(globtype, "REPORT_ID");
/* New report, restart numbering */
inputnum = 0;
break;
case TAG_GLOB_REPORT_CNT:
strcpy(globtype, "REPORT_CNT");
break;
case TAG_GLOB_PUSH:
strcpy(globtype, "PUSH");
break;
case TAG_GLOB_POP:
strcpy(globtype, "POP");
break;
}
/* Check to make sure we have a good tag number
so we don't overflow array */
if (tag < TAG_GLOB_MAX) {
switch (size) {
case 1:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data);
globalval[tag] = data;
break;
case 2:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data16);
globalval[tag] = data16;
break;
case 4:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data32);
globalval[tag] = data32;
break;
}
} else {
dev_dbg(ddev, "%sGLOBALTAG: ILLEGAL TAG:%d SIZE: %d\n",
indentstr, tag, size);
}
break;
case TYPE_LOCAL:
switch (tag) {
case TAG_GLOB_USAGE:
strcpy(globtype, "USAGE");
/* Always 1 byte */
usage = data;
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "MAX");
break;
default:
strcpy(globtype, "UNKNOWN");
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data);
break;
case 2:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data16);
break;
case 4:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data32);
break;
}
break;
}
}
}
Commit Message: Input: gtco - fix potential out-of-bound access
parse_hid_report_descriptor() has a while (i < length) loop, which
only guarantees that there's at least 1 byte in the buffer, but the
loop body can read multiple bytes which causes out-of-bounds access.
Reported-by: Andrey Konovalov <[email protected]>
Reviewed-by: Andrey Konovalov <[email protected]>
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID: CWE-125 | static void parse_hid_report_descriptor(struct gtco *device, char * report,
int length)
{
struct device *ddev = &device->intf->dev;
int x, i = 0;
/* Tag primitive vars */
__u8 prefix;
__u8 size;
__u8 tag;
__u8 type;
__u8 data = 0;
__u16 data16 = 0;
__u32 data32 = 0;
/* For parsing logic */
int inputnum = 0;
__u32 usage = 0;
/* Global Values, indexed by TAG */
__u32 globalval[TAG_GLOB_MAX];
__u32 oldval[TAG_GLOB_MAX];
/* Debug stuff */
char maintype = 'x';
char globtype[12];
int indent = 0;
char indentstr[10] = "";
dev_dbg(ddev, "======>>>>>>PARSE<<<<<<======\n");
/* Walk this report and pull out the info we need */
while (i < length) {
prefix = report[i++];
/* Determine data size and save the data in the proper variable */
size = (1U << PREF_SIZE(prefix)) >> 1;
if (i + size > length) {
dev_err(ddev,
"Not enough data (need %d, have %d)\n",
i + size, length);
break;
}
switch (size) {
case 1:
data = report[i];
break;
case 2:
data16 = get_unaligned_le16(&report[i]);
break;
case 4:
data32 = get_unaligned_le32(&report[i]);
break;
}
/* Skip size of data */
i += size;
/* What we do depends on the tag type */
tag = PREF_TAG(prefix);
type = PREF_TYPE(prefix);
switch (type) {
case TYPE_MAIN:
strcpy(globtype, "");
switch (tag) {
case TAG_MAIN_INPUT:
/*
* The INPUT MAIN tag signifies this is
* information from a report. We need to
* figure out what it is and store the
* min/max values
*/
maintype = 'I';
if (data == 2)
strcpy(globtype, "Variable");
else if (data == 3)
strcpy(globtype, "Var|Const");
dev_dbg(ddev, "::::: Saving Report: %d input #%d Max: 0x%X(%d) Min:0x%X(%d) of %d bits\n",
globalval[TAG_GLOB_REPORT_ID], inputnum,
globalval[TAG_GLOB_LOG_MAX], globalval[TAG_GLOB_LOG_MAX],
globalval[TAG_GLOB_LOG_MIN], globalval[TAG_GLOB_LOG_MIN],
globalval[TAG_GLOB_REPORT_SZ] * globalval[TAG_GLOB_REPORT_CNT]);
/*
We can assume that the first two input items
are always the X and Y coordinates. After
that, we look for everything else by
local usage value
*/
switch (inputnum) {
case 0: /* X coord */
dev_dbg(ddev, "GER: X Usage: 0x%x\n", usage);
if (device->max_X == 0) {
device->max_X = globalval[TAG_GLOB_LOG_MAX];
device->min_X = globalval[TAG_GLOB_LOG_MIN];
}
break;
case 1: /* Y coord */
dev_dbg(ddev, "GER: Y Usage: 0x%x\n", usage);
if (device->max_Y == 0) {
device->max_Y = globalval[TAG_GLOB_LOG_MAX];
device->min_Y = globalval[TAG_GLOB_LOG_MIN];
}
break;
default:
/* Tilt X */
if (usage == DIGITIZER_USAGE_TILT_X) {
if (device->maxtilt_X == 0) {
device->maxtilt_X = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_X = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Tilt Y */
if (usage == DIGITIZER_USAGE_TILT_Y) {
if (device->maxtilt_Y == 0) {
device->maxtilt_Y = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_Y = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Pressure */
if (usage == DIGITIZER_USAGE_TIP_PRESSURE) {
if (device->maxpressure == 0) {
device->maxpressure = globalval[TAG_GLOB_LOG_MAX];
device->minpressure = globalval[TAG_GLOB_LOG_MIN];
}
}
break;
}
inputnum++;
break;
case TAG_MAIN_OUTPUT:
maintype = 'O';
break;
case TAG_MAIN_FEATURE:
maintype = 'F';
break;
case TAG_MAIN_COL_START:
maintype = 'S';
if (data == 0) {
dev_dbg(ddev, "======>>>>>> Physical\n");
strcpy(globtype, "Physical");
} else
dev_dbg(ddev, "======>>>>>>\n");
/* Indent the debug output */
indent++;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Save global tags */
for (x = 0; x < TAG_GLOB_MAX; x++)
oldval[x] = globalval[x];
break;
case TAG_MAIN_COL_END:
dev_dbg(ddev, "<<<<<<======\n");
maintype = 'E';
indent--;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Copy global tags back */
for (x = 0; x < TAG_GLOB_MAX; x++)
globalval[x] = oldval[x];
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data);
break;
case 2:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data16);
break;
case 4:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data32);
break;
}
break;
case TYPE_GLOBAL:
switch (tag) {
case TAG_GLOB_USAGE:
/*
* First time we hit the global usage tag,
* it should tell us the type of device
*/
if (device->usage == 0)
device->usage = data;
strcpy(globtype, "USAGE");
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "LOG_MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "LOG_MAX");
break;
case TAG_GLOB_PHYS_MIN:
strcpy(globtype, "PHYS_MIN");
break;
case TAG_GLOB_PHYS_MAX:
strcpy(globtype, "PHYS_MAX");
break;
case TAG_GLOB_UNIT_EXP:
strcpy(globtype, "EXP");
break;
case TAG_GLOB_UNIT:
strcpy(globtype, "UNIT");
break;
case TAG_GLOB_REPORT_SZ:
strcpy(globtype, "REPORT_SZ");
break;
case TAG_GLOB_REPORT_ID:
strcpy(globtype, "REPORT_ID");
/* New report, restart numbering */
inputnum = 0;
break;
case TAG_GLOB_REPORT_CNT:
strcpy(globtype, "REPORT_CNT");
break;
case TAG_GLOB_PUSH:
strcpy(globtype, "PUSH");
break;
case TAG_GLOB_POP:
strcpy(globtype, "POP");
break;
}
/* Check to make sure we have a good tag number
so we don't overflow array */
if (tag < TAG_GLOB_MAX) {
switch (size) {
case 1:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data);
globalval[tag] = data;
break;
case 2:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data16);
globalval[tag] = data16;
break;
case 4:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data32);
globalval[tag] = data32;
break;
}
} else {
dev_dbg(ddev, "%sGLOBALTAG: ILLEGAL TAG:%d SIZE: %d\n",
indentstr, tag, size);
}
break;
case TYPE_LOCAL:
switch (tag) {
case TAG_GLOB_USAGE:
strcpy(globtype, "USAGE");
/* Always 1 byte */
usage = data;
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "MAX");
break;
default:
strcpy(globtype, "UNKNOWN");
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data);
break;
case 2:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data16);
break;
case 4:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data32);
break;
}
break;
}
}
}
| 167,673 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b;
struct sshcipher_ctx *cc;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey;
int r;
if ((newkey = ssh->state->newkeys[mode]) == NULL)
return SSH_ERR_INTERNAL_ERROR;
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
cc = (mode == MODE_OUT) ? ssh->state->send_context :
ssh->state->receive_context;
if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
return r;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
/* The cipher struct is constant and shared, you export pointer */
if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
(r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
(r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
(r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
(r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
(r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
(r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
goto out;
}
if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
(r = sshbuf_put_u32(b, comp->enabled)) != 0 ||
(r = sshbuf_put_cstring(b, comp->name)) != 0)
goto out;
r = sshbuf_put_stringb(m, b);
out:
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119 | newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b;
struct sshcipher_ctx *cc;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey;
int r;
if ((newkey = ssh->state->newkeys[mode]) == NULL)
return SSH_ERR_INTERNAL_ERROR;
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
cc = (mode == MODE_OUT) ? ssh->state->send_context :
ssh->state->receive_context;
if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
return r;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
/* The cipher struct is constant and shared, you export pointer */
if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
(r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
(r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
(r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
(r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
(r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
(r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
goto out;
}
if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
(r = sshbuf_put_cstring(b, comp->name)) != 0)
goto out;
r = sshbuf_put_stringb(m, b);
out:
sshbuf_free(b);
return r;
}
| 168,651 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int btif_hl_select_wake_reset(void){
char sig_recv = 0;
BTIF_TRACE_DEBUG("btif_hl_select_wake_reset");
recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL);
return(int)sig_recv;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static inline int btif_hl_select_wake_reset(void){
char sig_recv = 0;
BTIF_TRACE_DEBUG("btif_hl_select_wake_reset");
TEMP_FAILURE_RETRY(recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL));
return(int)sig_recv;
}
| 173,443 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int read_header_tga(gdIOCtx *ctx, oTga *tga)
{
unsigned char header[18];
if (gdGetBuf(header, sizeof(header), ctx) < 18) {
gd_error("fail to read header");
return -1;
}
tga->identsize = header[0];
tga->colormaptype = header[1];
tga->imagetype = header[2];
tga->colormapstart = header[3] + (header[4] << 8);
tga->colormaplength = header[5] + (header[6] << 8);
tga->colormapbits = header[7];
tga->xstart = header[8] + (header[9] << 8);
tga->ystart = header[10] + (header[11] << 8);
tga->width = header[12] + (header[13] << 8);
tga->height = header[14] + (header[15] << 8);
tga->bits = header[16];
tga->alphabits = header[17] & 0x0f;
tga->fliph = (header[17] & 0x10) ? 1 : 0;
tga->flipv = (header[17] & 0x20) ? 0 : 1;
#if DEBUG
printf("format bps: %i\n", tga->bits);
printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv);
printf("alpha: %i\n", tga->alphabits);
printf("wxh: %i %i\n", tga->width, tga->height);
#endif
switch(tga->bits) {
case 8:
case 16:
case 24:
case 32:
break;
default:
gd_error("bps %i not supported", tga->bits);
return -1;
break;
}
tga->ident = NULL;
if (tga->identsize > 0) {
tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char));
if(tga->ident == NULL) {
return -1;
}
gdGetBuf(tga->ident, tga->identsize, ctx);
}
return 1;
}
Commit Message: Unsupported TGA bpp/alphabit combinations should error gracefully
Currently, only 24bpp without alphabits and 32bpp with 8 alphabits are
really supported. All other combinations will be rejected with a warning.
CWE ID: CWE-125 | int read_header_tga(gdIOCtx *ctx, oTga *tga)
{
unsigned char header[18];
if (gdGetBuf(header, sizeof(header), ctx) < 18) {
gd_error("fail to read header");
return -1;
}
tga->identsize = header[0];
tga->colormaptype = header[1];
tga->imagetype = header[2];
tga->colormapstart = header[3] + (header[4] << 8);
tga->colormaplength = header[5] + (header[6] << 8);
tga->colormapbits = header[7];
tga->xstart = header[8] + (header[9] << 8);
tga->ystart = header[10] + (header[11] << 8);
tga->width = header[12] + (header[13] << 8);
tga->height = header[14] + (header[15] << 8);
tga->bits = header[16];
tga->alphabits = header[17] & 0x0f;
tga->fliph = (header[17] & 0x10) ? 1 : 0;
tga->flipv = (header[17] & 0x20) ? 0 : 1;
#if DEBUG
printf("format bps: %i\n", tga->bits);
printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv);
printf("alpha: %i\n", tga->alphabits);
printf("wxh: %i %i\n", tga->width, tga->height);
#endif
if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0)
|| (tga->bits == TGA_BPP_32 && tga->alphabits == 8)))
{
gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n",
tga->bits, tga->alphabits);
return -1;
}
tga->ident = NULL;
if (tga->identsize > 0) {
tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char));
if(tga->ident == NULL) {
return -1;
}
gdGetBuf(tga->ident, tga->identsize, ctx);
}
return 1;
}
| 167,005 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
int is_udp4;
bool slow;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len, addr_len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len, addr_len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_msg(skb, sizeof(struct udphdr),
msg, copied);
else {
err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
inet6_iif(skb));
}
*addr_len = sizeof(*sin6);
}
if (np->rxopt.all)
ip6_datagram_recv_common_ctl(sk, msg, skb);
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_specific_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
/* starting over for a new packet, but check if we need to yield */
cond_resched();
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
Commit Message: udp: properly support MSG_PEEK with truncated buffers
Backport of this upstream commit into stable kernels :
89c22d8c3b27 ("net: Fix skb csum races when peeking")
exposed a bug in udp stack vs MSG_PEEK support, when user provides
a buffer smaller than skb payload.
In this case,
skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov);
returns -EFAULT.
This bug does not happen in upstream kernels since Al Viro did a great
job to replace this into :
skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg);
This variant is safe vs short buffers.
For the time being, instead reverting Herbert Xu patch and add back
skb->ip_summed invalid changes, simply store the result of
udp_lib_checksum_complete() so that we avoid computing the checksum a
second time, and avoid the problematic
skb_copy_and_csum_datagram_iovec() call.
This patch can be applied on recent kernels as it avoids a double
checksumming, then backported to stable kernels as a bug fix.
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-358 | int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool checksum_valid = false;
int is_udp4;
bool slow;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len, addr_len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len, addr_len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
checksum_valid = !udp_lib_checksum_complete(skb);
if (!checksum_valid)
goto csum_copy_err;
}
if (checksum_valid || skb_csum_unnecessary(skb))
err = skb_copy_datagram_msg(skb, sizeof(struct udphdr),
msg, copied);
else {
err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
inet6_iif(skb));
}
*addr_len = sizeof(*sin6);
}
if (np->rxopt.all)
ip6_datagram_recv_common_ctl(sk, msg, skb);
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_specific_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
/* starting over for a new packet, but check if we need to yield */
cond_resched();
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
| 168,480 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void ThreadHeap::TakeSnapshot(SnapshotType type) {
DCHECK(thread_state_->InAtomicMarkingPause());
ThreadState::GCSnapshotInfo info(GCInfoTable::GcInfoIndex() + 1);
String thread_dump_name =
String::Format("blink_gc/thread_%lu",
static_cast<unsigned long>(thread_state_->ThreadId()));
const String heaps_dump_name = thread_dump_name + "/heaps";
const String classes_dump_name = thread_dump_name + "/classes";
int number_of_heaps_reported = 0;
#define SNAPSHOT_HEAP(ArenaType) \
{ \
number_of_heaps_reported++; \
switch (type) { \
case SnapshotType::kHeapSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeSnapshot( \
heaps_dump_name + "/" #ArenaType, info); \
break; \
case SnapshotType::kFreelistSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeFreelistSnapshot( \
heaps_dump_name + "/" #ArenaType); \
break; \
default: \
NOTREACHED(); \
} \
}
SNAPSHOT_HEAP(NormalPage1);
SNAPSHOT_HEAP(NormalPage2);
SNAPSHOT_HEAP(NormalPage3);
SNAPSHOT_HEAP(NormalPage4);
SNAPSHOT_HEAP(EagerSweep);
SNAPSHOT_HEAP(Vector1);
SNAPSHOT_HEAP(Vector2);
SNAPSHOT_HEAP(Vector3);
SNAPSHOT_HEAP(Vector4);
SNAPSHOT_HEAP(InlineVector);
SNAPSHOT_HEAP(HashTable);
SNAPSHOT_HEAP(LargeObject);
FOR_EACH_TYPED_ARENA(SNAPSHOT_HEAP);
DCHECK_EQ(number_of_heaps_reported, BlinkGC::kNumberOfArenas);
#undef SNAPSHOT_HEAP
if (type == SnapshotType::kFreelistSnapshot)
return;
size_t total_live_count = 0;
size_t total_dead_count = 0;
size_t total_live_size = 0;
size_t total_dead_size = 0;
for (size_t gc_info_index = 1; gc_info_index <= GCInfoTable::GcInfoIndex();
++gc_info_index) {
total_live_count += info.live_count[gc_info_index];
total_dead_count += info.dead_count[gc_info_index];
total_live_size += info.live_size[gc_info_index];
total_dead_size += info.dead_size[gc_info_index];
}
base::trace_event::MemoryAllocatorDump* thread_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(thread_dump_name);
thread_dump->AddScalar("live_count", "objects", total_live_count);
thread_dump->AddScalar("dead_count", "objects", total_dead_count);
thread_dump->AddScalar("live_size", "bytes", total_live_size);
thread_dump->AddScalar("dead_size", "bytes", total_dead_size);
base::trace_event::MemoryAllocatorDump* heaps_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(heaps_dump_name);
base::trace_event::MemoryAllocatorDump* classes_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(classes_dump_name);
BlinkGCMemoryDumpProvider::Instance()
->CurrentProcessMemoryDump()
->AddOwnershipEdge(classes_dump->guid(), heaps_dump->guid());
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560434}
CWE ID: CWE-362 | void ThreadHeap::TakeSnapshot(SnapshotType type) {
DCHECK(thread_state_->InAtomicMarkingPause());
ThreadState::GCSnapshotInfo info(GCInfoTable::Get().GcInfoIndex() + 1);
String thread_dump_name =
String::Format("blink_gc/thread_%lu",
static_cast<unsigned long>(thread_state_->ThreadId()));
const String heaps_dump_name = thread_dump_name + "/heaps";
const String classes_dump_name = thread_dump_name + "/classes";
int number_of_heaps_reported = 0;
#define SNAPSHOT_HEAP(ArenaType) \
{ \
number_of_heaps_reported++; \
switch (type) { \
case SnapshotType::kHeapSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeSnapshot( \
heaps_dump_name + "/" #ArenaType, info); \
break; \
case SnapshotType::kFreelistSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeFreelistSnapshot( \
heaps_dump_name + "/" #ArenaType); \
break; \
default: \
NOTREACHED(); \
} \
}
SNAPSHOT_HEAP(NormalPage1);
SNAPSHOT_HEAP(NormalPage2);
SNAPSHOT_HEAP(NormalPage3);
SNAPSHOT_HEAP(NormalPage4);
SNAPSHOT_HEAP(EagerSweep);
SNAPSHOT_HEAP(Vector1);
SNAPSHOT_HEAP(Vector2);
SNAPSHOT_HEAP(Vector3);
SNAPSHOT_HEAP(Vector4);
SNAPSHOT_HEAP(InlineVector);
SNAPSHOT_HEAP(HashTable);
SNAPSHOT_HEAP(LargeObject);
FOR_EACH_TYPED_ARENA(SNAPSHOT_HEAP);
DCHECK_EQ(number_of_heaps_reported, BlinkGC::kNumberOfArenas);
#undef SNAPSHOT_HEAP
if (type == SnapshotType::kFreelistSnapshot)
return;
size_t total_live_count = 0;
size_t total_dead_count = 0;
size_t total_live_size = 0;
size_t total_dead_size = 0;
for (size_t gc_info_index = 1;
gc_info_index <= GCInfoTable::Get().GcInfoIndex(); ++gc_info_index) {
total_live_count += info.live_count[gc_info_index];
total_dead_count += info.dead_count[gc_info_index];
total_live_size += info.live_size[gc_info_index];
total_dead_size += info.dead_size[gc_info_index];
}
base::trace_event::MemoryAllocatorDump* thread_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(thread_dump_name);
thread_dump->AddScalar("live_count", "objects", total_live_count);
thread_dump->AddScalar("dead_count", "objects", total_dead_count);
thread_dump->AddScalar("live_size", "bytes", total_live_size);
thread_dump->AddScalar("dead_size", "bytes", total_dead_size);
base::trace_event::MemoryAllocatorDump* heaps_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(heaps_dump_name);
base::trace_event::MemoryAllocatorDump* classes_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(classes_dump_name);
BlinkGCMemoryDumpProvider::Instance()
->CurrentProcessMemoryDump()
->AddOwnershipEdge(classes_dump->guid(), heaps_dump->guid());
}
| 173,137 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static inline signed int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,945 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void RunCallbacksWithDisabled(LogoCallbacks callbacks) {
if (callbacks.on_cached_encoded_logo_available) {
std::move(callbacks.on_cached_encoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_cached_decoded_logo_available) {
std::move(callbacks.on_cached_decoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_fresh_encoded_logo_available) {
std::move(callbacks.on_fresh_encoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_fresh_decoded_logo_available) {
std::move(callbacks.on_fresh_decoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119 | void RunCallbacksWithDisabled(LogoCallbacks callbacks) {
| 171,958 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: ScrollAnchor::ExamineResult ScrollAnchor::Examine(
const LayoutObject* candidate) const {
if (candidate == ScrollerLayoutBox(scroller_))
return ExamineResult(kContinue);
if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone)
return ExamineResult(kSkip);
if (candidate->IsLayoutInline())
return ExamineResult(kContinue);
if (candidate->IsAnonymous())
return ExamineResult(kContinue);
if (!candidate->IsText() && !candidate->IsBox())
return ExamineResult(kSkip);
if (!CandidateMayMoveWithScroller(candidate, scroller_))
return ExamineResult(kSkip);
LayoutRect candidate_rect = RelativeBounds(candidate, scroller_);
LayoutRect visible_rect =
ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint());
bool occupies_space =
candidate_rect.Width() > 0 && candidate_rect.Height() > 0;
if (occupies_space && visible_rect.Intersects(candidate_rect)) {
return ExamineResult(
visible_rect.Contains(candidate_rect) ? kReturn : kConstrain,
CornerToAnchor(scroller_));
} else {
return ExamineResult(kSkip);
}
}
Commit Message: Consider scroll-padding when determining scroll anchor node
Scroll anchoring should not anchor to a node that is behind scroll
padding.
Bug: 1010002
Change-Id: Icbd89fb85ea2c97a6de635930a9896f6a87b8f07
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1887745
Reviewed-by: Chris Harrelson <[email protected]>
Commit-Queue: Nick Burris <[email protected]>
Cr-Commit-Position: refs/heads/master@{#711020}
CWE ID: | ScrollAnchor::ExamineResult ScrollAnchor::Examine(
const LayoutObject* candidate) const {
if (candidate == ScrollerLayoutBox(scroller_))
return ExamineResult(kContinue);
if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone)
return ExamineResult(kSkip);
if (candidate->IsLayoutInline())
return ExamineResult(kContinue);
if (candidate->IsAnonymous())
return ExamineResult(kContinue);
if (!candidate->IsText() && !candidate->IsBox())
return ExamineResult(kSkip);
if (!CandidateMayMoveWithScroller(candidate, scroller_))
return ExamineResult(kSkip);
LayoutRect candidate_rect = RelativeBounds(candidate, scroller_);
LayoutRect visible_rect =
ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint());
const ComputedStyle* style = ScrollerLayoutBox(scroller_)->Style();
LayoutRectOutsets scroll_padding(
MinimumValueForLength(style->ScrollPaddingTop(), visible_rect.Height()),
MinimumValueForLength(style->ScrollPaddingRight(), visible_rect.Width()),
MinimumValueForLength(style->ScrollPaddingBottom(),
visible_rect.Height()),
MinimumValueForLength(style->ScrollPaddingLeft(), visible_rect.Width()));
visible_rect.Contract(scroll_padding);
bool occupies_space =
candidate_rect.Width() > 0 && candidate_rect.Height() > 0;
if (occupies_space && visible_rect.Intersects(candidate_rect)) {
return ExamineResult(
visible_rect.Contains(candidate_rect) ? kReturn : kConstrain,
CornerToAnchor(scroller_));
} else {
return ExamineResult(kSkip);
}
}
| 172,383 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void _xml_unparsedEntityDeclHandler(void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName)
{
xml_parser *parser = (xml_parser *)userData;
if (parser && parser->unparsedEntityDeclHandler) {
zval *retval, *args[6];
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding);
args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding);
args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding);
args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding);
args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) {
zval_ptr_dtor(&retval);
}
}
}
Commit Message:
CWE ID: CWE-119 | void _xml_unparsedEntityDeclHandler(void *userData,
void _xml_unparsedEntityDeclHandler(void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName)
{
xml_parser *parser = (xml_parser *)userData;
if (parser && parser->unparsedEntityDeclHandler) {
zval *retval, *args[6];
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding);
args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding);
args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding);
args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding);
args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) {
zval_ptr_dtor(&retval);
}
}
}
| 165,043 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void file_sb_list_add(struct file *file, struct super_block *sb)
{
if (likely(!(file->f_mode & FMODE_WRITE)))
return;
if (!S_ISREG(file_inode(file)->i_mode))
return;
lg_local_lock(&files_lglock);
__file_sb_list_add(file, sb);
lg_local_unlock(&files_lglock);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | void file_sb_list_add(struct file *file, struct super_block *sb)
| 166,798 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: tt_size_reset( TT_Size size,
FT_Bool only_height )
{
TT_Face face;
FT_Size_Metrics* metrics;
size->ttmetrics.valid = FALSE;
face = (TT_Face)size->root.face;
metrics = &size->metrics;
/* copy the result from base layer */
/* This bit flag, if set, indicates that the ppems must be */
/* rounded to integers. Nearly all TrueType fonts have this bit */
/* set, as hinting won't work really well otherwise. */
/* */
if ( face->header.Flags & 8 )
{
metrics->ascender =
FT_PIX_ROUND( FT_MulFix( face->root.ascender, metrics->y_scale ) );
metrics->descender =
FT_PIX_ROUND( FT_MulFix( face->root.descender, metrics->y_scale ) );
metrics->height =
FT_PIX_ROUND( FT_MulFix( face->root.height, metrics->y_scale ) );
}
size->ttmetrics.valid = TRUE;
if ( only_height )
return FT_Err_Ok;
if ( face->header.Flags & 8 )
{
metrics->x_scale = FT_DivFix( metrics->x_ppem << 6,
face->root.units_per_EM );
metrics->y_scale = FT_DivFix( metrics->y_ppem << 6,
face->root.units_per_EM );
metrics->max_advance =
FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width,
metrics->x_scale ) );
}
/* compute new transformation */
if ( metrics->x_ppem >= metrics->y_ppem )
{
size->ttmetrics.scale = metrics->x_scale;
size->ttmetrics.ppem = metrics->x_ppem;
size->ttmetrics.x_ratio = 0x10000L;
size->ttmetrics.y_ratio = FT_DivFix( metrics->y_ppem,
metrics->x_ppem );
}
else
{
size->ttmetrics.scale = metrics->y_scale;
size->ttmetrics.ppem = metrics->y_ppem;
size->ttmetrics.x_ratio = FT_DivFix( metrics->x_ppem,
metrics->y_ppem );
size->ttmetrics.y_ratio = 0x10000L;
}
#ifdef TT_USE_BYTECODE_INTERPRETER
size->cvt_ready = -1;
#endif /* TT_USE_BYTECODE_INTERPRETER */
return FT_Err_Ok;
}
Commit Message:
CWE ID: CWE-787 | tt_size_reset( TT_Size size,
FT_Bool only_height )
{
TT_Face face;
FT_Size_Metrics* metrics;
face = (TT_Face)size->root.face;
/* nothing to do for CFF2 */
if ( face->isCFF2 )
return FT_Err_Ok;
size->ttmetrics.valid = FALSE;
metrics = &size->metrics;
/* copy the result from base layer */
/* This bit flag, if set, indicates that the ppems must be */
/* rounded to integers. Nearly all TrueType fonts have this bit */
/* set, as hinting won't work really well otherwise. */
/* */
if ( face->header.Flags & 8 )
{
metrics->ascender =
FT_PIX_ROUND( FT_MulFix( face->root.ascender, metrics->y_scale ) );
metrics->descender =
FT_PIX_ROUND( FT_MulFix( face->root.descender, metrics->y_scale ) );
metrics->height =
FT_PIX_ROUND( FT_MulFix( face->root.height, metrics->y_scale ) );
}
size->ttmetrics.valid = TRUE;
if ( only_height )
return FT_Err_Ok;
if ( face->header.Flags & 8 )
{
metrics->x_scale = FT_DivFix( metrics->x_ppem << 6,
face->root.units_per_EM );
metrics->y_scale = FT_DivFix( metrics->y_ppem << 6,
face->root.units_per_EM );
metrics->max_advance =
FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width,
metrics->x_scale ) );
}
/* compute new transformation */
if ( metrics->x_ppem >= metrics->y_ppem )
{
size->ttmetrics.scale = metrics->x_scale;
size->ttmetrics.ppem = metrics->x_ppem;
size->ttmetrics.x_ratio = 0x10000L;
size->ttmetrics.y_ratio = FT_DivFix( metrics->y_ppem,
metrics->x_ppem );
}
else
{
size->ttmetrics.scale = metrics->y_scale;
size->ttmetrics.ppem = metrics->y_ppem;
size->ttmetrics.x_ratio = FT_DivFix( metrics->x_ppem,
metrics->y_ppem );
size->ttmetrics.y_ratio = 0x10000L;
}
#ifdef TT_USE_BYTECODE_INTERPRETER
size->cvt_ready = -1;
#endif /* TT_USE_BYTECODE_INTERPRETER */
return FT_Err_Ok;
}
| 164,887 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,
rpmpsm psm, char ** failedFile)
{
FD_t payload = rpmtePayload(te);
rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE);
rpmfs fs = rpmteGetFileStates(te);
rpmPlugins plugins = rpmtsPlugins(ts);
struct stat sb;
int saveerrno = errno;
int rc = 0;
int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0;
int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0;
int firsthardlink = -1;
int skip;
rpmFileAction action;
char *tid = NULL;
const char *suffix;
char *fpath = NULL;
if (fi == NULL) {
rc = RPMERR_BAD_MAGIC;
goto exit;
}
/* transaction id used for temporary path suffix while installing */
rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts));
/* Detect and create directories not explicitly in package. */
rc = fsmMkdirs(files, fs, plugins);
while (!rc) {
/* Read next payload header. */
rc = rpmfiNext(fi);
if (rc < 0) {
if (rc == RPMERR_ITER_END)
rc = 0;
break;
}
action = rpmfsGetAction(fs, rpmfiFX(fi));
skip = XFA_SKIPPING(action);
suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid;
if (action != FA_TOUCH) {
fpath = fsmFsPath(fi, suffix);
} else {
fpath = fsmFsPath(fi, "");
}
/* Remap file perms, owner, and group. */
rc = rpmfiStat(fi, 1, &sb);
fsmDebug(fpath, action, &sb);
/* Exit on error. */
if (rc)
break;
/* Run fsm file pre hook for all plugins */
rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath,
sb.st_mode, action);
if (rc) {
skip = 1;
} else {
setFileState(fs, rpmfiFX(fi));
}
if (!skip) {
int setmeta = 1;
/* Directories replacing something need early backup */
if (!suffix) {
rc = fsmBackup(fi, action);
}
/* Assume file does't exist when tmp suffix is in use */
if (!suffix) {
rc = fsmVerify(fpath, fi);
} else {
rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT;
}
if (S_ISREG(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmMkfile(fi, fpath, files, psm, nodigest,
&setmeta, &firsthardlink);
}
} else if (S_ISDIR(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
mode_t mode = sb.st_mode;
mode &= ~07777;
mode |= 00700;
rc = fsmMkdir(fpath, mode);
}
} else if (S_ISLNK(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmSymlink(rpmfiFLink(fi), fpath);
}
} else if (S_ISFIFO(sb.st_mode)) {
/* This mimics cpio S_ISSOCK() behavior but probably isn't right */
if (rc == RPMERR_ENOENT) {
rc = fsmMkfifo(fpath, 0000);
}
} else if (S_ISCHR(sb.st_mode) ||
S_ISBLK(sb.st_mode) ||
S_ISSOCK(sb.st_mode))
{
if (rc == RPMERR_ENOENT) {
rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev);
}
} else {
/* XXX Special case /dev/log, which shouldn't be packaged anyways */
if (!IS_DEV_LOG(fpath))
rc = RPMERR_UNKNOWN_FILETYPE;
}
/* Set permissions, timestamps etc for non-hardlink entries */
if (!rc && setmeta) {
rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps);
}
} else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) {
/* we skip the hard linked file containing the content */
/* write the content to the first used instead */
char *fn = rpmfilesFN(files, firsthardlink);
rc = expandRegular(fi, fn, psm, nodigest, 0);
firsthardlink = -1;
free(fn);
}
if (rc) {
if (!skip) {
/* XXX only erase if temp fn w suffix is in use */
if (suffix && (action != FA_TOUCH)) {
(void) fsmRemove(fpath, sb.st_mode);
}
errno = saveerrno;
}
} else {
/* Notify on success. */
rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi));
if (!skip) {
/* Backup file if needed. Directories are handled earlier */
if (suffix)
rc = fsmBackup(fi, action);
if (!rc)
rc = fsmCommit(&fpath, fi, action, suffix);
}
}
if (rc)
*failedFile = xstrdup(fpath);
/* Run fsm file post hook for all plugins */
rpmpluginsCallFsmFilePost(plugins, fi, fpath,
sb.st_mode, action, rc);
fpath = _free(fpath);
}
rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ));
rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST));
exit:
/* No need to bother with close errors on read */
rpmfiArchiveClose(fi);
rpmfiFree(fi);
Fclose(payload);
free(tid);
free(fpath);
return rc;
}
Commit Message: Don't follow symlinks on file creation (CVE-2017-7501)
Open newly created files with O_EXCL to prevent symlink tricks.
When reopening hardlinks for writing the actual content, use append
mode instead. This is compatible with the write-only permissions but
is not destructive in case we got redirected to somebody elses file,
verify the target before actually writing anything.
As these are files with the temporary suffix, errors mean a local
user with sufficient privileges to break the installation of the package
anyway is trying to goof us on purpose, don't bother trying to mend it
(we couldn't fix the hardlink case anyhow) but just bail out.
Based on a patch by Florian Festi.
CWE ID: CWE-59 | int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,
rpmpsm psm, char ** failedFile)
{
FD_t payload = rpmtePayload(te);
rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE);
rpmfs fs = rpmteGetFileStates(te);
rpmPlugins plugins = rpmtsPlugins(ts);
struct stat sb;
int saveerrno = errno;
int rc = 0;
int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0;
int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0;
int firsthardlink = -1;
int skip;
rpmFileAction action;
char *tid = NULL;
const char *suffix;
char *fpath = NULL;
if (fi == NULL) {
rc = RPMERR_BAD_MAGIC;
goto exit;
}
/* transaction id used for temporary path suffix while installing */
rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts));
/* Detect and create directories not explicitly in package. */
rc = fsmMkdirs(files, fs, plugins);
while (!rc) {
/* Read next payload header. */
rc = rpmfiNext(fi);
if (rc < 0) {
if (rc == RPMERR_ITER_END)
rc = 0;
break;
}
action = rpmfsGetAction(fs, rpmfiFX(fi));
skip = XFA_SKIPPING(action);
suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid;
if (action != FA_TOUCH) {
fpath = fsmFsPath(fi, suffix);
} else {
fpath = fsmFsPath(fi, "");
}
/* Remap file perms, owner, and group. */
rc = rpmfiStat(fi, 1, &sb);
fsmDebug(fpath, action, &sb);
/* Exit on error. */
if (rc)
break;
/* Run fsm file pre hook for all plugins */
rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath,
sb.st_mode, action);
if (rc) {
skip = 1;
} else {
setFileState(fs, rpmfiFX(fi));
}
if (!skip) {
int setmeta = 1;
/* Directories replacing something need early backup */
if (!suffix) {
rc = fsmBackup(fi, action);
}
/* Assume file does't exist when tmp suffix is in use */
if (!suffix) {
rc = fsmVerify(fpath, fi);
} else {
rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT;
}
if (S_ISREG(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmMkfile(fi, fpath, files, psm, nodigest,
&setmeta, &firsthardlink);
}
} else if (S_ISDIR(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
mode_t mode = sb.st_mode;
mode &= ~07777;
mode |= 00700;
rc = fsmMkdir(fpath, mode);
}
} else if (S_ISLNK(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmSymlink(rpmfiFLink(fi), fpath);
}
} else if (S_ISFIFO(sb.st_mode)) {
/* This mimics cpio S_ISSOCK() behavior but probably isn't right */
if (rc == RPMERR_ENOENT) {
rc = fsmMkfifo(fpath, 0000);
}
} else if (S_ISCHR(sb.st_mode) ||
S_ISBLK(sb.st_mode) ||
S_ISSOCK(sb.st_mode))
{
if (rc == RPMERR_ENOENT) {
rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev);
}
} else {
/* XXX Special case /dev/log, which shouldn't be packaged anyways */
if (!IS_DEV_LOG(fpath))
rc = RPMERR_UNKNOWN_FILETYPE;
}
/* Set permissions, timestamps etc for non-hardlink entries */
if (!rc && setmeta) {
rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps);
}
} else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) {
/* we skip the hard linked file containing the content */
/* write the content to the first used instead */
char *fn = rpmfilesFN(files, firsthardlink);
rc = expandRegular(fi, fn, psm, 0, nodigest, 0);
firsthardlink = -1;
free(fn);
}
if (rc) {
if (!skip) {
/* XXX only erase if temp fn w suffix is in use */
if (suffix && (action != FA_TOUCH)) {
(void) fsmRemove(fpath, sb.st_mode);
}
errno = saveerrno;
}
} else {
/* Notify on success. */
rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi));
if (!skip) {
/* Backup file if needed. Directories are handled earlier */
if (suffix)
rc = fsmBackup(fi, action);
if (!rc)
rc = fsmCommit(&fpath, fi, action, suffix);
}
}
if (rc)
*failedFile = xstrdup(fpath);
/* Run fsm file post hook for all plugins */
rpmpluginsCallFsmFilePost(plugins, fi, fpath,
sb.st_mode, action, rc);
fpath = _free(fpath);
}
rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ));
rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST));
exit:
/* No need to bother with close errors on read */
rpmfiArchiveClose(fi);
rpmfiFree(fi);
Fclose(payload);
free(tid);
free(fpath);
return rc;
}
| 168,269 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static void a2dp_open_ctrl_path(struct a2dp_stream_common *common)
{
int i;
/* retry logic to catch any timing variations on control channel */
for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++)
{
/* connect control channel if not already connected */
if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0)
{
/* success, now check if stack is ready */
if (check_a2dp_ready(common) == 0)
break;
ERROR("error : a2dp not ready, wait 250 ms and retry");
usleep(250000);
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
}
/* ctrl channel not ready, wait a bit */
usleep(250000);
}
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static void a2dp_open_ctrl_path(struct a2dp_stream_common *common)
{
int i;
/* retry logic to catch any timing variations on control channel */
for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++)
{
/* connect control channel if not already connected */
if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0)
{
/* success, now check if stack is ready */
if (check_a2dp_ready(common) == 0)
break;
ERROR("error : a2dp not ready, wait 250 ms and retry");
TEMP_FAILURE_RETRY(usleep(250000));
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
}
/* ctrl channel not ready, wait a bit */
TEMP_FAILURE_RETRY(usleep(250000));
}
}
| 173,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. Remember, I want response with just the fixed code only, No explanation. | Code: ldp_pdu_print(netdissect_options *ndo,
register const u_char *pptr)
{
const struct ldp_common_header *ldp_com_header;
const struct ldp_msg_header *ldp_msg_header;
const u_char *tptr,*msg_tptr;
u_short tlen;
u_short pdu_len,msg_len,msg_type,msg_tlen;
int hexdump,processed;
ldp_com_header = (const struct ldp_common_header *)pptr;
ND_TCHECK(*ldp_com_header);
/*
* Sanity checking of the header.
*/
if (EXTRACT_16BITS(&ldp_com_header->version) != LDP_VERSION) {
ND_PRINT((ndo, "%sLDP version %u packet not supported",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
EXTRACT_16BITS(&ldp_com_header->version)));
return 0;
}
pdu_len = EXTRACT_16BITS(&ldp_com_header->pdu_length);
if (pdu_len < sizeof(const struct ldp_common_header)-4) {
/* length too short */
ND_PRINT((ndo, "%sLDP, pdu-length: %u (too short, < %u)",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
pdu_len,
(u_int)(sizeof(const struct ldp_common_header)-4)));
return 0;
}
/* print the LSR-ID, label-space & length */
ND_PRINT((ndo, "%sLDP, Label-Space-ID: %s:%u, pdu-length: %u",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
ipaddr_string(ndo, &ldp_com_header->lsr_id),
EXTRACT_16BITS(&ldp_com_header->label_space),
pdu_len));
/* bail out if non-verbose */
if (ndo->ndo_vflag < 1)
return 0;
/* ok they seem to want to know everything - lets fully decode it */
tptr = pptr + sizeof(const struct ldp_common_header);
tlen = pdu_len - (sizeof(const struct ldp_common_header)-4); /* Type & Length fields not included */
while(tlen>0) {
/* did we capture enough for fully decoding the msg header ? */
ND_TCHECK2(*tptr, sizeof(struct ldp_msg_header));
ldp_msg_header = (const struct ldp_msg_header *)tptr;
msg_len=EXTRACT_16BITS(ldp_msg_header->length);
msg_type=LDP_MASK_MSG_TYPE(EXTRACT_16BITS(ldp_msg_header->type));
if (msg_len < sizeof(struct ldp_msg_header)-4) {
/* length too short */
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u (too short, < %u)",
tok2str(ldp_msg_values,
"Unknown",
msg_type),
msg_type,
msg_len,
(u_int)(sizeof(struct ldp_msg_header)-4)));
return 0;
}
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u, Message ID: 0x%08x, Flags: [%s if unknown]",
tok2str(ldp_msg_values,
"Unknown",
msg_type),
msg_type,
msg_len,
EXTRACT_32BITS(&ldp_msg_header->id),
LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_msg_header->type)) ? "continue processing" : "ignore"));
msg_tptr=tptr+sizeof(struct ldp_msg_header);
msg_tlen=msg_len-(sizeof(struct ldp_msg_header)-4); /* Type & Length fields not included */
/* did we capture enough for fully decoding the message ? */
ND_TCHECK2(*tptr, msg_len);
hexdump=FALSE;
switch(msg_type) {
case LDP_MSG_NOTIF:
case LDP_MSG_HELLO:
case LDP_MSG_INIT:
case LDP_MSG_KEEPALIVE:
case LDP_MSG_ADDRESS:
case LDP_MSG_LABEL_MAPPING:
case LDP_MSG_ADDRESS_WITHDRAW:
case LDP_MSG_LABEL_WITHDRAW:
while(msg_tlen >= 4) {
processed = ldp_tlv_print(ndo, msg_tptr, msg_tlen);
if (processed == 0)
break;
msg_tlen-=processed;
msg_tptr+=processed;
}
break;
/*
* FIXME those are the defined messages that lack a decoder
* you are welcome to contribute code ;-)
*/
case LDP_MSG_LABEL_REQUEST:
case LDP_MSG_LABEL_RELEASE:
case LDP_MSG_LABEL_ABORT_REQUEST:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, msg_tptr, "\n\t ", msg_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo, tptr+sizeof(struct ldp_msg_header), "\n\t ",
msg_len);
tptr += msg_len+4;
tlen -= msg_len+4;
}
return pdu_len+4;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
return 0;
}
Commit Message: (for 4.9.3) CVE-2018-14461/LDP: Fix a bounds check
In ldp_tlv_print(), the FT Session TLV length must be 12, not 8 (RFC3479)
This fixes a buffer over-read discovered by Konrad Rieck and
Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).
Moreover:
Add and use tstr[].
Add a comment.
CWE ID: CWE-125 | ldp_pdu_print(netdissect_options *ndo,
register const u_char *pptr)
{
const struct ldp_common_header *ldp_com_header;
const struct ldp_msg_header *ldp_msg_header;
const u_char *tptr,*msg_tptr;
u_short tlen;
u_short pdu_len,msg_len,msg_type,msg_tlen;
int hexdump,processed;
ldp_com_header = (const struct ldp_common_header *)pptr;
ND_TCHECK(*ldp_com_header);
/*
* Sanity checking of the header.
*/
if (EXTRACT_16BITS(&ldp_com_header->version) != LDP_VERSION) {
ND_PRINT((ndo, "%sLDP version %u packet not supported",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
EXTRACT_16BITS(&ldp_com_header->version)));
return 0;
}
pdu_len = EXTRACT_16BITS(&ldp_com_header->pdu_length);
if (pdu_len < sizeof(const struct ldp_common_header)-4) {
/* length too short */
ND_PRINT((ndo, "%sLDP, pdu-length: %u (too short, < %u)",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
pdu_len,
(u_int)(sizeof(const struct ldp_common_header)-4)));
return 0;
}
/* print the LSR-ID, label-space & length */
ND_PRINT((ndo, "%sLDP, Label-Space-ID: %s:%u, pdu-length: %u",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
ipaddr_string(ndo, &ldp_com_header->lsr_id),
EXTRACT_16BITS(&ldp_com_header->label_space),
pdu_len));
/* bail out if non-verbose */
if (ndo->ndo_vflag < 1)
return 0;
/* ok they seem to want to know everything - lets fully decode it */
tptr = pptr + sizeof(const struct ldp_common_header);
tlen = pdu_len - (sizeof(const struct ldp_common_header)-4); /* Type & Length fields not included */
while(tlen>0) {
/* did we capture enough for fully decoding the msg header ? */
ND_TCHECK2(*tptr, sizeof(struct ldp_msg_header));
ldp_msg_header = (const struct ldp_msg_header *)tptr;
msg_len=EXTRACT_16BITS(ldp_msg_header->length);
msg_type=LDP_MASK_MSG_TYPE(EXTRACT_16BITS(ldp_msg_header->type));
if (msg_len < sizeof(struct ldp_msg_header)-4) {
/* length too short */
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u (too short, < %u)",
tok2str(ldp_msg_values,
"Unknown",
msg_type),
msg_type,
msg_len,
(u_int)(sizeof(struct ldp_msg_header)-4)));
return 0;
}
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u, Message ID: 0x%08x, Flags: [%s if unknown]",
tok2str(ldp_msg_values,
"Unknown",
msg_type),
msg_type,
msg_len,
EXTRACT_32BITS(&ldp_msg_header->id),
LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_msg_header->type)) ? "continue processing" : "ignore"));
msg_tptr=tptr+sizeof(struct ldp_msg_header);
msg_tlen=msg_len-(sizeof(struct ldp_msg_header)-4); /* Type & Length fields not included */
/* did we capture enough for fully decoding the message ? */
ND_TCHECK2(*tptr, msg_len);
hexdump=FALSE;
switch(msg_type) {
case LDP_MSG_NOTIF:
case LDP_MSG_HELLO:
case LDP_MSG_INIT:
case LDP_MSG_KEEPALIVE:
case LDP_MSG_ADDRESS:
case LDP_MSG_LABEL_MAPPING:
case LDP_MSG_ADDRESS_WITHDRAW:
case LDP_MSG_LABEL_WITHDRAW:
while(msg_tlen >= 4) {
processed = ldp_tlv_print(ndo, msg_tptr, msg_tlen);
if (processed == 0)
break;
msg_tlen-=processed;
msg_tptr+=processed;
}
break;
/*
* FIXME those are the defined messages that lack a decoder
* you are welcome to contribute code ;-)
*/
case LDP_MSG_LABEL_REQUEST:
case LDP_MSG_LABEL_RELEASE:
case LDP_MSG_LABEL_ABORT_REQUEST:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, msg_tptr, "\n\t ", msg_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo, tptr+sizeof(struct ldp_msg_header), "\n\t ",
msg_len);
tptr += msg_len+4;
tlen -= msg_len+4;
}
return pdu_len+4;
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
| 169,852 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static void re_yyensure_buffer_stack (yyscan_t yyscanner)
{
yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; // After all that talk, this was set to 1 anyways...
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
CWE ID: CWE-476 | static void re_yyensure_buffer_stack (yyscan_t yyscanner)
{
yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; // After all that talk, this was set to 1 anyways...
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
| 168,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. Remember, I want response with just the fixed code only, No explanation. | Code: CreateFileHelper(PassRefPtrWillBeRawPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
: m_result(result)
, m_name(name)
, m_url(url)
, m_type(type)
{
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | CreateFileHelper(PassRefPtrWillBeRawPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
CreateFileHelper(CreateFileResult* result, const String& name, const KURL& url, FileSystemType type)
: m_result(result)
, m_name(name)
, m_url(url)
, m_type(type)
{
}
| 171,412 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: open_log_file(const char *name, const char *prog, const char *namespace, const char *instance)
{
char *file_name;
if (log_file) {
fclose(log_file);
log_file = NULL;
}
if (!name)
return;
file_name = make_file_name(name, prog, namespace, instance);
log_file = fopen(file_name, "a");
if (log_file) {
int n = fileno(log_file);
fcntl(n, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD));
fcntl(n, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL));
}
FREE(file_name);
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | open_log_file(const char *name, const char *prog, const char *namespace, const char *instance)
{
char *file_name;
if (log_file) {
fclose(log_file);
log_file = NULL;
}
if (!name)
return;
file_name = make_file_name(name, prog, namespace, instance);
log_file = fopen_safe(file_name, "a");
if (log_file) {
int n = fileno(log_file);
fcntl(n, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD));
fcntl(n, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL));
}
FREE(file_name);
}
| 168,994 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_siocgstamp(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timeval ktv;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv);
set_fs(old_fs);
if (!err)
err = compat_put_timeval(up, &ktv);
return err;
}
Commit Message: Fix order of arguments to compat_put_time[spec|val]
Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in
net/socket.c") introduced a bug where the helper functions to take
either a 64-bit or compat time[spec|val] got the arguments in the wrong
order, passing the kernel stack pointer off as a user pointer (and vice
versa).
Because of the user address range check, that in turn then causes an
EFAULT due to the user pointer range checking failing for the kernel
address. Incorrectly resuling in a failed system call for 32-bit
processes with a 64-bit kernel.
On odder architectures like HP-PA (with separate user/kernel address
spaces), it can be used read kernel memory.
Signed-off-by: Mikulas Patocka <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399 | static int do_siocgstamp(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timeval ktv;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv);
set_fs(old_fs);
if (!err)
err = compat_put_timeval(&ktv, up);
return err;
}
| 165,536 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
sk_read_actor_t recv_actor)
{
struct sk_buff *skb;
struct tcp_sock *tp = tcp_sk(sk);
u32 seq = tp->copied_seq;
u32 offset;
int copied = 0;
if (sk->sk_state == TCP_LISTEN)
return -ENOTCONN;
while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
if (offset < skb->len) {
int used;
size_t len;
len = skb->len - offset;
/* Stop reading if we hit a patch of urgent data */
if (tp->urg_data) {
u32 urg_offset = tp->urg_seq - seq;
if (urg_offset < len)
len = urg_offset;
if (!len)
break;
}
used = recv_actor(desc, skb, offset, len);
if (used < 0) {
if (!copied)
copied = used;
break;
} else if (used <= len) {
seq += used;
copied += used;
offset += used;
}
/*
* If recv_actor drops the lock (e.g. TCP splice
* receive) the skb pointer might be invalid when
* getting here: tcp_collapse might have deleted it
* while aggregating skbs from the socket queue.
*/
skb = tcp_recv_skb(sk, seq-1, &offset);
if (!skb || (offset+1 != skb->len))
break;
}
if (tcp_hdr(skb)->fin) {
sk_eat_skb(sk, skb, 0);
++seq;
break;
}
sk_eat_skb(sk, skb, 0);
if (!desc->count)
break;
}
tp->copied_seq = seq;
tcp_rcv_space_adjust(sk);
/* Clean up data we have read: This will do ACK frames. */
if (copied > 0)
tcp_cleanup_rbuf(sk, copied);
return copied;
}
Commit Message: net: Fix oops from tcp_collapse() when using splice()
tcp_read_sock() can have a eat skbs without immediately advancing copied_seq.
This can cause a panic in tcp_collapse() if it is called as a result
of the recv_actor dropping the socket lock.
A userspace program that splices data from a socket to either another
socket or to a file can trigger this bug.
Signed-off-by: Steven J. Magnani <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
sk_read_actor_t recv_actor)
{
struct sk_buff *skb;
struct tcp_sock *tp = tcp_sk(sk);
u32 seq = tp->copied_seq;
u32 offset;
int copied = 0;
if (sk->sk_state == TCP_LISTEN)
return -ENOTCONN;
while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
if (offset < skb->len) {
int used;
size_t len;
len = skb->len - offset;
/* Stop reading if we hit a patch of urgent data */
if (tp->urg_data) {
u32 urg_offset = tp->urg_seq - seq;
if (urg_offset < len)
len = urg_offset;
if (!len)
break;
}
used = recv_actor(desc, skb, offset, len);
if (used < 0) {
if (!copied)
copied = used;
break;
} else if (used <= len) {
seq += used;
copied += used;
offset += used;
}
/*
* If recv_actor drops the lock (e.g. TCP splice
* receive) the skb pointer might be invalid when
* getting here: tcp_collapse might have deleted it
* while aggregating skbs from the socket queue.
*/
skb = tcp_recv_skb(sk, seq-1, &offset);
if (!skb || (offset+1 != skb->len))
break;
}
if (tcp_hdr(skb)->fin) {
sk_eat_skb(sk, skb, 0);
++seq;
break;
}
sk_eat_skb(sk, skb, 0);
if (!desc->count)
break;
tp->copied_seq = seq;
}
tp->copied_seq = seq;
tcp_rcv_space_adjust(sk);
/* Clean up data we have read: This will do ACK frames. */
if (copied > 0)
tcp_cleanup_rbuf(sk, copied);
return copied;
}
| 166,084 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void CreateAuthenticatorFactory() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
std::string local_certificate = key_pair_.GenerateCertificate();
if (local_certificate.empty()) {
LOG(ERROR) << "Failed to generate host certificate.";
Shutdown(kHostInitializationFailed);
return;
}
scoped_ptr<protocol::AuthenticatorFactory> factory(
new protocol::Me2MeHostAuthenticatorFactory(
local_certificate, *key_pair_.private_key(), host_secret_hash_));
host_->SetAuthenticatorFactory(factory.Pass());
}
Commit Message: Fix crash in CreateAuthenticatorFactory().
CreateAuthenticatorFactory() is called asynchronously, but it didn't handle
the case when it's called after host object is destroyed.
BUG=150644
Review URL: https://codereview.chromium.org/11090036
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161077 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void CreateAuthenticatorFactory() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
if (!host_ || shutting_down_)
return;
std::string local_certificate = key_pair_.GenerateCertificate();
if (local_certificate.empty()) {
LOG(ERROR) << "Failed to generate host certificate.";
Shutdown(kHostInitializationFailed);
return;
}
scoped_ptr<protocol::AuthenticatorFactory> factory(
new protocol::Me2MeHostAuthenticatorFactory(
local_certificate, *key_pair_.private_key(), host_secret_hash_));
host_->SetAuthenticatorFactory(factory.Pass());
}
| 171,338 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int lxc_mount_auto_mounts(struct lxc_conf *conf, int flags, struct lxc_handler *handler)
{
int r;
size_t i;
static struct {
int match_mask;
int match_flag;
const char *source;
const char *destination;
const char *fstype;
unsigned long flags;
const char *options;
} default_mounts[] = {
/* Read-only bind-mounting... In older kernels, doing that required
* to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same
* one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from
* kernel 2.6.26 onwards. However, this apparently does not work on
* kernel 3.8. Unfortunately, on that very same kernel, doing the
* same trick as above doesn't seem to work either, there one needs
* to ALSO specify MS_BIND for the remount, otherwise the entire
* fs is remounted read-only or the mount fails because it's busy...
* MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as
* 2.6.32...
*/
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys/net", "%r/proc/net", NULL, MS_BIND, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys", "%r/proc/sys", NULL, MS_BIND, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/net", "%r/proc/sys/net", NULL, MS_MOVE, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL, MS_BIND, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sysrq-trigger", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_RW, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RW, "sysfs", "%r/sys", "sysfs", 0, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RO, "sysfs", "%r/sys", "sysfs", MS_RDONLY, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys", "sysfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys", "%r/sys", NULL, MS_BIND, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys/devices/virtual/net/devices/virtual/net", "%r/sys/devices/virtual/net", NULL, MS_BIND, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys/devices/virtual/net", NULL, MS_REMOUNT|MS_BIND|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL },
{ 0, 0, NULL, NULL, NULL, 0, NULL }
};
for (i = 0; default_mounts[i].match_mask; i++) {
if ((flags & default_mounts[i].match_mask) == default_mounts[i].match_flag) {
char *source = NULL;
char *destination = NULL;
int saved_errno;
unsigned long mflags;
if (default_mounts[i].source) {
/* will act like strdup if %r is not present */
source = lxc_string_replace("%r", conf->rootfs.path ? conf->rootfs.mount : "", default_mounts[i].source);
if (!source) {
SYSERROR("memory allocation error");
return -1;
}
}
if (default_mounts[i].destination) {
/* will act like strdup if %r is not present */
destination = lxc_string_replace("%r", conf->rootfs.path ? conf->rootfs.mount : "", default_mounts[i].destination);
if (!destination) {
saved_errno = errno;
SYSERROR("memory allocation error");
free(source);
errno = saved_errno;
return -1;
}
}
mflags = add_required_remount_flags(source, destination,
default_mounts[i].flags);
r = mount(source, destination, default_mounts[i].fstype, mflags, default_mounts[i].options);
saved_errno = errno;
if (r < 0 && errno == ENOENT) {
INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source, destination);
r = 0;
}
else if (r < 0)
SYSERROR("error mounting %s on %s flags %lu", source, destination, mflags);
free(source);
free(destination);
if (r < 0) {
errno = saved_errno;
return -1;
}
}
}
if (flags & LXC_AUTO_CGROUP_MASK) {
int cg_flags;
cg_flags = flags & LXC_AUTO_CGROUP_MASK;
/* If the type of cgroup mount was not specified, it depends on the
* container's capabilities as to what makes sense: if we have
* CAP_SYS_ADMIN, the read-only part can be remounted read-write
* anyway, so we may as well default to read-write; then the admin
* will not be given a false sense of security. (And if they really
* want mixed r/o r/w, then they can explicitly specify :mixed.)
* OTOH, if the container lacks CAP_SYS_ADMIN, do only default to
* :mixed, because then the container can't remount it read-write. */
if (cg_flags == LXC_AUTO_CGROUP_NOSPEC || cg_flags == LXC_AUTO_CGROUP_FULL_NOSPEC) {
int has_sys_admin = 0;
if (!lxc_list_empty(&conf->keepcaps)) {
has_sys_admin = in_caplist(CAP_SYS_ADMIN, &conf->keepcaps);
} else {
has_sys_admin = !in_caplist(CAP_SYS_ADMIN, &conf->caps);
}
if (cg_flags == LXC_AUTO_CGROUP_NOSPEC) {
cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_RW : LXC_AUTO_CGROUP_MIXED;
} else {
cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_FULL_RW : LXC_AUTO_CGROUP_FULL_MIXED;
}
}
if (!cgroup_mount(conf->rootfs.path ? conf->rootfs.mount : "", handler, cg_flags)) {
SYSERROR("error mounting /sys/fs/cgroup");
return -1;
}
}
return 0;
}
Commit Message: CVE-2015-1335: Protect container mounts against symlinks
When a container starts up, lxc sets up the container's inital fstree
by doing a bunch of mounting, guided by the container configuration
file. The container config is owned by the admin or user on the host,
so we do not try to guard against bad entries. However, since the
mount target is in the container, it's possible that the container admin
could divert the mount with symbolic links. This could bypass proper
container startup (i.e. confinement of a root-owned container by the
restrictive apparmor policy, by diverting the required write to
/proc/self/attr/current), or bypass the (path-based) apparmor policy
by diverting, say, /proc to /mnt in the container.
To prevent this,
1. do not allow mounts to paths containing symbolic links
2. do not allow bind mounts from relative paths containing symbolic
links.
Details:
Define safe_mount which ensures that the container has not inserted any
symbolic links into any mount targets for mounts to be done during
container setup.
The host's mount path may contain symbolic links. As it is under the
control of the administrator, that's ok. So safe_mount begins the check
for symbolic links after the rootfs->mount, by opening that directory.
It opens each directory along the path using openat() relative to the
parent directory using O_NOFOLLOW. When the target is reached, it
mounts onto /proc/self/fd/<targetfd>.
Use safe_mount() in mount_entry(), when mounting container proc,
and when needed. In particular, safe_mount() need not be used in
any case where:
1. the mount is done in the container's namespace
2. the mount is for the container's rootfs
3. the mount is relative to a tmpfs or proc/sysfs which we have
just safe_mount()ed ourselves
Since we were using proc/net as a temporary placeholder for /proc/sys/net
during container startup, and proc/net is a symbolic link, use proc/tty
instead.
Update the lxc.container.conf manpage with details about the new
restrictions.
Finally, add a testcase to test some symbolic link possibilities.
Reported-by: Roman Fiedler
Signed-off-by: Serge Hallyn <[email protected]>
Acked-by: Stéphane Graber <[email protected]>
CWE ID: CWE-59 | static int lxc_mount_auto_mounts(struct lxc_conf *conf, int flags, struct lxc_handler *handler)
{
int r;
size_t i;
static struct {
int match_mask;
int match_flag;
const char *source;
const char *destination;
const char *fstype;
unsigned long flags;
const char *options;
} default_mounts[] = {
/* Read-only bind-mounting... In older kernels, doing that required
* to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same
* one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from
* kernel 2.6.26 onwards. However, this apparently does not work on
* kernel 3.8. Unfortunately, on that very same kernel, doing the
* same trick as above doesn't seem to work either, there one needs
* to ALSO specify MS_BIND for the remount, otherwise the entire
* fs is remounted read-only or the mount fails because it's busy...
* MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as
* 2.6.32...
*/
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
/* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys/net", "%r/proc/tty", NULL, MS_BIND, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys", "%r/proc/sys", NULL, MS_BIND, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/tty", "%r/proc/sys/net", NULL, MS_MOVE, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL, MS_BIND, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sysrq-trigger", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
{ LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_RW, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RW, "sysfs", "%r/sys", "sysfs", 0, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RO, "sysfs", "%r/sys", "sysfs", MS_RDONLY, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys", "sysfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys", "%r/sys", NULL, MS_BIND, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys/devices/virtual/net/devices/virtual/net", "%r/sys/devices/virtual/net", NULL, MS_BIND, NULL },
{ LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys/devices/virtual/net", NULL, MS_REMOUNT|MS_BIND|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL },
{ 0, 0, NULL, NULL, NULL, 0, NULL }
};
for (i = 0; default_mounts[i].match_mask; i++) {
if ((flags & default_mounts[i].match_mask) == default_mounts[i].match_flag) {
char *source = NULL;
char *destination = NULL;
int saved_errno;
unsigned long mflags;
if (default_mounts[i].source) {
/* will act like strdup if %r is not present */
source = lxc_string_replace("%r", conf->rootfs.path ? conf->rootfs.mount : "", default_mounts[i].source);
if (!source) {
SYSERROR("memory allocation error");
return -1;
}
}
if (default_mounts[i].destination) {
/* will act like strdup if %r is not present */
destination = lxc_string_replace("%r", conf->rootfs.path ? conf->rootfs.mount : "", default_mounts[i].destination);
if (!destination) {
saved_errno = errno;
SYSERROR("memory allocation error");
free(source);
errno = saved_errno;
return -1;
}
}
mflags = add_required_remount_flags(source, destination,
default_mounts[i].flags);
r = safe_mount(source, destination, default_mounts[i].fstype, mflags, default_mounts[i].options, conf->rootfs.path ? conf->rootfs.mount : NULL);
saved_errno = errno;
if (r < 0 && errno == ENOENT) {
INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source, destination);
r = 0;
}
else if (r < 0)
SYSERROR("error mounting %s on %s flags %lu", source, destination, mflags);
free(source);
free(destination);
if (r < 0) {
errno = saved_errno;
return -1;
}
}
}
if (flags & LXC_AUTO_CGROUP_MASK) {
int cg_flags;
cg_flags = flags & LXC_AUTO_CGROUP_MASK;
/* If the type of cgroup mount was not specified, it depends on the
* container's capabilities as to what makes sense: if we have
* CAP_SYS_ADMIN, the read-only part can be remounted read-write
* anyway, so we may as well default to read-write; then the admin
* will not be given a false sense of security. (And if they really
* want mixed r/o r/w, then they can explicitly specify :mixed.)
* OTOH, if the container lacks CAP_SYS_ADMIN, do only default to
* :mixed, because then the container can't remount it read-write. */
if (cg_flags == LXC_AUTO_CGROUP_NOSPEC || cg_flags == LXC_AUTO_CGROUP_FULL_NOSPEC) {
int has_sys_admin = 0;
if (!lxc_list_empty(&conf->keepcaps)) {
has_sys_admin = in_caplist(CAP_SYS_ADMIN, &conf->keepcaps);
} else {
has_sys_admin = !in_caplist(CAP_SYS_ADMIN, &conf->caps);
}
if (cg_flags == LXC_AUTO_CGROUP_NOSPEC) {
cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_RW : LXC_AUTO_CGROUP_MIXED;
} else {
cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_FULL_RW : LXC_AUTO_CGROUP_FULL_MIXED;
}
}
if (!cgroup_mount(conf->rootfs.path ? conf->rootfs.mount : "", handler, cg_flags)) {
SYSERROR("error mounting /sys/fs/cgroup");
return -1;
}
}
return 0;
}
| 166,713 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return chromeos::GetKeyboardOverlayId(input_method_id);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return input_method::GetKeyboardOverlayId(input_method_id);
}
| 170,489 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void AutofillExternalDelegate::OnSuggestionsReturned(
int query_id,
const std::vector<Suggestion>& input_suggestions,
bool autoselect_first_suggestion,
bool is_all_server_suggestions) {
if (query_id != query_id_)
return;
std::vector<Suggestion> suggestions(input_suggestions);
PossiblyRemoveAutofillWarnings(&suggestions);
#if !defined(OS_ANDROID)
if (!suggestions.empty() && !features::ShouldUseNativeViews()) {
suggestions.push_back(Suggestion());
suggestions.back().frontend_id = POPUP_ITEM_ID_SEPARATOR;
}
#endif
if (should_show_scan_credit_card_) {
Suggestion scan_credit_card(
l10n_util::GetStringUTF16(IDS_AUTOFILL_SCAN_CREDIT_CARD));
scan_credit_card.frontend_id = POPUP_ITEM_ID_SCAN_CREDIT_CARD;
scan_credit_card.icon = base::ASCIIToUTF16("scanCreditCardIcon");
suggestions.push_back(scan_credit_card);
}
has_autofill_suggestions_ = false;
for (size_t i = 0; i < suggestions.size(); ++i) {
if (suggestions[i].frontend_id > 0) {
has_autofill_suggestions_ = true;
break;
}
}
if (should_show_cards_from_account_option_) {
suggestions.emplace_back(
l10n_util::GetStringUTF16(IDS_AUTOFILL_SHOW_ACCOUNT_CARDS));
suggestions.back().frontend_id = POPUP_ITEM_ID_SHOW_ACCOUNT_CARDS;
suggestions.back().icon = base::ASCIIToUTF16("google");
}
if (has_autofill_suggestions_)
ApplyAutofillOptions(&suggestions, is_all_server_suggestions);
if (suggestions.empty() && should_show_cc_signin_promo_) {
#if !defined(OS_ANDROID)
if (has_autofill_suggestions_) {
suggestions.push_back(Suggestion());
suggestions.back().frontend_id = POPUP_ITEM_ID_SEPARATOR;
}
#endif
Suggestion signin_promo_suggestion(
l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDIT_CARD_SIGNIN_PROMO));
signin_promo_suggestion.frontend_id =
POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO;
suggestions.push_back(signin_promo_suggestion);
signin_metrics::RecordSigninImpressionUserActionForAccessPoint(
signin_metrics::AccessPoint::ACCESS_POINT_AUTOFILL_DROPDOWN);
}
#if !defined(OS_ANDROID)
if (!suggestions.empty() &&
suggestions.back().frontend_id == POPUP_ITEM_ID_SEPARATOR) {
suggestions.pop_back();
}
#endif
InsertDataListValues(&suggestions);
if (suggestions.empty()) {
manager_->client()->HideAutofillPopup();
return;
}
if (query_field_.is_focusable) {
manager_->client()->ShowAutofillPopup(
element_bounds_, query_field_.text_direction, suggestions,
autoselect_first_suggestion, GetWeakPtr());
}
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <[email protected]>
Reviewed-by: Vasilii Sukhanov <[email protected]>
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Tommy Martino <[email protected]>
Commit-Queue: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416 | void AutofillExternalDelegate::OnSuggestionsReturned(
int query_id,
const std::vector<Suggestion>& input_suggestions,
bool autoselect_first_suggestion,
bool is_all_server_suggestions) {
if (query_id != query_id_)
return;
std::vector<Suggestion> suggestions(input_suggestions);
PossiblyRemoveAutofillWarnings(&suggestions);
if (should_show_scan_credit_card_) {
Suggestion scan_credit_card(
l10n_util::GetStringUTF16(IDS_AUTOFILL_SCAN_CREDIT_CARD));
scan_credit_card.frontend_id = POPUP_ITEM_ID_SCAN_CREDIT_CARD;
scan_credit_card.icon = base::ASCIIToUTF16("scanCreditCardIcon");
suggestions.push_back(scan_credit_card);
}
has_autofill_suggestions_ = false;
for (size_t i = 0; i < suggestions.size(); ++i) {
if (suggestions[i].frontend_id > 0) {
has_autofill_suggestions_ = true;
break;
}
}
if (should_show_cards_from_account_option_) {
suggestions.emplace_back(
l10n_util::GetStringUTF16(IDS_AUTOFILL_SHOW_ACCOUNT_CARDS));
suggestions.back().frontend_id = POPUP_ITEM_ID_SHOW_ACCOUNT_CARDS;
suggestions.back().icon = base::ASCIIToUTF16("google");
}
if (has_autofill_suggestions_)
ApplyAutofillOptions(&suggestions, is_all_server_suggestions);
if (suggestions.empty() && should_show_cc_signin_promo_) {
Suggestion signin_promo_suggestion(
l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDIT_CARD_SIGNIN_PROMO));
signin_promo_suggestion.frontend_id =
POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO;
suggestions.push_back(signin_promo_suggestion);
signin_metrics::RecordSigninImpressionUserActionForAccessPoint(
signin_metrics::AccessPoint::ACCESS_POINT_AUTOFILL_DROPDOWN);
}
InsertDataListValues(&suggestions);
if (suggestions.empty()) {
manager_->client()->HideAutofillPopup();
return;
}
if (query_field_.is_focusable) {
manager_->client()->ShowAutofillPopup(
element_bounds_, query_field_.text_direction, suggestions,
autoselect_first_suggestion, GetWeakPtr());
}
}
| 172,097 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void TIFF_MetaHandler::ProcessXMP()
{
this->processedXMP = true; // Make sure we only come through here once.
bool found;
bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0);
if ( readOnly ) {
this->psirMgr = new PSIR_MemoryReader();
this->iptcMgr = new IPTC_Reader();
} else {
this->psirMgr = new PSIR_FileWriter();
this->iptcMgr = new IPTC_Writer(); // ! Parse it later.
}
TIFF_Manager & tiff = this->tiffMgr; // Give the compiler help in recognizing non-aliases.
PSIR_Manager & psir = *this->psirMgr;
IPTC_Manager & iptc = *this->iptcMgr;
TIFF_Manager::TagInfo psirInfo;
bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo );
if ( havePSIR ) { // ! Do the Photoshop 6 integration before other legacy analysis.
psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen );
PSIR_Manager::ImgRsrcInfo buriedExif;
found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif );
if ( found ) {
tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen );
if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif );
}
}
TIFF_Manager::TagInfo iptcInfo;
bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); // The TIFF IPTC tag.
int iptcDigestState = kDigestMatches;
if ( haveIPTC ) {
bool haveDigest = false;
PSIR_Manager::ImgRsrcInfo digestInfo;
if ( havePSIR ) haveDigest = psir.GetImgRsrc ( kPSIR_IPTCDigest, &digestInfo );
if ( digestInfo.dataLen != 16 ) haveDigest = false;
if ( ! haveDigest ) {
iptcDigestState = kDigestMissing;
} else {
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, iptcInfo.dataLen, digestInfo.dataPtr );
if ( (iptcDigestState == kDigestDiffers) && (kTIFF_TypeSizes[iptcInfo.type] > 1) ) {
XMP_Uns8 * endPtr = (XMP_Uns8*)iptcInfo.dataPtr + iptcInfo.dataLen - 1;
XMP_Uns8 * minPtr = endPtr - kTIFF_TypeSizes[iptcInfo.type] + 1;
while ( (endPtr >= minPtr) && (*endPtr == 0) ) --endPtr;
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, unpaddedLen, digestInfo.dataPtr );
}
}
}
XMP_OptionBits options = k2XMP_FileHadExif; // TIFF files are presumed to have Exif legacy.
if ( haveIPTC ) options |= k2XMP_FileHadIPTC;
if ( this->containsXMP ) options |= k2XMP_FileHadXMP;
bool haveXMP = false;
if ( ! this->xmpPacket.empty() ) {
XMP_Assert ( this->containsXMP );
XMP_StringPtr packetStr = this->xmpPacket.c_str();
XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size();
try {
this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
} catch ( ... ) { /* Ignore parsing failures, someday we hope to get partial XMP back. */ }
haveXMP = true;
}
if ( haveIPTC && (! haveXMP) && (iptcDigestState == kDigestMatches) ) iptcDigestState = kDigestMissing;
bool parseIPTC = (iptcDigestState != kDigestMatches) || (! readOnly);
if ( parseIPTC ) iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen );
ImportPhotoData ( tiff, iptc, psir, iptcDigestState, &this->xmpObj, options );
this->containsXMP = true; // Assume we now have something in the XMP.
} // TIFF_MetaHandler::ProcessXMP
Commit Message:
CWE ID: CWE-125 | void TIFF_MetaHandler::ProcessXMP()
{
this->processedXMP = true; // Make sure we only come through here once.
bool found;
bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0);
if ( readOnly ) {
this->psirMgr = new PSIR_MemoryReader();
this->iptcMgr = new IPTC_Reader();
} else {
this->psirMgr = new PSIR_FileWriter();
this->iptcMgr = new IPTC_Writer(); // ! Parse it later.
}
TIFF_Manager & tiff = this->tiffMgr; // Give the compiler help in recognizing non-aliases.
PSIR_Manager & psir = *this->psirMgr;
IPTC_Manager & iptc = *this->iptcMgr;
TIFF_Manager::TagInfo psirInfo;
bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo );
if ( havePSIR ) { // ! Do the Photoshop 6 integration before other legacy analysis.
psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen );
PSIR_Manager::ImgRsrcInfo buriedExif;
found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif );
if ( found ) {
tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen );
if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif );
}
}
TIFF_Manager::TagInfo iptcInfo;
bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); // The TIFF IPTC tag.
int iptcDigestState = kDigestMatches;
if ( haveIPTC ) {
bool haveDigest = false;
PSIR_Manager::ImgRsrcInfo digestInfo;
if ( havePSIR ) haveDigest = psir.GetImgRsrc ( kPSIR_IPTCDigest, &digestInfo );
if ( digestInfo.dataLen != 16 ) haveDigest = false;
if ( ! haveDigest ) {
iptcDigestState = kDigestMissing;
} else {
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, iptcInfo.dataLen, digestInfo.dataPtr );
// See bug https://bugs.freedesktop.org/show_bug.cgi?id=105205
// if iptcInfo.dataLen is 0, then there is no digest.
if ( (iptcDigestState == kDigestDiffers) && (kTIFF_TypeSizes[iptcInfo.type] > 1) && iptcInfo.dataLen > 0 ) {
XMP_Uns8 * endPtr = (XMP_Uns8*)iptcInfo.dataPtr + iptcInfo.dataLen - 1;
XMP_Uns8 * minPtr = endPtr - kTIFF_TypeSizes[iptcInfo.type] + 1;
while ( (endPtr >= minPtr) && (*endPtr == 0) ) --endPtr;
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, unpaddedLen, digestInfo.dataPtr );
}
}
}
XMP_OptionBits options = k2XMP_FileHadExif; // TIFF files are presumed to have Exif legacy.
if ( haveIPTC ) options |= k2XMP_FileHadIPTC;
if ( this->containsXMP ) options |= k2XMP_FileHadXMP;
bool haveXMP = false;
if ( ! this->xmpPacket.empty() ) {
XMP_Assert ( this->containsXMP );
XMP_StringPtr packetStr = this->xmpPacket.c_str();
XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size();
try {
this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
} catch ( ... ) { /* Ignore parsing failures, someday we hope to get partial XMP back. */ }
haveXMP = true;
}
if ( haveIPTC && (! haveXMP) && (iptcDigestState == kDigestMatches) ) iptcDigestState = kDigestMissing;
bool parseIPTC = (iptcDigestState != kDigestMatches) || (! readOnly);
if ( parseIPTC ) iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen );
ImportPhotoData ( tiff, iptc, psir, iptcDigestState, &this->xmpObj, options );
this->containsXMP = true; // Assume we now have something in the XMP.
} // TIFF_MetaHandler::ProcessXMP
| 164,996 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int store_asoundrc(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Error: invalid .asoundrc file\n");
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) == -1)
errExit("fchown");
if (chmod(dest, 0644) == -1)
errExit("fchmod");
return 1; // file copied
}
return 0;
}
Commit Message: security fix
CWE ID: CWE-269 | static int store_asoundrc(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
// make sure the real path of the file is inside the home directory
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644); // regular user
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
| 170,099 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void AppCacheUpdateJob::HandleMasterEntryFetchCompleted(URLFetcher* fetcher,
int net_error) {
DCHECK(internal_state_ == NO_UPDATE || internal_state_ == DOWNLOADING);
UpdateURLLoaderRequest* request = fetcher->request();
const GURL& url = request->GetURL();
master_entry_fetches_.erase(url);
++master_entries_completed_;
int response_code = net_error == net::OK ? request->GetResponseCode() : -1;
auto found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
if (response_code / 100 == 2) {
AppCache* cache = inprogress_cache_.get() ? inprogress_cache_.get()
: group_->newest_complete_cache();
DCHECK(fetcher->response_writer());
AppCacheEntry master_entry(AppCacheEntry::MASTER,
fetcher->response_writer()->response_id(),
fetcher->response_writer()->amount_written());
if (cache->AddOrModifyEntry(url, master_entry))
added_master_entries_.push_back(url);
else
duplicate_response_ids_.push_back(master_entry.response_id());
if (!inprogress_cache_.get()) {
DCHECK(cache == group_->newest_complete_cache());
for (AppCacheHost* host : hosts)
host->AssociateCompleteCache(cache);
}
} else {
HostNotifier host_notifier;
for (AppCacheHost* host : hosts) {
host_notifier.AddHost(host);
if (inprogress_cache_.get())
host->AssociateNoCache(GURL());
host->RemoveObserver(this);
}
hosts.clear();
failed_master_entries_.insert(url);
const char kFormatString[] = "Manifest fetch failed (%d) %s";
std::string message = FormatUrlErrorMessage(
kFormatString, request->GetURL(), fetcher->result(), response_code);
host_notifier.SendErrorNotifications(blink::mojom::AppCacheErrorDetails(
message, blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR,
request->GetURL(), response_code, false /*is_cross_origin*/));
if (inprogress_cache_.get()) {
pending_master_entries_.erase(found);
--master_entries_completed_;
if (update_type_ == CACHE_ATTEMPT && pending_master_entries_.empty()) {
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
message,
blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR,
request->GetURL(), response_code, false /*is_cross_origin*/),
fetcher->result(), GURL());
return;
}
}
}
DCHECK(internal_state_ != CACHE_FAILURE);
FetchMasterEntries();
MaybeCompleteUpdate();
}
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 AppCacheUpdateJob::HandleMasterEntryFetchCompleted(URLFetcher* fetcher,
int net_error) {
DCHECK(internal_state_ == NO_UPDATE || internal_state_ == DOWNLOADING);
UpdateURLLoaderRequest* request = fetcher->request();
const GURL& url = request->GetURL();
master_entry_fetches_.erase(url);
++master_entries_completed_;
int response_code = net_error == net::OK ? request->GetResponseCode() : -1;
auto found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
if (response_code / 100 == 2) {
AppCache* cache = inprogress_cache_.get() ? inprogress_cache_.get()
: group_->newest_complete_cache();
DCHECK(fetcher->response_writer());
// Master entries cannot be cross-origin by definition, so they do not
// require padding.
AppCacheEntry master_entry(
AppCacheEntry::MASTER, fetcher->response_writer()->response_id(),
fetcher->response_writer()->amount_written(), /*padding_size=*/0);
if (cache->AddOrModifyEntry(url, master_entry))
added_master_entries_.push_back(url);
else
duplicate_response_ids_.push_back(master_entry.response_id());
if (!inprogress_cache_.get()) {
DCHECK(cache == group_->newest_complete_cache());
for (AppCacheHost* host : hosts)
host->AssociateCompleteCache(cache);
}
} else {
HostNotifier host_notifier;
for (AppCacheHost* host : hosts) {
host_notifier.AddHost(host);
if (inprogress_cache_.get())
host->AssociateNoCache(GURL());
host->RemoveObserver(this);
}
hosts.clear();
failed_master_entries_.insert(url);
const char kFormatString[] = "Manifest fetch failed (%d) %s";
std::string message = FormatUrlErrorMessage(
kFormatString, request->GetURL(), fetcher->result(), response_code);
host_notifier.SendErrorNotifications(blink::mojom::AppCacheErrorDetails(
message, blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR,
request->GetURL(), response_code, false /*is_cross_origin*/));
if (inprogress_cache_.get()) {
pending_master_entries_.erase(found);
--master_entries_completed_;
if (update_type_ == CACHE_ATTEMPT && pending_master_entries_.empty()) {
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
message,
blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR,
request->GetURL(), response_code, false /*is_cross_origin*/),
fetcher->result(), GURL());
return;
}
}
}
DCHECK(internal_state_ != CACHE_FAILURE);
FetchMasterEntries();
MaybeCompleteUpdate();
}
| 172,995 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct encrypted_key_payload *epayload = key->payload.data[0];
struct encrypted_key_payload *new_epayload;
char *buf;
char *new_master_desc = NULL;
const char *format = NULL;
size_t datalen = prep->datalen;
int ret = 0;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
buf = kmalloc(datalen + 1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
buf[datalen] = 0;
memcpy(buf, prep->data, datalen);
ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);
if (ret < 0)
goto out;
ret = valid_master_desc(new_master_desc, epayload->master_desc);
if (ret < 0)
goto out;
new_epayload = encrypted_key_alloc(key, epayload->format,
new_master_desc, epayload->datalen);
if (IS_ERR(new_epayload)) {
ret = PTR_ERR(new_epayload);
goto out;
}
__ekey_init(new_epayload, epayload->format, new_master_desc,
epayload->datalen);
memcpy(new_epayload->iv, epayload->iv, ivsize);
memcpy(new_epayload->payload_data, epayload->payload_data,
epayload->payload_datalen);
rcu_assign_keypointer(key, new_epayload);
call_rcu(&epayload->rcu, encrypted_rcu_free);
out:
kfree(buf);
return ret;
}
Commit Message: KEYS: Fix handling of stored error in a negatively instantiated user key
If a user key gets negatively instantiated, an error code is cached in the
payload area. A negatively instantiated key may be then be positively
instantiated by updating it with valid data. However, the ->update key
type method must be aware that the error code may be there.
The following may be used to trigger the bug in the user key type:
keyctl request2 user user "" @u
keyctl add user user "a" @u
which manifests itself as:
BUG: unable to handle kernel paging request at 00000000ffffff8a
IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
PGD 7cc30067 PUD 0
Oops: 0002 [#1] SMP
Modules linked in:
CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000
RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280
[<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246
RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001
RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82
RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000
R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82
R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700
FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0
Stack:
ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82
ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5
ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620
Call Trace:
[<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136
[<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129
[< inline >] __key_update security/keys/key.c:730
[<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908
[< inline >] SYSC_add_key security/keys/keyctl.c:125
[<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60
[<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185
Note the error code (-ENOKEY) in EDX.
A similar bug can be tripped by:
keyctl request2 trusted user "" @u
keyctl add trusted user "a" @u
This should also affect encrypted keys - but that has to be correctly
parameterised or it will fail with EINVAL before getting to the bit that
will crashes.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: David Howells <[email protected]>
Acked-by: Mimi Zohar <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-264 | static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct encrypted_key_payload *epayload = key->payload.data[0];
struct encrypted_key_payload *new_epayload;
char *buf;
char *new_master_desc = NULL;
const char *format = NULL;
size_t datalen = prep->datalen;
int ret = 0;
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags))
return -ENOKEY;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
buf = kmalloc(datalen + 1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
buf[datalen] = 0;
memcpy(buf, prep->data, datalen);
ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);
if (ret < 0)
goto out;
ret = valid_master_desc(new_master_desc, epayload->master_desc);
if (ret < 0)
goto out;
new_epayload = encrypted_key_alloc(key, epayload->format,
new_master_desc, epayload->datalen);
if (IS_ERR(new_epayload)) {
ret = PTR_ERR(new_epayload);
goto out;
}
__ekey_init(new_epayload, epayload->format, new_master_desc,
epayload->datalen);
memcpy(new_epayload->iv, epayload->iv, ivsize);
memcpy(new_epayload->payload_data, epayload->payload_data,
epayload->payload_datalen);
rcu_assign_keypointer(key, new_epayload);
call_rcu(&epayload->rcu, encrypted_rcu_free);
out:
kfree(buf);
return ret;
}
| 167,533 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: static int db_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
if (!(svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
!svm->nmi_singlestep) {
kvm_queue_exception(&svm->vcpu, DB_VECTOR);
return 1;
}
if (svm->nmi_singlestep) {
svm->nmi_singlestep = false;
if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
svm->vmcb->save.rflags &=
~(X86_EFLAGS_TF | X86_EFLAGS_RF);
update_db_bp_intercept(&svm->vcpu);
}
if (svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc =
svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = DB_VECTOR;
return 0;
}
return 1;
}
Commit Message: KVM: svm: unconditionally intercept #DB
This is needed to avoid the possibility that the guest triggers
an infinite stream of #DB exceptions (CVE-2015-8104).
VMX is not affected: because it does not save DR6 in the VMCS,
it already intercepts #DB unconditionally.
Reported-by: Jan Beulich <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399 | static int db_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
if (!(svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
!svm->nmi_singlestep) {
kvm_queue_exception(&svm->vcpu, DB_VECTOR);
return 1;
}
if (svm->nmi_singlestep) {
svm->nmi_singlestep = false;
if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
svm->vmcb->save.rflags &=
~(X86_EFLAGS_TF | X86_EFLAGS_RF);
}
if (svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc =
svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = DB_VECTOR;
return 0;
}
return 1;
}
| 166,568 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) {
if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL ||
lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL ||
lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL ||
lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL ||
lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) {
JsVar *rhs;
int op = lex->tk;
JSP_ASSERT_MATCH(op);
rhs = jspeAssignmentExpression();
rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS
if (JSP_SHOULD_EXECUTE && lhs) {
if (op=='=') {
/* If we're assigning to this and we don't have a parent,
* add it to the symbol table root */
if (!jsvGetRefs(lhs) && jsvIsName(lhs)) {
if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs))
jsvAddName(execInfo.root, lhs);
}
jspReplaceWith(lhs, rhs);
} else {
if (op==LEX_PLUSEQUAL) op='+';
else if (op==LEX_MINUSEQUAL) op='-';
else if (op==LEX_MULEQUAL) op='*';
else if (op==LEX_DIVEQUAL) op='/';
else if (op==LEX_MODEQUAL) op='%';
else if (op==LEX_ANDEQUAL) op='&';
else if (op==LEX_OREQUAL) op='|';
else if (op==LEX_XOREQUAL) op='^';
else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT;
else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT;
else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED;
if (op=='+' && jsvIsName(lhs)) {
JsVar *currentValue = jsvSkipName(lhs);
if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) {
/* A special case for string += where this is the only use of the string
* and we're not appending to ourselves. In this case we can do a
* simple append (rather than clone + append)*/
JsVar *str = jsvAsString(rhs, false);
jsvAppendStringVarComplete(currentValue, str);
jsvUnLock(str);
op = 0;
}
jsvUnLock(currentValue);
}
if (op) {
/* Fallback which does a proper add */
JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op);
jspReplaceWith(lhs, res);
jsvUnLock(res);
}
}
}
jsvUnLock(rhs);
}
return lhs;
}
Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437)
CWE ID: CWE-125 | NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) {
if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL ||
lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL ||
lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL ||
lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL ||
lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) {
JsVar *rhs;
int op = lex->tk;
JSP_ASSERT_MATCH(op);
rhs = jspeAssignmentExpression();
rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS
if (JSP_SHOULD_EXECUTE && lhs) {
if (op=='=') {
jspReplaceWithOrAddToRoot(lhs, rhs);
} else {
if (op==LEX_PLUSEQUAL) op='+';
else if (op==LEX_MINUSEQUAL) op='-';
else if (op==LEX_MULEQUAL) op='*';
else if (op==LEX_DIVEQUAL) op='/';
else if (op==LEX_MODEQUAL) op='%';
else if (op==LEX_ANDEQUAL) op='&';
else if (op==LEX_OREQUAL) op='|';
else if (op==LEX_XOREQUAL) op='^';
else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT;
else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT;
else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED;
if (op=='+' && jsvIsName(lhs)) {
JsVar *currentValue = jsvSkipName(lhs);
if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) {
/* A special case for string += where this is the only use of the string
* and we're not appending to ourselves. In this case we can do a
* simple append (rather than clone + append)*/
JsVar *str = jsvAsString(rhs, false);
jsvAppendStringVarComplete(currentValue, str);
jsvUnLock(str);
op = 0;
}
jsvUnLock(currentValue);
}
if (op) {
/* Fallback which does a proper add */
JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op);
jspReplaceWith(lhs, res);
jsvUnLock(res);
}
}
}
jsvUnLock(rhs);
}
return lhs;
}
| 169,207 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset) {
bloc = *offset;
send(huff->loc[ch], NULL, fout);
*offset = bloc;
}
Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.
CWE ID: CWE-119 | void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset) {
void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset, int maxoffset) {
bloc = *offset;
send(huff->loc[ch], NULL, fout, maxoffset);
*offset = bloc;
}
| 167,995 |
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. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, setMaxLineLen)
{
long max_len;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) {
return;
}
if (max_len < 0) {
zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero");
return;
}
intern->u.file.max_line_len = max_len;
} /* }}} */
/* {{{ proto int SplFileObject::getMaxLineLen()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, setMaxLineLen)
{
long max_len;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) {
return;
}
if (max_len < 0) {
zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero");
return;
}
intern->u.file.max_line_len = max_len;
} /* }}} */
/* {{{ proto int SplFileObject::getMaxLineLen()
| 167,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. Remember, I want response with just the fixed code only, No explanation. | Code: static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr,
BT_HDR* p_pkt) {
uint8_t opcode;
tAVRC_MSG msg;
uint8_t* p_data;
uint8_t* p_begin;
bool drop = false;
bool do_free = true;
BT_HDR* p_rsp = NULL;
uint8_t* p_rsp_data;
int xx;
bool reject = false;
const char* p_drop_msg = "dropped";
tAVRC_MSG_VENDOR* p_msg = &msg.vendor;
if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL &&
AVRC_PACKET_LEN < sizeof(p_pkt->len))) {
/* Ignore the invalid AV/C command frame */
p_drop_msg = "dropped - too long AV/C cmd frame size";
osi_free(p_pkt);
return;
}
if (cr == AVCT_REJ) {
/* The peer thinks that this PID is no longer open - remove this handle */
/* */
osi_free(p_pkt);
AVCT_RemoveConn(handle);
return;
} else if (cr == AVCT_RSP) {
/* Received response. Stop command timeout timer */
AVRC_TRACE_DEBUG("AVRC: stopping timer (handle=0x%02x)", handle);
alarm_cancel(avrc_cb.ccb_int[handle].tle);
}
p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
memset(&msg, 0, sizeof(tAVRC_MSG));
if (p_pkt->layer_specific == AVCT_DATA_BROWSE) {
opcode = AVRC_OP_BROWSE;
msg.browse.hdr.ctype = cr;
msg.browse.p_browse_data = p_data;
msg.browse.browse_len = p_pkt->len;
msg.browse.p_browse_pkt = p_pkt;
} else {
msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK;
AVRC_TRACE_DEBUG("%s handle:%d, ctype:%d, offset:%d, len: %d", __func__,
handle, msg.hdr.ctype, p_pkt->offset, p_pkt->len);
msg.hdr.subunit_type =
(p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT;
msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK;
opcode = p_data[2];
}
if (((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) ||
((avrc_cb.ccb[handle].control & AVRC_CT_CONTROL) && (cr == AVCT_RSP))) {
switch (opcode) {
case AVRC_OP_UNIT_INFO:
if (cr == AVCT_CMD) {
/* send the response to the peer */
p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_UNIT_INFO_RSP_LEN);
p_rsp_data = avrc_get_data_ptr(p_rsp);
*p_rsp_data = AVRC_RSP_IMPL_STBL;
/* check & set the offset. set response code, set subunit_type &
subunit_id,
set AVRC_OP_UNIT_INFO */
/* 3 bytes: ctype, subunit*, opcode */
p_rsp_data += AVRC_AVC_HDR_SIZE;
*p_rsp_data++ = 7;
/* Panel subunit & id=0 */
*p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
AVRC_CO_ID_TO_BE_STREAM(p_rsp_data, avrc_cb.ccb[handle].company_id);
p_rsp->len =
(uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset);
cr = AVCT_RSP;
p_drop_msg = "auto respond";
} else {
/* parse response */
p_data += 4; /* 3 bytes: ctype, subunit*, opcode + octet 3 (is 7)*/
msg.unit.unit_type =
(*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT;
msg.unit.unit = *p_data & AVRC_SUBID_MASK;
p_data++;
AVRC_BE_STREAM_TO_CO_ID(msg.unit.company_id, p_data);
}
break;
case AVRC_OP_SUB_INFO:
if (cr == AVCT_CMD) {
/* send the response to the peer */
p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_SUB_UNIT_INFO_RSP_LEN);
p_rsp_data = avrc_get_data_ptr(p_rsp);
*p_rsp_data = AVRC_RSP_IMPL_STBL;
/* check & set the offset. set response code, set (subunit_type &
subunit_id),
set AVRC_OP_SUB_INFO, set (page & extention code) */
p_rsp_data += 4;
/* Panel subunit & id=0 */
*p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
memset(p_rsp_data, AVRC_CMD_OPRND_PAD, AVRC_SUBRSP_OPRND_BYTES);
p_rsp_data += AVRC_SUBRSP_OPRND_BYTES;
p_rsp->len =
(uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset);
cr = AVCT_RSP;
p_drop_msg = "auto responded";
} else {
/* parse response */
p_data += AVRC_AVC_HDR_SIZE; /* 3 bytes: ctype, subunit*, opcode */
msg.sub.page =
(*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK;
xx = 0;
while (*p_data != AVRC_CMD_OPRND_PAD && xx < AVRC_SUB_TYPE_LEN) {
msg.sub.subunit_type[xx] = *p_data++ >> AVRC_SUBTYPE_SHIFT;
if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL)
msg.sub.panel = true;
xx++;
}
}
break;
case AVRC_OP_VENDOR: {
p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_begin = p_data;
if (p_pkt->len <
AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */
{
if (cr == AVCT_CMD)
reject = true;
else
drop = true;
break;
}
p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*,
opcode */
AVRC_BE_STREAM_TO_CO_ID(p_msg->company_id, p_data);
p_msg->p_vendor_data = p_data;
p_msg->vendor_len = p_pkt->len - (p_data - p_begin);
uint8_t drop_code = 0;
if (p_msg->company_id == AVRC_CO_METADATA) {
/* Validate length for metadata message */
if (p_pkt->len < (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE)) {
if (cr == AVCT_CMD)
reject = true;
else
drop = true;
break;
}
/* Check+handle fragmented messages */
drop_code = avrc_proc_far_msg(handle, label, cr, &p_pkt, p_msg);
if (drop_code > 0) drop = true;
}
if (drop_code > 0) {
if (drop_code != 4) do_free = false;
switch (drop_code) {
case 1:
p_drop_msg = "sent_frag";
break;
case 2:
p_drop_msg = "req_cont";
break;
case 3:
p_drop_msg = "sent_frag3";
break;
case 4:
p_drop_msg = "sent_frag_free";
break;
default:
p_drop_msg = "sent_fragd";
}
}
/* If vendor response received, and did not ask for continuation */
/* then check queue for addition commands to send */
if ((cr == AVCT_RSP) && (drop_code != 2)) {
avrc_send_next_vendor_cmd(handle);
}
} break;
case AVRC_OP_PASS_THRU:
if (p_pkt->len < 5) /* 3 bytes: ctype, subunit*, opcode & op_id & len */
{
if (cr == AVCT_CMD)
reject = true;
else
drop = true;
break;
}
p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*,
opcode */
msg.pass.op_id = (AVRC_PASS_OP_ID_MASK & *p_data);
if (AVRC_PASS_STATE_MASK & *p_data)
msg.pass.state = true;
else
msg.pass.state = false;
p_data++;
msg.pass.pass_len = *p_data++;
if (msg.pass.pass_len != p_pkt->len - 5)
msg.pass.pass_len = p_pkt->len - 5;
if (msg.pass.pass_len)
msg.pass.p_pass_data = p_data;
else
msg.pass.p_pass_data = NULL;
break;
case AVRC_OP_BROWSE:
/* If browse response received, then check queue for addition commands
* to send */
if (cr == AVCT_RSP) {
avrc_send_next_vendor_cmd(handle);
}
break;
default:
if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) &&
(cr == AVCT_CMD)) {
/* reject unsupported opcode */
reject = true;
}
drop = true;
break;
}
} else /* drop the event */
{
if (opcode != AVRC_OP_BROWSE) drop = true;
}
if (reject) {
/* reject unsupported opcode */
p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_REJ_MSG_LEN);
p_rsp_data = avrc_get_data_ptr(p_rsp);
*p_rsp_data = AVRC_RSP_REJ;
p_drop_msg = "rejected";
cr = AVCT_RSP;
drop = true;
}
if (p_rsp) {
/* set to send response right away */
AVCT_MsgReq(handle, label, cr, p_rsp);
drop = true;
}
if (!drop) {
msg.hdr.opcode = opcode;
avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg);
} else {
AVRC_TRACE_WARNING("%s %s msg handle:%d, control:%d, cr:%d, opcode:x%x",
__func__, p_drop_msg, handle,
avrc_cb.ccb[handle].control, cr, opcode);
}
if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) {
do_free = false;
}
if (do_free) osi_free(p_pkt);
}
Commit Message: Add missing AVRCP message length checks inside avrc_msg_cback
Explicitly check the length of the received message before
accessing the data.
Bug: 111803925
Bug: 79883824
Test: POC scripts
Change-Id: I00b1c6bd6dd7e18ac2c469ef2032c7ff10dcaecb
Merged-In: I00b1c6bd6dd7e18ac2c469ef2032c7ff10dcaecb
(cherry picked from commit 282deb3e27407aaa88b8ddbdbd7bb7d56ddc635f)
(cherry picked from commit 007868d05f4b761842c7345161aeda6fd40dd245)
CWE ID: CWE-125 | static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr,
BT_HDR* p_pkt) {
uint8_t opcode;
tAVRC_MSG msg;
uint8_t* p_data;
uint8_t* p_begin;
bool drop = false;
bool do_free = true;
BT_HDR* p_rsp = NULL;
uint8_t* p_rsp_data;
int xx;
bool reject = false;
const char* p_drop_msg = "dropped";
tAVRC_MSG_VENDOR* p_msg = &msg.vendor;
if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL &&
AVRC_PACKET_LEN < sizeof(p_pkt->len))) {
/* Ignore the invalid AV/C command frame */
p_drop_msg = "dropped - too long AV/C cmd frame size";
osi_free(p_pkt);
return;
}
if (cr == AVCT_REJ) {
/* The peer thinks that this PID is no longer open - remove this handle */
/* */
osi_free(p_pkt);
AVCT_RemoveConn(handle);
return;
} else if (cr == AVCT_RSP) {
/* Received response. Stop command timeout timer */
AVRC_TRACE_DEBUG("AVRC: stopping timer (handle=0x%02x)", handle);
alarm_cancel(avrc_cb.ccb_int[handle].tle);
}
p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
memset(&msg, 0, sizeof(tAVRC_MSG));
if (p_pkt->layer_specific == AVCT_DATA_BROWSE) {
opcode = AVRC_OP_BROWSE;
msg.browse.hdr.ctype = cr;
msg.browse.p_browse_data = p_data;
msg.browse.browse_len = p_pkt->len;
msg.browse.p_browse_pkt = p_pkt;
} else {
if (p_pkt->len < AVRC_AVC_HDR_SIZE) {
android_errorWriteLog(0x534e4554, "111803925");
AVRC_TRACE_WARNING("%s: message length %d too short: must be at least %d",
__func__, p_pkt->len, AVRC_AVC_HDR_SIZE);
osi_free(p_pkt);
return;
}
msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK;
AVRC_TRACE_DEBUG("%s handle:%d, ctype:%d, offset:%d, len: %d", __func__,
handle, msg.hdr.ctype, p_pkt->offset, p_pkt->len);
msg.hdr.subunit_type =
(p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT;
msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK;
opcode = p_data[2];
}
if (((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) ||
((avrc_cb.ccb[handle].control & AVRC_CT_CONTROL) && (cr == AVCT_RSP))) {
switch (opcode) {
case AVRC_OP_UNIT_INFO:
if (cr == AVCT_CMD) {
/* send the response to the peer */
p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_UNIT_INFO_RSP_LEN);
p_rsp_data = avrc_get_data_ptr(p_rsp);
*p_rsp_data = AVRC_RSP_IMPL_STBL;
/* check & set the offset. set response code, set subunit_type &
subunit_id,
set AVRC_OP_UNIT_INFO */
/* 3 bytes: ctype, subunit*, opcode */
p_rsp_data += AVRC_AVC_HDR_SIZE;
*p_rsp_data++ = 7;
/* Panel subunit & id=0 */
*p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
AVRC_CO_ID_TO_BE_STREAM(p_rsp_data, avrc_cb.ccb[handle].company_id);
p_rsp->len =
(uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset);
cr = AVCT_RSP;
p_drop_msg = "auto respond";
} else {
/* parse response */
if (p_pkt->len < AVRC_OP_UNIT_INFO_RSP_LEN) {
AVRC_TRACE_WARNING(
"%s: message length %d too short: must be at least %d",
__func__, p_pkt->len, AVRC_OP_UNIT_INFO_RSP_LEN);
android_errorWriteLog(0x534e4554, "79883824");
drop = true;
p_drop_msg = "UNIT_INFO_RSP too short";
break;
}
p_data += 4; /* 3 bytes: ctype, subunit*, opcode + octet 3 (is 7)*/
msg.unit.unit_type =
(*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT;
msg.unit.unit = *p_data & AVRC_SUBID_MASK;
p_data++;
AVRC_BE_STREAM_TO_CO_ID(msg.unit.company_id, p_data);
}
break;
case AVRC_OP_SUB_INFO:
if (cr == AVCT_CMD) {
/* send the response to the peer */
p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_SUB_UNIT_INFO_RSP_LEN);
p_rsp_data = avrc_get_data_ptr(p_rsp);
*p_rsp_data = AVRC_RSP_IMPL_STBL;
/* check & set the offset. set response code, set (subunit_type &
subunit_id),
set AVRC_OP_SUB_INFO, set (page & extention code) */
p_rsp_data += 4;
/* Panel subunit & id=0 */
*p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
memset(p_rsp_data, AVRC_CMD_OPRND_PAD, AVRC_SUBRSP_OPRND_BYTES);
p_rsp_data += AVRC_SUBRSP_OPRND_BYTES;
p_rsp->len =
(uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset);
cr = AVCT_RSP;
p_drop_msg = "auto responded";
} else {
/* parse response */
if (p_pkt->len < AVRC_OP_SUB_UNIT_INFO_RSP_LEN) {
AVRC_TRACE_WARNING(
"%s: message length %d too short: must be at least %d",
__func__, p_pkt->len, AVRC_OP_SUB_UNIT_INFO_RSP_LEN);
android_errorWriteLog(0x534e4554, "79883824");
drop = true;
p_drop_msg = "SUB_UNIT_INFO_RSP too short";
break;
}
p_data += AVRC_AVC_HDR_SIZE; /* 3 bytes: ctype, subunit*, opcode */
msg.sub.page =
(*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK;
xx = 0;
while (*p_data != AVRC_CMD_OPRND_PAD && xx < AVRC_SUB_TYPE_LEN) {
msg.sub.subunit_type[xx] = *p_data++ >> AVRC_SUBTYPE_SHIFT;
if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL)
msg.sub.panel = true;
xx++;
}
}
break;
case AVRC_OP_VENDOR: {
p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_begin = p_data;
if (p_pkt->len <
AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */
{
if (cr == AVCT_CMD)
reject = true;
else
drop = true;
break;
}
p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*,
opcode */
AVRC_BE_STREAM_TO_CO_ID(p_msg->company_id, p_data);
p_msg->p_vendor_data = p_data;
p_msg->vendor_len = p_pkt->len - (p_data - p_begin);
uint8_t drop_code = 0;
if (p_msg->company_id == AVRC_CO_METADATA) {
/* Validate length for metadata message */
if (p_pkt->len < (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE)) {
if (cr == AVCT_CMD)
reject = true;
else
drop = true;
break;
}
/* Check+handle fragmented messages */
drop_code = avrc_proc_far_msg(handle, label, cr, &p_pkt, p_msg);
if (drop_code > 0) drop = true;
}
if (drop_code > 0) {
if (drop_code != 4) do_free = false;
switch (drop_code) {
case 1:
p_drop_msg = "sent_frag";
break;
case 2:
p_drop_msg = "req_cont";
break;
case 3:
p_drop_msg = "sent_frag3";
break;
case 4:
p_drop_msg = "sent_frag_free";
break;
default:
p_drop_msg = "sent_fragd";
}
}
/* If vendor response received, and did not ask for continuation */
/* then check queue for addition commands to send */
if ((cr == AVCT_RSP) && (drop_code != 2)) {
avrc_send_next_vendor_cmd(handle);
}
} break;
case AVRC_OP_PASS_THRU:
if (p_pkt->len < 5) /* 3 bytes: ctype, subunit*, opcode & op_id & len */
{
if (cr == AVCT_CMD)
reject = true;
else
drop = true;
break;
}
p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*,
opcode */
msg.pass.op_id = (AVRC_PASS_OP_ID_MASK & *p_data);
if (AVRC_PASS_STATE_MASK & *p_data)
msg.pass.state = true;
else
msg.pass.state = false;
p_data++;
msg.pass.pass_len = *p_data++;
if (msg.pass.pass_len != p_pkt->len - 5)
msg.pass.pass_len = p_pkt->len - 5;
if (msg.pass.pass_len)
msg.pass.p_pass_data = p_data;
else
msg.pass.p_pass_data = NULL;
break;
case AVRC_OP_BROWSE:
/* If browse response received, then check queue for addition commands
* to send */
if (cr == AVCT_RSP) {
avrc_send_next_vendor_cmd(handle);
}
break;
default:
if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) &&
(cr == AVCT_CMD)) {
/* reject unsupported opcode */
reject = true;
}
drop = true;
break;
}
} else /* drop the event */
{
if (opcode != AVRC_OP_BROWSE) drop = true;
}
if (reject) {
/* reject unsupported opcode */
p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_REJ_MSG_LEN);
p_rsp_data = avrc_get_data_ptr(p_rsp);
*p_rsp_data = AVRC_RSP_REJ;
p_drop_msg = "rejected";
cr = AVCT_RSP;
drop = true;
}
if (p_rsp) {
/* set to send response right away */
AVCT_MsgReq(handle, label, cr, p_rsp);
drop = true;
}
if (!drop) {
msg.hdr.opcode = opcode;
avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg);
} else {
AVRC_TRACE_WARNING("%s %s msg handle:%d, control:%d, cr:%d, opcode:x%x",
__func__, p_drop_msg, handle,
avrc_cb.ccb[handle].control, cr, opcode);
}
if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) {
do_free = false;
}
if (do_free) osi_free(p_pkt);
}
| 174,079 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.