project
stringclasses
765 values
commit_id
stringlengths
6
81
func
stringlengths
19
482k
vul
int64
0
1
CVE ID
stringlengths
13
16
CWE ID
stringclasses
13 values
CWE Name
stringclasses
13 values
CWE Description
stringclasses
13 values
Potential Mitigation
stringclasses
11 values
__index_level_0__
int64
0
23.9k
php-src
2fefae47716d501aec41c1102f3fd4531f070b05
PHP_FUNCTION(dns_get_record) { char *hostname; int hostname_len; long type_param = PHP_DNS_ANY; zval *authns = NULL, *addtl = NULL; int type_to_fetch; #if defined(HAVE_DNS_SEARCH) struct sockaddr_storage from; uint32_t fromsize = sizeof(from); dns_handle_t handle; #elif defined(HAVE_RES_NSEARCH) struct __res_state state; struct __res_state *handle = &state; #endif HEADER *hp; querybuf answer; u_char *cp = NULL, *end = NULL; int n, qd, an, ns = 0, ar = 0; int type, first_query = 1, store_results = 1; zend_bool raw = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz!z!b", &hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) { return; } if (authns) { zval_dtor(authns); array_init(authns); } if (addtl) { zval_dtor(addtl); array_init(addtl); } if (!raw) { if ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%ld' not supported", type_param); RETURN_FALSE; } } else { if ((type_param < 1) || (type_param > 0xFFFF)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Numeric DNS record type must be between 1 and 65535, '%ld' given", type_param); RETURN_FALSE; } } /* Initialize the return array */ array_init(return_value); /* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 ) * If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 ) * store_results is used to skip storing the results retrieved in step * NUMTYPES+1 when results were already fetched. * - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 ) * - In case of raw mode, we query only the requestd type instead of looping type by type * before going with the additional info stuff. */ if (raw) { type = -1; } else if (type_param == PHP_DNS_ANY) { type = PHP_DNS_NUM_TYPES + 1; } else { type = 0; } for ( ; type < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query; type++ ) { first_query = 0; switch (type) { case -1: /* raw */ type_to_fetch = type_param; /* skip over the rest and go directly to additional records */ type = PHP_DNS_NUM_TYPES - 1; break; case 0: type_to_fetch = type_param&PHP_DNS_A ? DNS_T_A : 0; break; case 1: type_to_fetch = type_param&PHP_DNS_NS ? DNS_T_NS : 0; break; case 2: type_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0; break; case 3: type_to_fetch = type_param&PHP_DNS_SOA ? DNS_T_SOA : 0; break; case 4: type_to_fetch = type_param&PHP_DNS_PTR ? DNS_T_PTR : 0; break; case 5: type_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0; break; case 6: type_to_fetch = type_param&PHP_DNS_MX ? DNS_T_MX : 0; break; case 7: type_to_fetch = type_param&PHP_DNS_TXT ? DNS_T_TXT : 0; break; case 8: type_to_fetch = type_param&PHP_DNS_AAAA ? DNS_T_AAAA : 0; break; case 9: type_to_fetch = type_param&PHP_DNS_SRV ? DNS_T_SRV : 0; break; case 10: type_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0; break; case 11: type_to_fetch = type_param&PHP_DNS_A6 ? DNS_T_A6 : 0; break; case PHP_DNS_NUM_TYPES: store_results = 0; continue; default: case (PHP_DNS_NUM_TYPES + 1): type_to_fetch = DNS_T_ANY; break; } if (type_to_fetch) { #if defined(HAVE_DNS_SEARCH) handle = dns_open(NULL); if (handle == NULL) { zval_dtor(return_value); RETURN_FALSE; } #elif defined(HAVE_RES_NSEARCH) memset(&state, 0, sizeof(state)); if (res_ninit(handle)) { zval_dtor(return_value); RETURN_FALSE; } #else res_init(); #endif n = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer); if (n < 0) { php_dns_free_handle(handle); continue; } cp = answer.qb2 + HFIXEDSZ; end = answer.qb2 + n; hp = (HEADER *)&answer; qd = ntohs(hp->qdcount); an = ntohs(hp->ancount); ns = ntohs(hp->nscount); ar = ntohs(hp->arcount); /* Skip QD entries, they're only used by dn_expand later on */ while (qd-- > 0) { n = dn_skipname(cp, end); if (n < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to parse DNS data received"); zval_dtor(return_value); php_dns_free_handle(handle); RETURN_FALSE; } cp += n + QFIXEDSZ; } /* YAY! Our real answers! */ while (an-- && cp && cp < end) { zval *retval; cp = php_parserr(cp, &answer, type_to_fetch, store_results, raw, &retval); if (retval != NULL && store_results) { add_next_index_zval(return_value, retval); } } if (authns || addtl) { /* List of Authoritative Name Servers * Process when only requesting addtl so that we can skip through the section */ while (ns-- > 0 && cp && cp < end) { zval *retval = NULL; cp = php_parserr(cp, &answer, DNS_T_ANY, authns != NULL, raw, &retval); if (retval != NULL) { add_next_index_zval(authns, retval); } } } if (addtl) { /* Additional records associated with authoritative name servers */ while (ar-- > 0 && cp && cp < end) { zval *retval = NULL; cp = php_parserr(cp, &answer, DNS_T_ANY, 1, raw, &retval); if (retval != NULL) { add_next_index_zval(addtl, retval); } } } php_dns_free_handle(handle); } } }
1
CVE-2014-3597
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
8,975
OpenSC
412a6142c27a5973c61ba540e33cdc22d5608e68
static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen, int invert) { const u8 *in = inbuf; u8 *out = (u8 *) outbuf; int zero_bits = *in & 0x07; size_t octets_left = inlen - 1; int i, count = 0; memset(outbuf, 0, outlen); in++; if (outlen < octets_left) return SC_ERROR_BUFFER_TOO_SMALL; if (inlen < 1) return SC_ERROR_INVALID_ASN1_OBJECT; while (octets_left) { /* 1st octet of input: ABCDEFGH, where A is the MSB */ /* 1st octet of output: HGFEDCBA, where A is the LSB */ /* first bit in bit string is the LSB in first resulting octet */ int bits_to_go; *out = 0; if (octets_left == 1) bits_to_go = 8 - zero_bits; else bits_to_go = 8; if (invert) for (i = 0; i < bits_to_go; i++) { *out |= ((*in >> (7 - i)) & 1) << i; } else { *out = *in; } out++; in++; octets_left--; count++; } return (count * 8) - zero_bits; }
1
CVE-2019-15945
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
1,797
libxml2
2240fbf5912054af025fb6e01e26375100275e74
gz_next4(xz_statep state, unsigned long *ret) { int ch; unsigned long val; z_streamp strm = &(state->zstrm); val = NEXTZ(); val += (unsigned) NEXTZ() << 8; val += (unsigned long) NEXTZ() << 16; ch = NEXTZ(); if (ch == -1) return -1; val += (unsigned long) ch << 24; *ret = val; return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,147
linux
60085c3d009b0df252547adb336d1ccca5ce52ec
static int recv_msg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t buf_len, int flags) { struct sock *sk = sock->sk; struct tipc_port *tport = tipc_sk_port(sk); struct sk_buff *buf; struct tipc_msg *msg; long timeout; unsigned int sz; u32 err; int res; /* Catch invalid receive requests */ if (unlikely(!buf_len)) return -EINVAL; lock_sock(sk); if (unlikely(sock->state == SS_UNCONNECTED)) { res = -ENOTCONN; goto exit; } timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); restart: /* Look for a message in receive queue; wait if necessary */ while (skb_queue_empty(&sk->sk_receive_queue)) { if (sock->state == SS_DISCONNECTING) { res = -ENOTCONN; goto exit; } if (timeout <= 0L) { res = timeout ? timeout : -EWOULDBLOCK; goto exit; } release_sock(sk); timeout = wait_event_interruptible_timeout(*sk_sleep(sk), tipc_rx_ready(sock), timeout); lock_sock(sk); } /* Look at first message in receive queue */ buf = skb_peek(&sk->sk_receive_queue); msg = buf_msg(buf); sz = msg_data_sz(msg); err = msg_errcode(msg); /* Discard an empty non-errored message & try again */ if ((!sz) && (!err)) { advance_rx_queue(sk); goto restart; } /* Capture sender's address (optional) */ set_orig_addr(m, msg); /* Capture ancillary data (optional) */ res = anc_data_recv(m, msg, tport); if (res) goto exit; /* Capture message data (if valid) & compute return value (always) */ if (!err) { if (unlikely(buf_len < sz)) { sz = buf_len; m->msg_flags |= MSG_TRUNC; } res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg), m->msg_iov, sz); if (res) goto exit; res = sz; } else { if ((sock->state == SS_READY) || ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)) res = 0; else res = -ECONNRESET; } /* Consume received message (optional) */ if (likely(!(flags & MSG_PEEK))) { if ((sock->state != SS_READY) && (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN)) tipc_acknowledge(tport->ref, tport->conn_unacked); advance_rx_queue(sk); } exit: release_sock(sk); return res; }
1
CVE-2013-3235
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Phase: Architecture and Design Strategy: Separation of Privilege Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges.
4,340
linux
040757f738e13caaa9c5078bca79aa97e11dde88
static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid) { struct hlist_head *hashent = ucounts_hashentry(ns, uid); struct ucounts *ucounts, *new; spin_lock_irq(&ucounts_lock); ucounts = find_ucounts(ns, uid, hashent); if (!ucounts) { spin_unlock_irq(&ucounts_lock); new = kzalloc(sizeof(*new), GFP_KERNEL); if (!new) return NULL; new->ns = ns; new->uid = uid; atomic_set(&new->count, 0); spin_lock_irq(&ucounts_lock); ucounts = find_ucounts(ns, uid, hashent); if (ucounts) { kfree(new); } else { hlist_add_head(&new->node, hashent); ucounts = new; } } if (!atomic_add_unless(&ucounts->count, 1, INT_MAX)) ucounts = NULL; spin_unlock_irq(&ucounts_lock); return ucounts; }
1
CVE-2017-6874
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
6,058
tensorflow
e84c975313e8e8e38bb2ea118196369c45c51378
static void AddInstanceStatsToMap( const int32_t instance, const int32_t feature_dim, const int32_t bucket_id, const int32_t logits_dims, const int32_t stats_dims, StatsPartitionMap* stats_map, const TTypes<float>::ConstMatrix& gradients, const TTypes<float>::ConstMatrix& hessians, const TTypes<int32>::ConstVec& node_ids) { const int32_t node_id = node_ids(instance); const auto key = StatsPartitionKey(node_id, feature_dim, bucket_id); std::pair<StatsPartitionIterator, bool> const& insert_result = stats_map->insert(StatsPartitionIterator::value_type( key, std::vector<float>(stats_dims, 0.0f))); auto& stats = insert_result.first->second; for (int stat_dim = 0; stat_dim < logits_dims; ++stat_dim) { stats[stat_dim] += gradients(instance, stat_dim); } for (int stat_dim = logits_dims; stat_dim < stats_dims; ++stat_dim) { stats[stat_dim] += hessians(instance, stat_dim - logits_dims); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,853
Chrome
60907d63ce74cbed893473c4e9bb569f47ca0c01
void LoginUtils::Set(LoginUtils* mock) { Singleton<LoginUtilsWrapper>::get()->reset(mock); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,104
php-src
8d2539fa0faf3f63e1d1e7635347c5b9e777d47b
static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry *pce; zval obj; /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) || !strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) || !strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) || !strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) || !strcmp((char *)name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (Z_TYPE(ent1->data) == IS_UNDEF) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp((char *)name, EL_BINARY)) { zend_string *new_str = NULL; if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) { new_str = php_base64_decode( (unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } zval_ptr_dtor(&ent1->data); if (new_str) { ZVAL_STR(&ent1->data, new_str); } else { ZVAL_EMPTY_STRING(&ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE(ent1->data) == IS_OBJECT) { zval fname, retval; ZVAL_STRING(&fname, "__wakeup"); call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (Z_ISUNDEF(ent2->data)) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(&ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zend_string_forget_hash_val(Z_STR(ent1->data)); if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) { incomplete_class = 1; pce = PHP_IC_ENTRY; } if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data)); } else { /* Initialize target object */ object_init_ex(&obj, pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP(obj), Z_ARRVAL(ent2->data), zval_add_ref, 0); if (incomplete_class) { php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ZVAL_COPY_VALUE(&ent2->data, &obj); } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE(ent2->data); add_property_zval(&ent2->data, ent1->varname, &ent1->data); if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data); EG(scope) = old_scope; } else { zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp((char *)name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp((char *)name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } }
1
CVE-2016-10162
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
7,793
Chrome
a4150b688a754d3d10d2ca385155b1c95d77d6ae
void FeatureInfo::InitializeFeatures() { std::string extensions_string(gl::GetGLExtensionsFromCurrentContext()); gfx::ExtensionSet extensions(gfx::MakeExtensionSet(extensions_string)); const char* version_str = reinterpret_cast<const char*>(glGetString(GL_VERSION)); const char* renderer_str = reinterpret_cast<const char*>(glGetString(GL_RENDERER)); gl_version_info_.reset( new gl::GLVersionInfo(version_str, renderer_str, extensions)); bool enable_es3 = IsWebGL2OrES3OrHigherContext(); bool has_pixel_buffers = gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_ARB_pixel_buffer_object") || gfx::HasExtension(extensions, "GL_NV_pixel_buffer_object"); ScopedPixelUnpackBufferOverride scoped_pbo_override(has_pixel_buffers, 0); AddExtensionString("GL_ANGLE_translated_shader_source"); AddExtensionString("GL_CHROMIUM_async_pixel_transfers"); AddExtensionString("GL_CHROMIUM_bind_uniform_location"); AddExtensionString("GL_CHROMIUM_color_space_metadata"); AddExtensionString("GL_CHROMIUM_command_buffer_query"); AddExtensionString("GL_CHROMIUM_command_buffer_latency_query"); AddExtensionString("GL_CHROMIUM_copy_texture"); AddExtensionString("GL_CHROMIUM_deschedule"); AddExtensionString("GL_CHROMIUM_get_error_query"); AddExtensionString("GL_CHROMIUM_lose_context"); AddExtensionString("GL_CHROMIUM_pixel_transfer_buffer_object"); AddExtensionString("GL_CHROMIUM_rate_limit_offscreen_context"); AddExtensionString("GL_CHROMIUM_resize"); AddExtensionString("GL_CHROMIUM_resource_safe"); AddExtensionString("GL_CHROMIUM_strict_attribs"); AddExtensionString("GL_CHROMIUM_texture_mailbox"); AddExtensionString("GL_CHROMIUM_trace_marker"); AddExtensionString("GL_EXT_debug_marker"); AddExtensionString("GL_EXT_unpack_subimage"); AddExtensionString("GL_OES_vertex_array_object"); if (gfx::HasExtension(extensions, "GL_ANGLE_translated_shader_source")) { feature_flags_.angle_translated_shader_source = true; } bool enable_dxt1 = false; bool enable_dxt3 = false; bool enable_dxt5 = false; bool have_s3tc = gfx::HasExtension(extensions, "GL_EXT_texture_compression_s3tc"); bool have_dxt3 = have_s3tc || gfx::HasExtension(extensions, "GL_ANGLE_texture_compression_dxt3"); bool have_dxt5 = have_s3tc || gfx::HasExtension(extensions, "GL_ANGLE_texture_compression_dxt5"); if (gfx::HasExtension(extensions, "GL_EXT_texture_compression_dxt1") || gfx::HasExtension(extensions, "GL_ANGLE_texture_compression_dxt1") || have_s3tc) { enable_dxt1 = true; } if (have_dxt3) { enable_dxt3 = true; } if (have_dxt5) { enable_dxt5 = true; } if (enable_dxt1) { feature_flags_.ext_texture_format_dxt1 = true; AddExtensionString("GL_ANGLE_texture_compression_dxt1"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGB_S3TC_DXT1_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT1_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGB_S3TC_DXT1_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT1_EXT); } if (enable_dxt3) { AddExtensionString("GL_ANGLE_texture_compression_dxt3"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT3_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT3_EXT); } if (enable_dxt5) { feature_flags_.ext_texture_format_dxt5 = true; AddExtensionString("GL_ANGLE_texture_compression_dxt5"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT5_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT5_EXT); } bool have_astc = gfx::HasExtension(extensions, "GL_KHR_texture_compression_astc_ldr"); if (have_astc) { feature_flags_.ext_texture_format_astc = true; AddExtensionString("GL_KHR_texture_compression_astc_ldr"); GLint astc_format_it = GL_COMPRESSED_RGBA_ASTC_4x4_KHR; GLint astc_format_max = GL_COMPRESSED_RGBA_ASTC_12x12_KHR; for (; astc_format_it <= astc_format_max; astc_format_it++) { validators_.compressed_texture_format.AddValue(astc_format_it); validators_.texture_internal_format_storage.AddValue(astc_format_it); } astc_format_it = GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; astc_format_max = GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; for (; astc_format_it <= astc_format_max; astc_format_it++) { validators_.compressed_texture_format.AddValue(astc_format_it); validators_.texture_internal_format_storage.AddValue(astc_format_it); } } bool have_atc = gfx::HasExtension(extensions, "GL_AMD_compressed_ATC_texture") || gfx::HasExtension(extensions, "GL_ATI_texture_compression_atitc"); if (have_atc) { feature_flags_.ext_texture_format_atc = true; AddExtensionString("GL_AMD_compressed_ATC_texture"); validators_.compressed_texture_format.AddValue(GL_ATC_RGB_AMD); validators_.compressed_texture_format.AddValue( GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); validators_.texture_internal_format_storage.AddValue(GL_ATC_RGB_AMD); validators_.texture_internal_format_storage.AddValue( GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); } if (gfx::HasExtension(extensions, "GL_EXT_texture_filter_anisotropic")) { AddExtensionString("GL_EXT_texture_filter_anisotropic"); validators_.texture_parameter.AddValue(GL_TEXTURE_MAX_ANISOTROPY_EXT); validators_.g_l_state.AddValue(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); } bool enable_depth_texture = false; GLenum depth_texture_format = GL_NONE; if (!workarounds_.disable_depth_texture && (gfx::HasExtension(extensions, "GL_ARB_depth_texture") || gfx::HasExtension(extensions, "GL_OES_depth_texture") || gfx::HasExtension(extensions, "GL_ANGLE_depth_texture") || gl_version_info_->is_desktop_core_profile)) { enable_depth_texture = true; depth_texture_format = GL_DEPTH_COMPONENT; feature_flags_.angle_depth_texture = gfx::HasExtension(extensions, "GL_ANGLE_depth_texture"); } if (enable_depth_texture) { AddExtensionString("GL_CHROMIUM_depth_texture"); AddExtensionString("GL_GOOGLE_depth_texture"); validators_.texture_internal_format.AddValue(GL_DEPTH_COMPONENT); validators_.texture_format.AddValue(GL_DEPTH_COMPONENT); validators_.pixel_type.AddValue(GL_UNSIGNED_SHORT); validators_.pixel_type.AddValue(GL_UNSIGNED_INT); validators_.texture_depth_renderable_internal_format.AddValue( GL_DEPTH_COMPONENT); } GLenum depth_stencil_texture_format = GL_NONE; if (gfx::HasExtension(extensions, "GL_EXT_packed_depth_stencil") || gfx::HasExtension(extensions, "GL_OES_packed_depth_stencil") || gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile) { AddExtensionString("GL_OES_packed_depth_stencil"); feature_flags_.packed_depth24_stencil8 = true; if (enable_depth_texture) { if (gl_version_info_->is_es3) { depth_stencil_texture_format = GL_DEPTH24_STENCIL8; } else { depth_stencil_texture_format = GL_DEPTH_STENCIL; } validators_.texture_internal_format.AddValue(GL_DEPTH_STENCIL); validators_.texture_format.AddValue(GL_DEPTH_STENCIL); validators_.pixel_type.AddValue(GL_UNSIGNED_INT_24_8); validators_.texture_depth_renderable_internal_format.AddValue( GL_DEPTH_STENCIL); validators_.texture_stencil_renderable_internal_format.AddValue( GL_DEPTH_STENCIL); } validators_.render_buffer_format.AddValue(GL_DEPTH24_STENCIL8); if (context_type_ == CONTEXT_TYPE_WEBGL1) { validators_.attachment.AddValue(GL_DEPTH_STENCIL_ATTACHMENT); validators_.attachment_query.AddValue(GL_DEPTH_STENCIL_ATTACHMENT); } } if (gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_OES_vertex_array_object") || gfx::HasExtension(extensions, "GL_ARB_vertex_array_object") || gfx::HasExtension(extensions, "GL_APPLE_vertex_array_object")) { feature_flags_.native_vertex_array_object = true; } if (workarounds_.use_client_side_arrays_for_stream_buffers) { feature_flags_.native_vertex_array_object = false; } if (gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_OES_element_index_uint") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_element_index_uint"); validators_.index_type.AddValue(GL_UNSIGNED_INT); } bool has_srgb_framebuffer_support = false; if (gl_version_info_->IsAtLeastGL(3, 2) || (gl_version_info_->IsAtLeastGL(2, 0) && (gfx::HasExtension(extensions, "GL_EXT_framebuffer_sRGB") || gfx::HasExtension(extensions, "GL_ARB_framebuffer_sRGB")))) { feature_flags_.desktop_srgb_support = true; has_srgb_framebuffer_support = true; } if ((((gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_OES_rgb8_rgba8")) && gfx::HasExtension(extensions, "GL_EXT_sRGB")) || feature_flags_.desktop_srgb_support) && IsWebGL1OrES2Context()) { feature_flags_.ext_srgb = true; AddExtensionString("GL_EXT_sRGB"); validators_.texture_internal_format.AddValue(GL_SRGB_EXT); validators_.texture_internal_format.AddValue(GL_SRGB_ALPHA_EXT); validators_.texture_format.AddValue(GL_SRGB_EXT); validators_.texture_format.AddValue(GL_SRGB_ALPHA_EXT); validators_.render_buffer_format.AddValue(GL_SRGB8_ALPHA8_EXT); validators_.framebuffer_attachment_parameter.AddValue( GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT); validators_.texture_unsized_internal_format.AddValue(GL_SRGB_EXT); validators_.texture_unsized_internal_format.AddValue(GL_SRGB_ALPHA_EXT); has_srgb_framebuffer_support = true; } if (gl_version_info_->is_es3) has_srgb_framebuffer_support = true; if (has_srgb_framebuffer_support && !IsWebGLContext()) { if (feature_flags_.desktop_srgb_support || gfx::HasExtension(extensions, "GL_EXT_sRGB_write_control")) { feature_flags_.ext_srgb_write_control = true; AddExtensionString("GL_EXT_sRGB_write_control"); validators_.capability.AddValue(GL_FRAMEBUFFER_SRGB_EXT); } } if (gfx::HasExtension(extensions, "GL_EXT_texture_sRGB_decode") && !IsWebGLContext()) { AddExtensionString("GL_EXT_texture_sRGB_decode"); validators_.texture_parameter.AddValue(GL_TEXTURE_SRGB_DECODE_EXT); } bool have_s3tc_srgb = false; if (gl_version_info_->is_es) { have_s3tc_srgb = gfx::HasExtension(extensions, "GL_NV_sRGB_formats") || gfx::HasExtension(extensions, "GL_EXT_texture_compression_s3tc_srgb"); } else { if (gfx::HasExtension(extensions, "GL_EXT_texture_sRGB") || gl_version_info_->IsAtLeastGL(4, 1)) { have_s3tc_srgb = gfx::HasExtension(extensions, "GL_EXT_texture_compression_s3tc"); } } if (have_s3tc_srgb) { AddExtensionString("GL_EXT_texture_compression_s3tc_srgb"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_SRGB_S3TC_DXT1_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_SRGB_S3TC_DXT1_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT); } bool has_apple_bgra = gfx::HasExtension(extensions, "GL_APPLE_texture_format_BGRA8888"); bool has_ext_bgra = gfx::HasExtension(extensions, "GL_EXT_texture_format_BGRA8888"); bool enable_texture_format_bgra8888 = has_ext_bgra || has_apple_bgra || !gl_version_info_->is_es; bool has_ext_texture_storage = gfx::HasExtension(extensions, "GL_EXT_texture_storage"); bool has_arb_texture_storage = gfx::HasExtension(extensions, "GL_ARB_texture_storage"); bool has_texture_storage = !workarounds_.disable_texture_storage && (has_ext_texture_storage || has_arb_texture_storage || gl_version_info_->is_es3 || gl_version_info_->IsAtLeastGL(4, 2)); bool enable_texture_storage = has_texture_storage; bool texture_storage_incompatible_with_bgra = gl_version_info_->is_es3 && !has_ext_texture_storage && !has_apple_bgra; if (texture_storage_incompatible_with_bgra && enable_texture_format_bgra8888 && enable_texture_storage) { switch (context_type_) { case CONTEXT_TYPE_OPENGLES2: enable_texture_storage = false; break; case CONTEXT_TYPE_OPENGLES3: enable_texture_format_bgra8888 = false; break; case CONTEXT_TYPE_WEBGL1: case CONTEXT_TYPE_WEBGL2: case CONTEXT_TYPE_WEBGL2_COMPUTE: case CONTEXT_TYPE_WEBGPU: break; } } if (enable_texture_storage) { feature_flags_.ext_texture_storage = true; AddExtensionString("GL_EXT_texture_storage"); validators_.texture_parameter.AddValue(GL_TEXTURE_IMMUTABLE_FORMAT_EXT); } if (enable_texture_format_bgra8888) { feature_flags_.ext_texture_format_bgra8888 = true; AddExtensionString("GL_EXT_texture_format_BGRA8888"); validators_.texture_internal_format.AddValue(GL_BGRA_EXT); validators_.texture_format.AddValue(GL_BGRA_EXT); validators_.texture_unsized_internal_format.AddValue(GL_BGRA_EXT); validators_.texture_internal_format_storage.AddValue(GL_BGRA8_EXT); validators_.texture_sized_color_renderable_internal_format.AddValue( GL_BGRA8_EXT); validators_.texture_sized_texture_filterable_internal_format.AddValue( GL_BGRA8_EXT); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRA_8888); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRX_8888); } bool enable_render_buffer_bgra = gl_version_info_->is_angle || !gl_version_info_->is_es; if (enable_render_buffer_bgra) { feature_flags_.ext_render_buffer_format_bgra8888 = true; AddExtensionString("GL_CHROMIUM_renderbuffer_format_BGRA8888"); validators_.render_buffer_format.AddValue(GL_BGRA8_EXT); } bool enable_read_format_bgra = gfx::HasExtension(extensions, "GL_EXT_read_format_bgra") || !gl_version_info_->is_es; if (enable_read_format_bgra) { feature_flags_.ext_read_format_bgra = true; AddExtensionString("GL_EXT_read_format_bgra"); validators_.read_pixel_format.AddValue(GL_BGRA_EXT); } feature_flags_.arb_es3_compatibility = gfx::HasExtension(extensions, "GL_ARB_ES3_compatibility") && !gl_version_info_->is_es; feature_flags_.ext_disjoint_timer_query = gfx::HasExtension(extensions, "GL_EXT_disjoint_timer_query"); if (feature_flags_.ext_disjoint_timer_query || gfx::HasExtension(extensions, "GL_ARB_timer_query") || gfx::HasExtension(extensions, "GL_EXT_timer_query")) { AddExtensionString("GL_EXT_disjoint_timer_query"); } if (gfx::HasExtension(extensions, "GL_OES_rgb8_rgba8") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_rgb8_rgba8"); validators_.render_buffer_format.AddValue(GL_RGB8_OES); validators_.render_buffer_format.AddValue(GL_RGBA8_OES); } if (!disallowed_features_.npot_support && (gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_ARB_texture_non_power_of_two") || gfx::HasExtension(extensions, "GL_OES_texture_npot"))) { AddExtensionString("GL_OES_texture_npot"); feature_flags_.npot_ok = true; } InitializeFloatAndHalfFloatFeatures(extensions); if (!workarounds_.disable_chromium_framebuffer_multisample) { bool ext_has_multisample = gfx::HasExtension(extensions, "GL_ARB_framebuffer_object") || (gfx::HasExtension(extensions, "GL_EXT_framebuffer_multisample") && gfx::HasExtension(extensions, "GL_EXT_framebuffer_blit")) || gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile; if (gl_version_info_->is_angle || gl_version_info_->is_swiftshader) { ext_has_multisample |= gfx::HasExtension(extensions, "GL_ANGLE_framebuffer_multisample"); } if (ext_has_multisample) { feature_flags_.chromium_framebuffer_multisample = true; validators_.framebuffer_target.AddValue(GL_READ_FRAMEBUFFER_EXT); validators_.framebuffer_target.AddValue(GL_DRAW_FRAMEBUFFER_EXT); validators_.g_l_state.AddValue(GL_READ_FRAMEBUFFER_BINDING_EXT); validators_.g_l_state.AddValue(GL_MAX_SAMPLES_EXT); validators_.render_buffer_parameter.AddValue(GL_RENDERBUFFER_SAMPLES_EXT); AddExtensionString("GL_CHROMIUM_framebuffer_multisample"); } } if (gfx::HasExtension(extensions, "GL_EXT_multisampled_render_to_texture")) { feature_flags_.multisampled_render_to_texture = true; } else if (gfx::HasExtension(extensions, "GL_IMG_multisampled_render_to_texture")) { feature_flags_.multisampled_render_to_texture = true; feature_flags_.use_img_for_multisampled_render_to_texture = true; } if (feature_flags_.multisampled_render_to_texture) { validators_.render_buffer_parameter.AddValue(GL_RENDERBUFFER_SAMPLES_EXT); validators_.g_l_state.AddValue(GL_MAX_SAMPLES_EXT); validators_.framebuffer_attachment_parameter.AddValue( GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT); AddExtensionString("GL_EXT_multisampled_render_to_texture"); } if (!gl_version_info_->is_es || gfx::HasExtension(extensions, "GL_EXT_multisample_compatibility")) { AddExtensionString("GL_EXT_multisample_compatibility"); feature_flags_.ext_multisample_compatibility = true; validators_.capability.AddValue(GL_MULTISAMPLE_EXT); validators_.capability.AddValue(GL_SAMPLE_ALPHA_TO_ONE_EXT); } if (gfx::HasExtension(extensions, "GL_INTEL_framebuffer_CMAA")) { feature_flags_.chromium_screen_space_antialiasing = true; AddExtensionString("GL_CHROMIUM_screen_space_antialiasing"); } else if (gl_version_info_->IsAtLeastGLES(3, 1) || (gl_version_info_->IsAtLeastGL(3, 0) && gfx::HasExtension(extensions, "GL_ARB_shading_language_420pack") && gfx::HasExtension(extensions, "GL_ARB_texture_storage") && gfx::HasExtension(extensions, "GL_ARB_texture_gather") && gfx::HasExtension(extensions, "GL_ARB_explicit_uniform_location") && gfx::HasExtension(extensions, "GL_ARB_explicit_attrib_location") && gfx::HasExtension(extensions, "GL_ARB_shader_image_load_store"))) { feature_flags_.chromium_screen_space_antialiasing = true; feature_flags_.use_chromium_screen_space_antialiasing_via_shaders = true; AddExtensionString("GL_CHROMIUM_screen_space_antialiasing"); } if (gfx::HasExtension(extensions, "GL_OES_depth24") || gl::HasDesktopGLFeatures() || gl_version_info_->is_es3) { AddExtensionString("GL_OES_depth24"); feature_flags_.oes_depth24 = true; validators_.render_buffer_format.AddValue(GL_DEPTH_COMPONENT24); } if (gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_OES_standard_derivatives") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_standard_derivatives"); feature_flags_.oes_standard_derivatives = true; validators_.hint_target.AddValue(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES); validators_.g_l_state.AddValue(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES); } if (gfx::HasExtension(extensions, "GL_CHROMIUM_texture_filtering_hint")) { AddExtensionString("GL_CHROMIUM_texture_filtering_hint"); feature_flags_.chromium_texture_filtering_hint = true; validators_.hint_target.AddValue(GL_TEXTURE_FILTERING_HINT_CHROMIUM); validators_.g_l_state.AddValue(GL_TEXTURE_FILTERING_HINT_CHROMIUM); } if (gfx::HasExtension(extensions, "GL_OES_EGL_image_external")) { AddExtensionString("GL_OES_EGL_image_external"); feature_flags_.oes_egl_image_external = true; } if (gfx::HasExtension(extensions, "GL_NV_EGL_stream_consumer_external")) { AddExtensionString("GL_NV_EGL_stream_consumer_external"); feature_flags_.nv_egl_stream_consumer_external = true; } if (feature_flags_.oes_egl_image_external || feature_flags_.nv_egl_stream_consumer_external) { validators_.texture_bind_target.AddValue(GL_TEXTURE_EXTERNAL_OES); validators_.get_tex_param_target.AddValue(GL_TEXTURE_EXTERNAL_OES); validators_.texture_parameter.AddValue(GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES); validators_.g_l_state.AddValue(GL_TEXTURE_BINDING_EXTERNAL_OES); } if (gfx::HasExtension(extensions, "GL_OES_compressed_ETC1_RGB8_texture") && !gl_version_info_->is_angle) { AddExtensionString("GL_OES_compressed_ETC1_RGB8_texture"); feature_flags_.oes_compressed_etc1_rgb8_texture = true; validators_.compressed_texture_format.AddValue(GL_ETC1_RGB8_OES); validators_.texture_internal_format_storage.AddValue(GL_ETC1_RGB8_OES); } if (gfx::HasExtension(extensions, "GL_CHROMIUM_compressed_texture_etc") || (gl_version_info_->is_es3 && !gl_version_info_->is_angle)) { AddExtensionString("GL_CHROMIUM_compressed_texture_etc"); validators_.UpdateETCCompressedTextureFormats(); } if (gfx::HasExtension(extensions, "GL_AMD_compressed_ATC_texture")) { AddExtensionString("GL_AMD_compressed_ATC_texture"); validators_.compressed_texture_format.AddValue(GL_ATC_RGB_AMD); validators_.compressed_texture_format.AddValue( GL_ATC_RGBA_EXPLICIT_ALPHA_AMD); validators_.compressed_texture_format.AddValue( GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); validators_.texture_internal_format_storage.AddValue(GL_ATC_RGB_AMD); validators_.texture_internal_format_storage.AddValue( GL_ATC_RGBA_EXPLICIT_ALPHA_AMD); validators_.texture_internal_format_storage.AddValue( GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); } if (gfx::HasExtension(extensions, "GL_IMG_texture_compression_pvrtc")) { AddExtensionString("GL_IMG_texture_compression_pvrtc"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG); } if (gfx::HasExtension(extensions, "GL_ARB_texture_rectangle") || gfx::HasExtension(extensions, "GL_ANGLE_texture_rectangle") || gl_version_info_->is_desktop_core_profile) { AddExtensionString("GL_ARB_texture_rectangle"); feature_flags_.arb_texture_rectangle = true; validators_.texture_bind_target.AddValue(GL_TEXTURE_RECTANGLE_ARB); validators_.texture_target.AddValue(GL_TEXTURE_RECTANGLE_ARB); validators_.get_tex_param_target.AddValue(GL_TEXTURE_RECTANGLE_ARB); validators_.g_l_state.AddValue(GL_TEXTURE_BINDING_RECTANGLE_ARB); } #if defined(OS_MACOSX) || defined(OS_CHROMEOS) AddExtensionString("GL_CHROMIUM_ycbcr_420v_image"); feature_flags_.chromium_image_ycbcr_420v = true; #endif if (feature_flags_.chromium_image_ycbcr_420v) { feature_flags_.gpu_memory_buffer_formats.Add( gfx::BufferFormat::YUV_420_BIPLANAR); } if (gfx::HasExtension(extensions, "GL_APPLE_ycbcr_422")) { AddExtensionString("GL_CHROMIUM_ycbcr_422_image"); feature_flags_.chromium_image_ycbcr_422 = true; feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::UYVY_422); } #if defined(OS_MACOSX) feature_flags_.chromium_image_xr30 = base::mac::IsAtLeastOS10_13(); #elif !defined(OS_WIN) feature_flags_.chromium_image_xb30 = gl_version_info_->IsAtLeastGL(3, 3) || gl_version_info_->IsAtLeastGLES(3, 0) || gfx::HasExtension(extensions, "GL_EXT_texture_type_2_10_10_10_REV"); #endif if (feature_flags_.chromium_image_xr30 || feature_flags_.chromium_image_xb30) { validators_.texture_internal_format.AddValue(GL_RGB10_A2_EXT); validators_.render_buffer_format.AddValue(GL_RGB10_A2_EXT); validators_.texture_internal_format_storage.AddValue(GL_RGB10_A2_EXT); validators_.pixel_type.AddValue(GL_UNSIGNED_INT_2_10_10_10_REV); } if (feature_flags_.chromium_image_xr30) { feature_flags_.gpu_memory_buffer_formats.Add( gfx::BufferFormat::BGRX_1010102); } if (feature_flags_.chromium_image_xb30) { feature_flags_.gpu_memory_buffer_formats.Add( gfx::BufferFormat::RGBX_1010102); } if (gfx::HasExtension(extensions, "GL_ANGLE_texture_usage")) { feature_flags_.angle_texture_usage = true; AddExtensionString("GL_ANGLE_texture_usage"); validators_.texture_parameter.AddValue(GL_TEXTURE_USAGE_ANGLE); } bool have_occlusion_query = gl_version_info_->IsAtLeastGLES(3, 0) || gl_version_info_->IsAtLeastGL(3, 3); bool have_ext_occlusion_query_boolean = gfx::HasExtension(extensions, "GL_EXT_occlusion_query_boolean"); bool have_arb_occlusion_query2 = gfx::HasExtension(extensions, "GL_ARB_occlusion_query2"); bool have_arb_occlusion_query = (gl_version_info_->is_desktop_core_profile && gl_version_info_->IsAtLeastGL(1, 5)) || gfx::HasExtension(extensions, "GL_ARB_occlusion_query"); if (have_occlusion_query || have_ext_occlusion_query_boolean || have_arb_occlusion_query2 || have_arb_occlusion_query) { feature_flags_.occlusion_query = have_arb_occlusion_query; if (context_type_ == CONTEXT_TYPE_OPENGLES2) { AddExtensionString("GL_EXT_occlusion_query_boolean"); } feature_flags_.occlusion_query_boolean = true; feature_flags_.use_arb_occlusion_query2_for_occlusion_query_boolean = !have_ext_occlusion_query_boolean && (have_arb_occlusion_query2 || (gl_version_info_->IsAtLeastGL(3, 3) && gl_version_info_->IsLowerThanGL(4, 3))); feature_flags_.use_arb_occlusion_query_for_occlusion_query_boolean = !have_ext_occlusion_query_boolean && have_arb_occlusion_query && !have_arb_occlusion_query2; } if (gfx::HasExtension(extensions, "GL_ANGLE_instanced_arrays") || (gfx::HasExtension(extensions, "GL_ARB_instanced_arrays") && gfx::HasExtension(extensions, "GL_ARB_draw_instanced")) || gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile) { AddExtensionString("GL_ANGLE_instanced_arrays"); feature_flags_.angle_instanced_arrays = true; validators_.vertex_attribute.AddValue(GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE); } bool have_es2_draw_buffers_vendor_agnostic = gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_ARB_draw_buffers") || gfx::HasExtension(extensions, "GL_EXT_draw_buffers"); bool can_emulate_es2_draw_buffers_on_es3_nv = gl_version_info_->is_es3 && gfx::HasExtension(extensions, "GL_NV_draw_buffers"); bool is_webgl_compatibility_context = gfx::HasExtension(extensions, "GL_ANGLE_webgl_compatibility"); bool have_es2_draw_buffers = !workarounds_.disable_ext_draw_buffers && (have_es2_draw_buffers_vendor_agnostic || can_emulate_es2_draw_buffers_on_es3_nv) && (context_type_ == CONTEXT_TYPE_OPENGLES2 || (context_type_ == CONTEXT_TYPE_WEBGL1 && IsWebGLDrawBuffersSupported(is_webgl_compatibility_context, depth_texture_format, depth_stencil_texture_format))); if (have_es2_draw_buffers) { AddExtensionString("GL_EXT_draw_buffers"); feature_flags_.ext_draw_buffers = true; feature_flags_.nv_draw_buffers = can_emulate_es2_draw_buffers_on_es3_nv && !have_es2_draw_buffers_vendor_agnostic; } if (IsWebGL2OrES3OrHigherContext() || have_es2_draw_buffers) { GLint max_color_attachments = 0; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &max_color_attachments); for (GLenum i = GL_COLOR_ATTACHMENT1_EXT; i < static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + max_color_attachments); ++i) { validators_.attachment.AddValue(i); validators_.attachment_query.AddValue(i); } static_assert(GL_COLOR_ATTACHMENT0_EXT == GL_COLOR_ATTACHMENT0, "GL_COLOR_ATTACHMENT0_EXT should equal GL_COLOR_ATTACHMENT0"); validators_.g_l_state.AddValue(GL_MAX_COLOR_ATTACHMENTS_EXT); validators_.g_l_state.AddValue(GL_MAX_DRAW_BUFFERS_ARB); GLint max_draw_buffers = 0; glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &max_draw_buffers); for (GLenum i = GL_DRAW_BUFFER0_ARB; i < static_cast<GLenum>(GL_DRAW_BUFFER0_ARB + max_draw_buffers); ++i) { validators_.g_l_state.AddValue(i); } } if (gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_EXT_blend_minmax") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_EXT_blend_minmax"); validators_.equation.AddValue(GL_MIN_EXT); validators_.equation.AddValue(GL_MAX_EXT); static_assert(GL_MIN_EXT == GL_MIN && GL_MAX_EXT == GL_MAX, "min & max variations must match"); } if (gfx::HasExtension(extensions, "GL_EXT_frag_depth") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_EXT_frag_depth"); feature_flags_.ext_frag_depth = true; } if (gfx::HasExtension(extensions, "GL_EXT_shader_texture_lod") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_EXT_shader_texture_lod"); feature_flags_.ext_shader_texture_lod = true; } bool ui_gl_fence_works = gl::GLFence::IsSupported(); UMA_HISTOGRAM_BOOLEAN("GPU.FenceSupport", ui_gl_fence_works); feature_flags_.map_buffer_range = gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_ARB_map_buffer_range") || gfx::HasExtension(extensions, "GL_EXT_map_buffer_range"); if (has_pixel_buffers && ui_gl_fence_works && !workarounds_.disable_async_readpixels) { feature_flags_.use_async_readpixels = true; } if (gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_ARB_sampler_objects")) { feature_flags_.enable_samplers = true; } if ((gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_EXT_discard_framebuffer")) && !workarounds_.disable_discard_framebuffer) { AddExtensionString("GL_EXT_discard_framebuffer"); feature_flags_.ext_discard_framebuffer = true; } if (ui_gl_fence_works) { AddExtensionString("GL_CHROMIUM_sync_query"); feature_flags_.chromium_sync_query = true; } if (!workarounds_.disable_blend_equation_advanced) { bool blend_equation_advanced_coherent = gfx::HasExtension(extensions, "GL_NV_blend_equation_advanced_coherent") || gfx::HasExtension(extensions, "GL_KHR_blend_equation_advanced_coherent"); if (blend_equation_advanced_coherent || gfx::HasExtension(extensions, "GL_NV_blend_equation_advanced") || gfx::HasExtension(extensions, "GL_KHR_blend_equation_advanced")) { const GLenum equations[] = { GL_MULTIPLY_KHR, GL_SCREEN_KHR, GL_OVERLAY_KHR, GL_DARKEN_KHR, GL_LIGHTEN_KHR, GL_COLORDODGE_KHR, GL_COLORBURN_KHR, GL_HARDLIGHT_KHR, GL_SOFTLIGHT_KHR, GL_DIFFERENCE_KHR, GL_EXCLUSION_KHR, GL_HSL_HUE_KHR, GL_HSL_SATURATION_KHR, GL_HSL_COLOR_KHR, GL_HSL_LUMINOSITY_KHR}; for (GLenum equation : equations) validators_.equation.AddValue(equation); if (blend_equation_advanced_coherent) AddExtensionString("GL_KHR_blend_equation_advanced_coherent"); AddExtensionString("GL_KHR_blend_equation_advanced"); feature_flags_.blend_equation_advanced = true; feature_flags_.blend_equation_advanced_coherent = blend_equation_advanced_coherent; } } if (gfx::HasExtension(extensions, "GL_NV_framebuffer_mixed_samples")) { AddExtensionString("GL_CHROMIUM_framebuffer_mixed_samples"); feature_flags_.chromium_framebuffer_mixed_samples = true; validators_.g_l_state.AddValue(GL_COVERAGE_MODULATION_CHROMIUM); } if (gfx::HasExtension(extensions, "GL_NV_path_rendering")) { bool has_dsa = gl_version_info_->IsAtLeastGL(4, 5) || gfx::HasExtension(extensions, "GL_EXT_direct_state_access"); bool has_piq = gl_version_info_->IsAtLeastGL(4, 3) || gfx::HasExtension(extensions, "GL_ARB_program_interface_query"); bool has_fms = feature_flags_.chromium_framebuffer_mixed_samples; if ((gl_version_info_->IsAtLeastGLES(3, 1) || (gl_version_info_->IsAtLeastGL(3, 2) && has_dsa && has_piq)) && has_fms) { AddExtensionString("GL_CHROMIUM_path_rendering"); feature_flags_.chromium_path_rendering = true; validators_.g_l_state.AddValue(GL_PATH_MODELVIEW_MATRIX_CHROMIUM); validators_.g_l_state.AddValue(GL_PATH_PROJECTION_MATRIX_CHROMIUM); validators_.g_l_state.AddValue(GL_PATH_STENCIL_FUNC_CHROMIUM); validators_.g_l_state.AddValue(GL_PATH_STENCIL_REF_CHROMIUM); validators_.g_l_state.AddValue(GL_PATH_STENCIL_VALUE_MASK_CHROMIUM); } } if ((gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_EXT_texture_rg") || gfx::HasExtension(extensions, "GL_ARB_texture_rg")) && IsGL_REDSupportedOnFBOs()) { feature_flags_.ext_texture_rg = true; AddExtensionString("GL_EXT_texture_rg"); validators_.texture_format.AddValue(GL_RED_EXT); validators_.texture_format.AddValue(GL_RG_EXT); validators_.texture_internal_format.AddValue(GL_RED_EXT); validators_.texture_internal_format.AddValue(GL_R8_EXT); validators_.texture_internal_format.AddValue(GL_RG_EXT); validators_.texture_internal_format.AddValue(GL_RG8_EXT); validators_.read_pixel_format.AddValue(GL_RED_EXT); validators_.read_pixel_format.AddValue(GL_RG_EXT); validators_.render_buffer_format.AddValue(GL_R8_EXT); validators_.render_buffer_format.AddValue(GL_RG8_EXT); validators_.texture_unsized_internal_format.AddValue(GL_RED_EXT); validators_.texture_unsized_internal_format.AddValue(GL_RG_EXT); validators_.texture_internal_format_storage.AddValue(GL_R8_EXT); validators_.texture_internal_format_storage.AddValue(GL_RG8_EXT); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::R_8); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RG_88); } UMA_HISTOGRAM_BOOLEAN("GPU.TextureRG", feature_flags_.ext_texture_rg); if (gl_version_info_->is_desktop_core_profile || (gl_version_info_->IsAtLeastGL(2, 1) && gfx::HasExtension(extensions, "GL_ARB_texture_rg")) || gfx::HasExtension(extensions, "GL_EXT_texture_norm16")) { feature_flags_.ext_texture_norm16 = true; g_r16_is_present = true; validators_.pixel_type.AddValue(GL_UNSIGNED_SHORT); validators_.texture_format.AddValue(GL_RED_EXT); validators_.texture_internal_format.AddValue(GL_R16_EXT); validators_.texture_internal_format.AddValue(GL_RED_EXT); validators_.texture_unsized_internal_format.AddValue(GL_RED_EXT); validators_.texture_internal_format_storage.AddValue(GL_R16_EXT); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::R_16); } UMA_HISTOGRAM_ENUMERATION( "GPU.TextureR16Ext_LuminanceF16", GpuTextureUMAHelper(), static_cast<int>(GpuTextureResultR16_L16::kMax) + 1); if (enable_es3 && gfx::HasExtension(extensions, "GL_EXT_window_rectangles")) { AddExtensionString("GL_EXT_window_rectangles"); feature_flags_.ext_window_rectangles = true; validators_.g_l_state.AddValue(GL_WINDOW_RECTANGLE_MODE_EXT); validators_.g_l_state.AddValue(GL_MAX_WINDOW_RECTANGLES_EXT); validators_.g_l_state.AddValue(GL_NUM_WINDOW_RECTANGLES_EXT); validators_.indexed_g_l_state.AddValue(GL_WINDOW_RECTANGLE_EXT); } bool has_opengl_dual_source_blending = gl_version_info_->IsAtLeastGL(3, 3) || (gl_version_info_->IsAtLeastGL(3, 2) && gfx::HasExtension(extensions, "GL_ARB_blend_func_extended")); if (!disable_shader_translator_ && !workarounds_.get_frag_data_info_bug && ((gl_version_info_->IsAtLeastGL(3, 2) && has_opengl_dual_source_blending) || (gl_version_info_->IsAtLeastGLES(3, 0) && gfx::HasExtension(extensions, "GL_EXT_blend_func_extended")))) { feature_flags_.ext_blend_func_extended = true; AddExtensionString("GL_EXT_blend_func_extended"); validators_.dst_blend_factor.AddValue(GL_SRC_ALPHA_SATURATE_EXT); validators_.src_blend_factor.AddValue(GL_SRC1_ALPHA_EXT); validators_.dst_blend_factor.AddValue(GL_SRC1_ALPHA_EXT); validators_.src_blend_factor.AddValue(GL_SRC1_COLOR_EXT); validators_.dst_blend_factor.AddValue(GL_SRC1_COLOR_EXT); validators_.src_blend_factor.AddValue(GL_ONE_MINUS_SRC1_COLOR_EXT); validators_.dst_blend_factor.AddValue(GL_ONE_MINUS_SRC1_COLOR_EXT); validators_.src_blend_factor.AddValue(GL_ONE_MINUS_SRC1_ALPHA_EXT); validators_.dst_blend_factor.AddValue(GL_ONE_MINUS_SRC1_ALPHA_EXT); validators_.g_l_state.AddValue(GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT); } #if !defined(OS_MACOSX) if (workarounds_.ignore_egl_sync_failures) { gl::GLFenceEGL::SetIgnoreFailures(); } #endif if (workarounds_.avoid_egl_image_target_texture_reuse) { TextureDefinition::AvoidEGLTargetTextureReuse(); } if (gl_version_info_->IsLowerThanGL(4, 3)) { feature_flags_.emulate_primitive_restart_fixed_index = true; } feature_flags_.angle_robust_client_memory = gfx::HasExtension(extensions, "GL_ANGLE_robust_client_memory"); feature_flags_.khr_debug = gl_version_info_->IsAtLeastGL(4, 3) || gl_version_info_->IsAtLeastGLES(3, 2) || gfx::HasExtension(extensions, "GL_KHR_debug"); feature_flags_.chromium_gpu_fence = gl::GLFence::IsGpuFenceSupported(); if (feature_flags_.chromium_gpu_fence) AddExtensionString("GL_CHROMIUM_gpu_fence"); feature_flags_.chromium_bind_generates_resource = gfx::HasExtension(extensions, "GL_CHROMIUM_bind_generates_resource"); feature_flags_.angle_webgl_compatibility = is_webgl_compatibility_context; feature_flags_.chromium_copy_texture = gfx::HasExtension(extensions, "GL_CHROMIUM_copy_texture"); feature_flags_.chromium_copy_compressed_texture = gfx::HasExtension(extensions, "GL_CHROMIUM_copy_compressed_texture"); feature_flags_.angle_client_arrays = gfx::HasExtension(extensions, "GL_ANGLE_client_arrays"); feature_flags_.angle_request_extension = gfx::HasExtension(extensions, "GL_ANGLE_request_extension"); feature_flags_.ext_debug_marker = gfx::HasExtension(extensions, "GL_EXT_debug_marker"); feature_flags_.arb_robustness = gfx::HasExtension(extensions, "GL_ARB_robustness"); feature_flags_.khr_robustness = gfx::HasExtension(extensions, "GL_KHR_robustness"); feature_flags_.ext_robustness = gfx::HasExtension(extensions, "GL_EXT_robustness"); feature_flags_.ext_pixel_buffer_object = gfx::HasExtension(extensions, "GL_ARB_pixel_buffer_object") || gfx::HasExtension(extensions, "GL_NV_pixel_buffer_object"); feature_flags_.ext_unpack_subimage = gfx::HasExtension(extensions, "GL_EXT_unpack_subimage"); feature_flags_.oes_rgb8_rgba8 = gfx::HasExtension(extensions, "GL_OES_rgb8_rgba8"); feature_flags_.angle_robust_resource_initialization = gfx::HasExtension(extensions, "GL_ANGLE_robust_resource_initialization"); feature_flags_.nv_fence = gfx::HasExtension(extensions, "GL_NV_fence"); feature_flags_.unpremultiply_and_dither_copy = !is_passthrough_cmd_decoder_; if (feature_flags_.unpremultiply_and_dither_copy) AddExtensionString("GL_CHROMIUM_unpremultiply_and_dither_copy"); feature_flags_.separate_stencil_ref_mask_writemask = !(gl_version_info_->is_d3d) && !IsWebGLContext(); if (gfx::HasExtension(extensions, "GL_MESA_framebuffer_flip_y")) { feature_flags_.mesa_framebuffer_flip_y = true; validators_.framebuffer_parameter.AddValue(GL_FRAMEBUFFER_FLIP_Y_MESA); AddExtensionString("GL_MESA_framebuffer_flip_y"); } if (is_passthrough_cmd_decoder_ && gfx::HasExtension(extensions, "GL_OVR_multiview2")) { AddExtensionString("GL_OVR_multiview2"); feature_flags_.ovr_multiview2 = true; } if (is_passthrough_cmd_decoder_ && gfx::HasExtension(extensions, "GL_KHR_parallel_shader_compile")) { AddExtensionString("GL_KHR_parallel_shader_compile"); feature_flags_.khr_parallel_shader_compile = true; validators_.g_l_state.AddValue(GL_MAX_SHADER_COMPILER_THREADS_KHR); validators_.shader_parameter.AddValue(GL_COMPLETION_STATUS_KHR); validators_.program_parameter.AddValue(GL_COMPLETION_STATUS_KHR); } if (gfx::HasExtension(extensions, "GL_KHR_robust_buffer_access_behavior")) { AddExtensionString("GL_KHR_robust_buffer_access_behavior"); feature_flags_.khr_robust_buffer_access_behavior = true; } if (!is_passthrough_cmd_decoder_ || gfx::HasExtension(extensions, "GL_ANGLE_multi_draw")) { feature_flags_.webgl_multi_draw = true; AddExtensionString("GL_WEBGL_multi_draw"); if (gfx::HasExtension(extensions, "GL_ANGLE_instanced_arrays") || feature_flags_.angle_instanced_arrays || gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile) { feature_flags_.webgl_multi_draw_instanced = true; AddExtensionString("GL_WEBGL_multi_draw_instanced"); } } if (gfx::HasExtension(extensions, "GL_NV_internalformat_sample_query")) { feature_flags_.nv_internalformat_sample_query = true; } if (gfx::HasExtension(extensions, "GL_AMD_framebuffer_multisample_advanced")) { feature_flags_.amd_framebuffer_multisample_advanced = true; AddExtensionString("GL_AMD_framebuffer_multisample_advanced"); } }
1
CVE-2016-5219
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
4,488
jabberd2
aabcffae560d5fd00cd1d2ffce5d760353cf0a4d
static void _out_verify(conn_t out, nad_t nad) { int attr, ns; jid_t from, to; conn_t in; char *rkey; int valid; attr = nad_find_attr(nad, 0, -1, "from", NULL); if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) { log_debug(ZONE, "missing or invalid from on db verify packet"); nad_free(nad); return; } attr = nad_find_attr(nad, 0, -1, "to", NULL); if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) { log_debug(ZONE, "missing or invalid to on db verify packet"); jid_free(from); nad_free(nad); return; } attr = nad_find_attr(nad, 0, -1, "id", NULL); if(attr < 0) { log_debug(ZONE, "missing id on db verify packet"); jid_free(from); jid_free(to); nad_free(nad); return; } /* get the incoming conn */ in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr)); if(in == NULL) { log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr)); jid_free(from); jid_free(to); nad_free(nad); return; } rkey = s2s_route_key(NULL, to->domain, from->domain); attr = nad_find_attr(nad, 0, -1, "type", "valid"); if(attr >= 0) { xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID); log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : ""); valid = 1; } else { log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey); valid = 0; } free(rkey); nad_free(nad); /* decrement outstanding verify counter */ --out->verify; /* let them know what happened */ nad = nad_new(); ns = nad_add_namespace(nad, uri_DIALBACK, "db"); nad_append_elem(nad, ns, "result", 0); nad_append_attr(nad, -1, "to", from->domain); nad_append_attr(nad, -1, "from", to->domain); nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid"); /* off it goes */ sx_nad_write(in->s, nad); /* if invalid, close the stream */ if (!valid) { /* generate stream error */ sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed"); /* close the incoming stream */ sx_close(in->s); } jid_free(from); jid_free(to); }
1
CVE-2012-3525
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
102
tor
57e35ad3d91724882c345ac709666a551a977f0f
networkstatus_parse_vote_from_string(const char *s, const char **eos_out, networkstatus_type_t ns_type) { smartlist_t *tokens = smartlist_create(); smartlist_t *rs_tokens = NULL, *footer_tokens = NULL; networkstatus_voter_info_t *voter = NULL; networkstatus_t *ns = NULL; digests_t ns_digests; const char *cert, *end_of_header, *end_of_footer, *s_dup = s; directory_token_t *tok; int ok; struct in_addr in; int i, inorder, n_signatures = 0; memarea_t *area = NULL, *rs_area = NULL; consensus_flavor_t flav = FLAV_NS; tor_assert(s); if (eos_out) *eos_out = NULL; if (router_get_networkstatus_v3_hashes(s, &ns_digests)) { log_warn(LD_DIR, "Unable to compute digest of network-status"); goto err; } area = memarea_new(); end_of_header = find_start_of_next_routerstatus(s); if (tokenize_string(area, s, end_of_header, tokens, (ns_type == NS_TYPE_CONSENSUS) ? networkstatus_consensus_token_table : networkstatus_token_table, 0)) { log_warn(LD_DIR, "Error tokenizing network-status vote header"); goto err; } ns = tor_malloc_zero(sizeof(networkstatus_t)); memcpy(&ns->digests, &ns_digests, sizeof(ns_digests)); tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION); tor_assert(tok); if (tok->n_args > 1) { int flavor = networkstatus_parse_flavor_name(tok->args[1]); if (flavor < 0) { log_warn(LD_DIR, "Can't parse document with unknown flavor %s", escaped(tok->args[2])); goto err; } ns->flavor = flav = flavor; } if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) { log_warn(LD_DIR, "Flavor found on non-consensus networkstatus."); goto err; } if (ns_type != NS_TYPE_CONSENSUS) { const char *end_of_cert = NULL; if (!(cert = strstr(s, "\ndir-key-certificate-version"))) goto err; ++cert; ns->cert = authority_cert_parse_from_string(cert, &end_of_cert); if (!ns->cert || !end_of_cert || end_of_cert > end_of_header) goto err; } tok = find_by_keyword(tokens, K_VOTE_STATUS); tor_assert(tok->n_args); if (!strcmp(tok->args[0], "vote")) { ns->type = NS_TYPE_VOTE; } else if (!strcmp(tok->args[0], "consensus")) { ns->type = NS_TYPE_CONSENSUS; } else if (!strcmp(tok->args[0], "opinion")) { ns->type = NS_TYPE_OPINION; } else { log_warn(LD_DIR, "Unrecognized vote status %s in network-status", escaped(tok->args[0])); goto err; } if (ns_type != ns->type) { log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus."); goto err; } if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) { tok = find_by_keyword(tokens, K_PUBLISHED); if (parse_iso_time(tok->args[0], &ns->published)) goto err; ns->supported_methods = smartlist_create(); tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS); if (tok) { for (i=0; i < tok->n_args; ++i) smartlist_add(ns->supported_methods, tor_strdup(tok->args[i])); } else { smartlist_add(ns->supported_methods, tor_strdup("1")); } } else { tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD); if (tok) { ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX, &ok, NULL); if (!ok) goto err; } else { ns->consensus_method = 1; } } tok = find_by_keyword(tokens, K_VALID_AFTER); if (parse_iso_time(tok->args[0], &ns->valid_after)) goto err; tok = find_by_keyword(tokens, K_FRESH_UNTIL); if (parse_iso_time(tok->args[0], &ns->fresh_until)) goto err; tok = find_by_keyword(tokens, K_VALID_UNTIL); if (parse_iso_time(tok->args[0], &ns->valid_until)) goto err; tok = find_by_keyword(tokens, K_VOTING_DELAY); tor_assert(tok->n_args >= 2); ns->vote_seconds = (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL); if (!ok) goto err; ns->dist_seconds = (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL); if (!ok) goto err; if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) { log_warn(LD_DIR, "Vote/consensus freshness interval is too short"); goto err; } if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) { log_warn(LD_DIR, "Vote/consensus liveness interval is too short"); goto err; } if (ns->vote_seconds < MIN_VOTE_SECONDS) { log_warn(LD_DIR, "Vote seconds is too short"); goto err; } if (ns->dist_seconds < MIN_DIST_SECONDS) { log_warn(LD_DIR, "Dist seconds is too short"); goto err; } if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) { ns->client_versions = tor_strdup(tok->args[0]); } if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) { ns->server_versions = tor_strdup(tok->args[0]); } tok = find_by_keyword(tokens, K_KNOWN_FLAGS); ns->known_flags = smartlist_create(); inorder = 1; for (i = 0; i < tok->n_args; ++i) { smartlist_add(ns->known_flags, tor_strdup(tok->args[i])); if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) { log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]); inorder = 0; } } if (!inorder) { log_warn(LD_DIR, "known-flags not in order"); goto err; } tok = find_opt_by_keyword(tokens, K_PARAMS); if (tok) { inorder = 1; ns->net_params = smartlist_create(); for (i = 0; i < tok->n_args; ++i) { int ok=0; char *eq = strchr(tok->args[i], '='); if (!eq) { log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i])); goto err; } tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL); if (!ok) { log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i])); goto err; } if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) { log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]); inorder = 0; } smartlist_add(ns->net_params, tor_strdup(tok->args[i])); } if (!inorder) { log_warn(LD_DIR, "params not in order"); goto err; } } ns->voters = smartlist_create(); SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) { tok = _tok; if (tok->tp == K_DIR_SOURCE) { tor_assert(tok->n_args >= 6); if (voter) smartlist_add(ns->voters, voter); voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t)); voter->sigs = smartlist_create(); if (ns->type != NS_TYPE_CONSENSUS) memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN); voter->nickname = tor_strdup(tok->args[0]); if (strlen(tok->args[1]) != HEX_DIGEST_LEN || base16_decode(voter->identity_digest, sizeof(voter->identity_digest), tok->args[1], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding identity digest %s in " "network-status vote.", escaped(tok->args[1])); goto err; } if (ns->type != NS_TYPE_CONSENSUS && tor_memneq(ns->cert->cache_info.identity_digest, voter->identity_digest, DIGEST_LEN)) { log_warn(LD_DIR,"Mismatch between identities in certificate and vote"); goto err; } voter->address = tor_strdup(tok->args[2]); if (!tor_inet_aton(tok->args[3], &in)) { log_warn(LD_DIR, "Error decoding IP address %s in network-status.", escaped(tok->args[3])); goto err; } voter->addr = ntohl(in.s_addr); voter->dir_port = (uint16_t) tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL); if (!ok) goto err; voter->or_port = (uint16_t) tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL); if (!ok) goto err; } else if (tok->tp == K_CONTACT) { if (!voter || voter->contact) { log_warn(LD_DIR, "contact element is out of place."); goto err; } voter->contact = tor_strdup(tok->args[0]); } else if (tok->tp == K_VOTE_DIGEST) { tor_assert(ns->type == NS_TYPE_CONSENSUS); tor_assert(tok->n_args >= 1); if (!voter || ! tor_digest_is_zero(voter->vote_digest)) { log_warn(LD_DIR, "vote-digest element is out of place."); goto err; } if (strlen(tok->args[0]) != HEX_DIGEST_LEN || base16_decode(voter->vote_digest, sizeof(voter->vote_digest), tok->args[0], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding vote digest %s in " "network-status consensus.", escaped(tok->args[0])); goto err; } } } SMARTLIST_FOREACH_END(_tok); if (voter) { smartlist_add(ns->voters, voter); voter = NULL; } if (smartlist_len(ns->voters) == 0) { log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus."); goto err; } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) { log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus."); goto err; } if (ns->type != NS_TYPE_CONSENSUS && (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) { int bad = 1; if (strlen(tok->args[0]) == HEX_DIGEST_LEN) { networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0); if (base16_decode(voter->legacy_id_digest, DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN)<0) bad = 1; else bad = 0; } if (bad) { log_warn(LD_DIR, "Invalid legacy key digest %s on vote.", escaped(tok->args[0])); } } /* Parse routerstatus lines. */ rs_tokens = smartlist_create(); rs_area = memarea_new(); s = end_of_header; ns->routerstatus_list = smartlist_create(); while (!strcmpstart(s, "r ")) { if (ns->type != NS_TYPE_CONSENSUS) { vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t)); if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns, rs, 0, 0)) smartlist_add(ns->routerstatus_list, rs); else { tor_free(rs->version); tor_free(rs); } } else { routerstatus_t *rs; if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, NULL, NULL, ns->consensus_method, flav))) smartlist_add(ns->routerstatus_list, rs); } } for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) { routerstatus_t *rs1, *rs2; if (ns->type != NS_TYPE_CONSENSUS) { vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1); vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i); rs1 = &a->status; rs2 = &b->status; } else { rs1 = smartlist_get(ns->routerstatus_list, i-1); rs2 = smartlist_get(ns->routerstatus_list, i); } if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) { log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity " "digest"); goto err; } } /* Parse footer; check signature. */ footer_tokens = smartlist_create(); if ((end_of_footer = strstr(s, "\nnetwork-status-version "))) ++end_of_footer; else end_of_footer = s + strlen(s); if (tokenize_string(area,s, end_of_footer, footer_tokens, networkstatus_vote_footer_token_table, 0)) { log_warn(LD_DIR, "Error tokenizing network-status vote footer."); goto err; } { int found_sig = 0; SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) { tok = _tok; if (tok->tp == K_DIRECTORY_SIGNATURE) found_sig = 1; else if (found_sig) { log_warn(LD_DIR, "Extraneous token after first directory-signature"); goto err; } } SMARTLIST_FOREACH_END(_tok); } if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) { if (tok != smartlist_get(footer_tokens, 0)) { log_warn(LD_DIR, "Misplaced directory-footer token"); goto err; } } tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS); if (tok) { ns->weight_params = smartlist_create(); for (i = 0; i < tok->n_args; ++i) { int ok=0; char *eq = strchr(tok->args[i], '='); if (!eq) { log_warn(LD_DIR, "Bad element '%s' in weight params", escaped(tok->args[i])); goto err; } tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL); if (!ok) { log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i])); goto err; } smartlist_add(ns->weight_params, tor_strdup(tok->args[i])); } } SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) { char declared_identity[DIGEST_LEN]; networkstatus_voter_info_t *v; document_signature_t *sig; const char *id_hexdigest = NULL; const char *sk_hexdigest = NULL; digest_algorithm_t alg = DIGEST_SHA1; tok = _tok; if (tok->tp != K_DIRECTORY_SIGNATURE) continue; tor_assert(tok->n_args >= 2); if (tok->n_args == 2) { id_hexdigest = tok->args[0]; sk_hexdigest = tok->args[1]; } else { const char *algname = tok->args[0]; int a; id_hexdigest = tok->args[1]; sk_hexdigest = tok->args[2]; a = crypto_digest_algorithm_parse_name(algname); if (a<0) { log_warn(LD_DIR, "Unknown digest algorithm %s; skipping", escaped(algname)); continue; } alg = a; } if (!tok->object_type || strcmp(tok->object_type, "SIGNATURE") || tok->object_size < 128 || tok->object_size > 512) { log_warn(LD_DIR, "Bad object type or length on directory-signature"); goto err; } if (strlen(id_hexdigest) != HEX_DIGEST_LEN || base16_decode(declared_identity, sizeof(declared_identity), id_hexdigest, HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding declared identity %s in " "network-status vote.", escaped(id_hexdigest)); goto err; } if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) { log_warn(LD_DIR, "ID on signature on network-status vote does not match " "any declared directory source."); goto err; } sig = tor_malloc_zero(sizeof(document_signature_t)); memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN); sig->alg = alg; if (strlen(sk_hexdigest) != HEX_DIGEST_LEN || base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest), sk_hexdigest, HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding declared signing key digest %s in " "network-status vote.", escaped(sk_hexdigest)); tor_free(sig); goto err; } if (ns->type != NS_TYPE_CONSENSUS) { if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest, DIGEST_LEN)) { log_warn(LD_DIR, "Digest mismatch between declared and actual on " "network-status vote."); tor_free(sig); goto err; } } if (voter_get_sig_by_algorithm(v, sig->alg)) { /* We already parsed a vote with this algorithm from this voter. Use the first one. */ log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus " "that contains two votes from the same voter with the same " "algorithm. Ignoring the second vote."); tor_free(sig); continue; } if (ns->type != NS_TYPE_CONSENSUS) { if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN, tok, ns->cert->signing_key, 0, "network-status vote")) { tor_free(sig); goto err; } sig->good_signature = 1; } else { if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) { tor_free(sig); goto err; } sig->signature = tor_memdup(tok->object_body, tok->object_size); sig->signature_len = (int) tok->object_size; } smartlist_add(v->sigs, sig); ++n_signatures; } SMARTLIST_FOREACH_END(_tok); if (! n_signatures) { log_warn(LD_DIR, "No signatures on networkstatus vote."); goto err; } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) { log_warn(LD_DIR, "Received more than one signature on a " "network-status vote."); goto err; } if (eos_out) *eos_out = end_of_footer; goto done; err: dump_desc(s_dup, "v3 networkstatus"); networkstatus_vote_free(ns); ns = NULL; done: if (tokens) { SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t)); smartlist_free(tokens); } if (voter) { if (voter->sigs) { SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig, document_signature_free(sig)); smartlist_free(voter->sigs); } tor_free(voter->nickname); tor_free(voter->address); tor_free(voter->contact); tor_free(voter); } if (rs_tokens) { SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t)); smartlist_free(rs_tokens); } if (footer_tokens) { SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t)); smartlist_free(footer_tokens); } if (area) { DUMP_AREA(area, "v3 networkstatus"); memarea_drop_all(area); } if (rs_area) memarea_drop_all(rs_area); return ns; }
1
CVE-2012-3517
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
1,369
admesh
e84d8353f1347e1f26f0a95770d92ba14e6ede38
stl_update_connects_remove_1(stl_file *stl, int facet_num) { int j; if (stl->error) return; /* Update list of connected edges */ j = ((stl->neighbors_start[facet_num].neighbor[0] == -1) + (stl->neighbors_start[facet_num].neighbor[1] == -1) + (stl->neighbors_start[facet_num].neighbor[2] == -1)); if(j == 0) { /* Facet has 3 neighbors */ stl->stats.connected_facets_3_edge -= 1; } else if(j == 1) { /* Facet has 2 neighbors */ stl->stats.connected_facets_2_edge -= 1; } else if(j == 2) { /* Facet has 1 neighbor */ stl->stats.connected_facets_1_edge -= 1; } }
1
CVE-2018-25033
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
2,950
wolfssl
23878512c65834d12811b1107d19a001478eca5d
int wc_SignatureGenerateHash_ex( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* hash_data, word32 hash_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng, int verify) { int ret; /* Suppress possible unused arg if all signature types are disabled */ (void)rng; /* Check arguments */ if (hash_data == NULL || hash_len <= 0 || sig == NULL || sig_len == NULL || *sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (needs to be at least max) */ if ((int)*sig_len < wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid hash type/len"); return ret; } ret = 0; /* Create signature using hash as data */ switch (sig_type) { case WC_SIGNATURE_TYPE_ECC: #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN) /* Create signature using provided ECC key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((ecc_key*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_ecc_sign_hash(hash_data, hash_len, sig, sig_len, rng, (ecc_key*)key); } while (ret == WC_PENDING_E); #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) /* Create signature using provided RSA key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((RsaKey*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_RsaSSL_Sign(hash_data, hash_len, sig, *sig_len, (RsaKey*)key, rng); } while (ret == WC_PENDING_E); if (ret >= 0) { *sig_len = ret; ret = 0; /* Success */ } #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_NONE: default: ret = BAD_FUNC_ARG; break; } if (ret == 0 && verify) { ret = wc_SignatureVerifyHash(hash_type, sig_type, hash_data, hash_len, sig, *sig_len, key, key_len); } return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,837
psutil
3a9bccfd2c6d2e6538298cd3892058b1204056e0
psutil_convert_ipaddr(struct sockaddr *addr, int family) { char buf[NI_MAXHOST]; int err; int addrlen; size_t n; size_t len; const char *data; char *ptr; if (addr == NULL) { Py_INCREF(Py_None); return Py_None; } else if (family == AF_INET || family == AF_INET6) { if (family == AF_INET) addrlen = sizeof(struct sockaddr_in); else addrlen = sizeof(struct sockaddr_in6); err = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST); if (err != 0) { // XXX we get here on FreeBSD when processing 'lo' / AF_INET6 // broadcast. Not sure what to do other than returning None. // ifconfig does not show anything BTW. //PyErr_Format(PyExc_RuntimeError, gai_strerror(err)); //return NULL; Py_INCREF(Py_None); return Py_None; } else { return Py_BuildValue("s", buf); } } #ifdef PSUTIL_LINUX else if (family == AF_PACKET) { struct sockaddr_ll *lladdr = (struct sockaddr_ll *)addr; len = lladdr->sll_halen; data = (const char *)lladdr->sll_addr; } #elif defined(PSUTIL_BSD) || defined(PSUTIL_OSX) else if (addr->sa_family == AF_LINK) { // Note: prior to Python 3.4 socket module does not expose // AF_LINK so we'll do. struct sockaddr_dl *dladdr = (struct sockaddr_dl *)addr; len = dladdr->sdl_alen; data = LLADDR(dladdr); } #endif else { // unknown family Py_INCREF(Py_None); return Py_None; } // AF_PACKET or AF_LINK if (len > 0) { ptr = buf; for (n = 0; n < len; ++n) { sprintf(ptr, "%02x:", data[n] & 0xff); ptr += 3; } *--ptr = '\0'; return Py_BuildValue("s", buf); } else { Py_INCREF(Py_None); return Py_None; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,737
linux
9438fabb73eb48055b58b89fc51e0bc4db22fabd
CIFSSMBSetEA(const int xid, struct cifs_tcon *tcon, const char *fileName, const char *ea_name, const void *ea_value, const __u16 ea_value_len, const struct nls_table *nls_codepage, int remap) { struct smb_com_transaction2_spi_req *pSMB = NULL; struct smb_com_transaction2_spi_rsp *pSMBr = NULL; struct fealist *parm_data; int name_len; int rc = 0; int bytes_returned = 0; __u16 params, param_offset, byte_count, offset, count; cFYI(1, "In SetEA"); SetEARetry: rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB, (void **) &pSMBr); if (rc) return rc; if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) { name_len = cifsConvertToUCS((__le16 *) pSMB->FileName, fileName, PATH_MAX, nls_codepage, remap); name_len++; /* trailing null */ name_len *= 2; } else { /* BB improve the check for buffer overruns BB */ name_len = strnlen(fileName, PATH_MAX); name_len++; /* trailing null */ strncpy(pSMB->FileName, fileName, name_len); } params = 6 + name_len; /* done calculating parms using name_len of file name, now use name_len to calculate length of ea name we are going to create in the inode xattrs */ if (ea_name == NULL) name_len = 0; else name_len = strnlen(ea_name, 255); count = sizeof(*parm_data) + ea_value_len + name_len; pSMB->MaxParameterCount = cpu_to_le16(2); /* BB find max SMB PDU from sess */ pSMB->MaxDataCount = cpu_to_le16(1000); pSMB->MaxSetupCount = 0; pSMB->Reserved = 0; pSMB->Flags = 0; pSMB->Timeout = 0; pSMB->Reserved2 = 0; param_offset = offsetof(struct smb_com_transaction2_spi_req, InformationLevel) - 4; offset = param_offset + params; pSMB->InformationLevel = cpu_to_le16(SMB_SET_FILE_EA); parm_data = (struct fealist *) (((char *) &pSMB->hdr.Protocol) + offset); pSMB->ParameterOffset = cpu_to_le16(param_offset); pSMB->DataOffset = cpu_to_le16(offset); pSMB->SetupCount = 1; pSMB->Reserved3 = 0; pSMB->SubCommand = cpu_to_le16(TRANS2_SET_PATH_INFORMATION); byte_count = 3 /* pad */ + params + count; pSMB->DataCount = cpu_to_le16(count); parm_data->list_len = cpu_to_le32(count); parm_data->list[0].EA_flags = 0; /* we checked above that name len is less than 255 */ parm_data->list[0].name_len = (__u8)name_len; /* EA names are always ASCII */ if (ea_name) strncpy(parm_data->list[0].name, ea_name, name_len); parm_data->list[0].name[name_len] = 0; parm_data->list[0].value_len = cpu_to_le16(ea_value_len); /* caller ensures that ea_value_len is less than 64K but we need to ensure that it fits within the smb */ /*BB add length check to see if it would fit in negotiated SMB buffer size BB */ /* if (ea_value_len > buffer_size - 512 (enough for header)) */ if (ea_value_len) memcpy(parm_data->list[0].name+name_len+1, ea_value, ea_value_len); pSMB->TotalDataCount = pSMB->DataCount; pSMB->ParameterCount = cpu_to_le16(params); pSMB->TotalParameterCount = pSMB->ParameterCount; pSMB->Reserved4 = 0; inc_rfc1001_len(pSMB, byte_count); pSMB->ByteCount = cpu_to_le16(byte_count); rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB, (struct smb_hdr *) pSMBr, &bytes_returned, 0); if (rc) cFYI(1, "SetPathInfo (EA) returned %d", rc); cifs_buf_release(pSMB); if (rc == -EAGAIN) goto SetEARetry; return rc; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,279
Chrome
9785a8b9672f6f35f5a401a86251c4109eda4175
void AwFeatureListCreator::SetUpFieldTrials() { auto* metrics_client = AwMetricsServiceClient::GetInstance(); DCHECK(!field_trial_list_); field_trial_list_ = std::make_unique<base::FieldTrialList>( metrics_client->CreateLowEntropyProvider()); std::unique_ptr<variations::SeedResponse> seed = GetAndClearJavaSeed(); base::Time null_time; base::Time seed_date = seed ? base::Time::FromJavaTime(seed->date) : null_time; variations::UIStringOverrider ui_string_overrider; client_ = std::make_unique<AwVariationsServiceClient>(); auto seed_store = std::make_unique<variations::VariationsSeedStore>( local_state_.get(), /*initial_seed=*/std::move(seed), /*on_initial_seed_stored=*/base::DoNothing()); if (!seed_date.is_null()) seed_store->RecordLastFetchTime(seed_date); variations_field_trial_creator_ = std::make_unique<variations::VariationsFieldTrialCreator>( local_state_.get(), client_.get(), std::move(seed_store), ui_string_overrider); variations_field_trial_creator_->OverrideVariationsPlatform( variations::Study::PLATFORM_ANDROID_WEBVIEW); std::set<std::string> unforceable_field_trials; variations::SafeSeedManager ignored_safe_seed_manager(true, local_state_.get()); variations_field_trial_creator_->SetupFieldTrials( cc::switches::kEnableGpuBenchmarking, switches::kEnableFeatures, switches::kDisableFeatures, unforceable_field_trials, std::vector<std::string>(), content::GetSwitchDependentFeatureOverrides( *base::CommandLine::ForCurrentProcess()), /*low_entropy_provider=*/nullptr, std::make_unique<base::FeatureList>(), aw_field_trials_.get(), &ignored_safe_seed_manager); }
1
CVE-2017-5072
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
988
libtasn1
f979435823a02f842c41d49cd41cc81f25b5d677
_asn1_delete_not_used (asn1_node node) { asn1_node p, p2; if (node == NULL) return ASN1_ELEMENT_NOT_FOUND; p = node; while (p) { if (p->type & CONST_NOT_USED) { p2 = NULL; if (p != node) { p2 = _asn1_find_left (p); if (!p2) p2 = _asn1_get_up (p); } asn1_delete_structure (&p); p = p2; } if (!p) break; /* reach node */ if (p->down) { p = p->down; } else { if (p == node) p = NULL; else if (p->right) p = p->right; else { while (1) { p = _asn1_get_up (p); if (p == node) { p = NULL; break; } if (p->right) { p = p->right; break; } } } } } return ASN1_SUCCESS; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,527
linux-2.6
f5fb09fa3392ad43fbcfc2f4580752f383ab5996
static void minix_read_inode(struct inode * inode) { if (INODE_VERSION(inode) == MINIX_V1) V1_minix_read_inode(inode); else V2_minix_read_inode(inode); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,325
libtasn1
5520704d075802df25ce4ffccc010ba1641bd484
_asn1_expand_object_id (asn1_node node) { asn1_node p, p2, p3, p4, p5; char name_root[ASN1_MAX_NAME_SIZE], name2[2 * ASN1_MAX_NAME_SIZE + 1]; int move, tlen; if (node == NULL) return ASN1_ELEMENT_NOT_FOUND; _asn1_str_cpy (name_root, sizeof (name_root), node->name); p = node; move = DOWN; while (!((p == node) && (move == UP))) { if (move != UP) { if ((type_field (p->type) == ASN1_ETYPE_OBJECT_ID) && (p->type & CONST_ASSIGN)) { p2 = p->down; if (p2 && (type_field (p2->type) == ASN1_ETYPE_CONSTANT)) { if (p2->value && !isdigit (p2->value[0])) { _asn1_str_cpy (name2, sizeof (name2), name_root); _asn1_str_cat (name2, sizeof (name2), "."); _asn1_str_cat (name2, sizeof (name2), (char *) p2->value); p3 = asn1_find_node (node, name2); if (!p3 || (type_field (p3->type) != ASN1_ETYPE_OBJECT_ID) || !(p3->type & CONST_ASSIGN)) return ASN1_ELEMENT_NOT_FOUND; _asn1_set_down (p, p2->right); _asn1_remove_node (p2, 0); p2 = p; p4 = p3->down; while (p4) { if (type_field (p4->type) == ASN1_ETYPE_CONSTANT) { p5 = _asn1_add_single_node (ASN1_ETYPE_CONSTANT); _asn1_set_name (p5, p4->name); if (p4->value) { tlen = _asn1_strlen (p4->value); if (tlen > 0) _asn1_set_value (p5, p4->value, tlen + 1); } if (p2 == p) { _asn1_set_right (p5, p->down); _asn1_set_down (p, p5); } else { _asn1_set_right (p5, p2->right); _asn1_set_right (p2, p5); } p2 = p5; } p4 = p4->right; } move = DOWN; continue; } } } move = DOWN; } else move = RIGHT; if (move == DOWN) { if (p->down) p = p->down; else move = RIGHT; } if (p == node) { move = UP; continue; } if (move == RIGHT) { if (p && p->right) p = p->right; else move = UP; } if (move == UP) p = _asn1_find_up (p); } /*******************************/ /* expand DEFAULT */ /*******************************/ p = node; move = DOWN; while (!((p == node) && (move == UP))) { if (move != UP) { if ((type_field (p->type) == ASN1_ETYPE_OBJECT_ID) && (p->type & CONST_DEFAULT)) { p2 = p->down; if (p2 && (type_field (p2->type) == ASN1_ETYPE_DEFAULT)) { _asn1_str_cpy (name2, sizeof (name2), name_root); _asn1_str_cat (name2, sizeof (name2), "."); _asn1_str_cat (name2, sizeof (name2), (char *) p2->value); p3 = asn1_find_node (node, name2); if (!p3 || (type_field (p3->type) != ASN1_ETYPE_OBJECT_ID) || !(p3->type & CONST_ASSIGN)) return ASN1_ELEMENT_NOT_FOUND; p4 = p3->down; name2[0] = 0; while (p4) { if (type_field (p4->type) == ASN1_ETYPE_CONSTANT) { if (p4->value == NULL) return ASN1_VALUE_NOT_FOUND; if (name2[0]) _asn1_str_cat (name2, sizeof (name2), "."); _asn1_str_cat (name2, sizeof (name2), (char *) p4->value); } p4 = p4->right; } tlen = strlen (name2); if (tlen > 0) _asn1_set_value (p2, name2, tlen + 1); } } move = DOWN; } else move = RIGHT; if (move == DOWN) { if (p->down) p = p->down; else move = RIGHT; } if (p == node) { move = UP; continue; } if (move == RIGHT) { if (p && p->right) p = p->right; else move = UP; } if (move == UP) p = _asn1_find_up (p); } return ASN1_SUCCESS; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,363
asylo
90d7619e9dd99bcdb6cd28c7649d741d254d9a1a
extern "C" bool enc_is_error_handler_set() { return error_handler != nullptr; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,484
Chrome
b2dfe7c175fb21263f06eb586f1ed235482a3281
Eina_Bool ewk_frame_reload_full(Evas_Object* ewkFrame) { EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData, false); EINA_SAFETY_ON_NULL_RETURN_VAL(smartData->frame, false); smartData->frame->loader()->reload(true); return true; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,205
linux
f647d7c155f069c1a068030255c300663516420e
int copy_thread(unsigned long clone_flags, unsigned long sp, unsigned long arg, struct task_struct *p) { int err; struct pt_regs *childregs; struct task_struct *me = current; p->thread.sp0 = (unsigned long)task_stack_page(p) + THREAD_SIZE; childregs = task_pt_regs(p); p->thread.sp = (unsigned long) childregs; p->thread.usersp = me->thread.usersp; set_tsk_thread_flag(p, TIF_FORK); p->thread.io_bitmap_ptr = NULL; savesegment(gs, p->thread.gsindex); p->thread.gs = p->thread.gsindex ? 0 : me->thread.gs; savesegment(fs, p->thread.fsindex); p->thread.fs = p->thread.fsindex ? 0 : me->thread.fs; savesegment(es, p->thread.es); savesegment(ds, p->thread.ds); memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps)); if (unlikely(p->flags & PF_KTHREAD)) { /* kernel thread */ memset(childregs, 0, sizeof(struct pt_regs)); childregs->sp = (unsigned long)childregs; childregs->ss = __KERNEL_DS; childregs->bx = sp; /* function */ childregs->bp = arg; childregs->orig_ax = -1; childregs->cs = __KERNEL_CS | get_kernel_rpl(); childregs->flags = X86_EFLAGS_IF | X86_EFLAGS_FIXED; return 0; } *childregs = *current_pt_regs(); childregs->ax = 0; if (sp) childregs->sp = sp; err = -ENOMEM; if (unlikely(test_tsk_thread_flag(me, TIF_IO_BITMAP))) { p->thread.io_bitmap_ptr = kmemdup(me->thread.io_bitmap_ptr, IO_BITMAP_BYTES, GFP_KERNEL); if (!p->thread.io_bitmap_ptr) { p->thread.io_bitmap_max = 0; return -ENOMEM; } set_tsk_thread_flag(p, TIF_IO_BITMAP); } /* * Set a new TLS for the child thread? */ if (clone_flags & CLONE_SETTLS) { #ifdef CONFIG_IA32_EMULATION if (test_thread_flag(TIF_IA32)) err = do_set_thread_area(p, -1, (struct user_desc __user *)childregs->si, 0); else #endif err = do_arch_prctl(p, ARCH_SET_FS, childregs->r8); if (err) goto out; } err = 0; out: if (err && p->thread.io_bitmap_ptr) { kfree(p->thread.io_bitmap_ptr); p->thread.io_bitmap_max = 0; } return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,935
Chrome
244c78b3f737f2cacab2d212801b0524cbcc3a7b
DeviceTokenFetcher::DeviceTokenFetcher( DeviceManagementService* service, CloudPolicyCacheBase* cache, CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler) { Initialize(service, cache, data_store, notifier, scheduler); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,180
openssl
30c22fa8b1d840036b8e203585738df62a03cec8
int EC_GROUP_copy(EC_GROUP *dest, const EC_GROUP *src) { if (dest->meth->group_copy == 0) { ECerr(EC_F_EC_GROUP_COPY, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (dest->meth != src->meth) { ECerr(EC_F_EC_GROUP_COPY, EC_R_INCOMPATIBLE_OBJECTS); return 0; } if (dest == src) return 1; dest->curve_name = src->curve_name; /* Copy precomputed */ dest->pre_comp_type = src->pre_comp_type; switch (src->pre_comp_type) { case PCT_none: dest->pre_comp.ec = NULL; break; case PCT_nistz256: #ifdef ECP_NISTZ256_ASM dest->pre_comp.nistz256 = EC_nistz256_pre_comp_dup(src->pre_comp.nistz256); #endif break; #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 case PCT_nistp224: dest->pre_comp.nistp224 = EC_nistp224_pre_comp_dup(src->pre_comp.nistp224); break; case PCT_nistp256: dest->pre_comp.nistp256 = EC_nistp256_pre_comp_dup(src->pre_comp.nistp256); break; case PCT_nistp521: dest->pre_comp.nistp521 = EC_nistp521_pre_comp_dup(src->pre_comp.nistp521); break; #else case PCT_nistp224: case PCT_nistp256: case PCT_nistp521: break; #endif case PCT_ec: dest->pre_comp.ec = EC_ec_pre_comp_dup(src->pre_comp.ec); break; } if (src->mont_data != NULL) { if (dest->mont_data == NULL) { dest->mont_data = BN_MONT_CTX_new(); if (dest->mont_data == NULL) return 0; } if (!BN_MONT_CTX_copy(dest->mont_data, src->mont_data)) return 0; } else { /* src->generator == NULL */ BN_MONT_CTX_free(dest->mont_data); dest->mont_data = NULL; } if (src->generator != NULL) { if (dest->generator == NULL) { dest->generator = EC_POINT_new(dest); if (dest->generator == NULL) return 0; } if (!EC_POINT_copy(dest->generator, src->generator)) return 0; } else { /* src->generator == NULL */ EC_POINT_clear_free(dest->generator); dest->generator = NULL; } if ((src->meth->flags & EC_FLAGS_CUSTOM_CURVE) == 0) { if (!BN_copy(dest->order, src->order)) return 0; if (!BN_copy(dest->cofactor, src->cofactor)) return 0; } dest->asn1_flag = src->asn1_flag; dest->asn1_form = src->asn1_form; if (src->seed) { OPENSSL_free(dest->seed); if ((dest->seed = OPENSSL_malloc(src->seed_len)) == NULL) { ECerr(EC_F_EC_GROUP_COPY, ERR_R_MALLOC_FAILURE); return 0; } if (!memcpy(dest->seed, src->seed, src->seed_len)) return 0; dest->seed_len = src->seed_len; } else { OPENSSL_free(dest->seed); dest->seed = NULL; dest->seed_len = 0; } return dest->meth->group_copy(dest, src); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,128
FreeRDP
795842f4096501fcefc1a7f535ccc8132feb31d7
static UINT parallel_process_irp_read(PARALLEL_DEVICE* parallel, IRP* irp) { UINT32 Length; UINT64 Offset; ssize_t status; BYTE* buffer = NULL; if (Stream_GetRemainingLength(irp->input) < 12) return ERROR_INVALID_DATA; Stream_Read_UINT32(irp->input, Length); Stream_Read_UINT64(irp->input, Offset); buffer = (BYTE*)malloc(Length); if (!buffer) { WLog_ERR(TAG, "malloc failed!"); return CHANNEL_RC_NO_MEMORY; } status = read(parallel->file, buffer, Length); if (status < 0) { irp->IoStatus = STATUS_UNSUCCESSFUL; free(buffer); buffer = NULL; Length = 0; } else { } Stream_Write_UINT32(irp->output, Length); if (Length > 0) { if (!Stream_EnsureRemainingCapacity(irp->output, Length)) { WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); free(buffer); return CHANNEL_RC_NO_MEMORY; } Stream_Write(irp->output, buffer, Length); } free(buffer); return irp->Complete(irp); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,059
Chrome
29734f46c6dc9362783091180c2ee279ad53637f
V4L2JpegEncodeAccelerator::JobRecord::JobRecord( scoped_refptr<VideoFrame> input_frame, scoped_refptr<VideoFrame> output_frame, int quality, int32_t task_id, BitstreamBuffer* exif_buffer) : input_frame(input_frame), output_frame(output_frame), quality(quality), task_id(task_id), output_shm(base::SharedMemoryHandle(), 0, true), // dummy exif_shm(nullptr) { if (exif_buffer) { exif_shm.reset(new UnalignedSharedMemory(exif_buffer->TakeRegion(), exif_buffer->size(), false)); exif_offset = exif_buffer->offset(); } }
1
CVE-2017-5101
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
3,407
libreswan
9b31deafbdbf0c2206358dfbf2d4e343e365f23f
void process_packet(struct msg_digest **mdp) { struct msg_digest *md = *mdp; struct state *st = NULL; int maj, min; enum state_kind from_state = STATE_UNDEFINED; /* state we started in */ struct isakmp_hdr *hdr; #define SEND_NOTIFICATION(t) { \ if (st) \ send_notification_from_state(st, from_state, t); \ else \ send_notification_from_md(md, t); } if (!in_struct(&md->hdr, &isakmp_hdr_desc, &md->packet_pbs, &md->message_pbs)) { /* Identify specific failures: * - bad ISAKMP major/minor version numbers */ if (md->packet_pbs.roof - md->packet_pbs.cur >= (ptrdiff_t)isakmp_hdr_desc.size) { hdr = (struct isakmp_hdr *)md->packet_pbs.cur; maj = (hdr->isa_version >> ISA_MAJ_SHIFT); min = (hdr->isa_version & ISA_MIN_MASK); if ( maj != ISAKMP_MAJOR_VERSION && maj != IKEv2_MAJOR_VERSION) { /* We don't know IKEv3+ */ SEND_NOTIFICATION(INVALID_MAJOR_VERSION); return; } else if (maj == ISAKMP_MAJOR_VERSION && min != ISAKMP_MINOR_VERSION) { /* We only know IKEv1 1.0 */ SEND_NOTIFICATION(INVALID_MINOR_VERSION); return; } /* As per RFC 4306/5996, accept unknown IKEv2 minor */ } else { libreswan_log("received packet size (%lu) is smaller than " "an IKE header - packet dropped", md->packet_pbs.roof - md->packet_pbs.cur); SEND_NOTIFICATION(PAYLOAD_MALFORMED); return; } } if (md->packet_pbs.roof < md->message_pbs.roof) { libreswan_log( "received packet size (%u) is smaller than from " "size specified in ISAKMP HDR (%u) - packet dropped", (unsigned) pbs_room(&md->packet_pbs), md->hdr.isa_length); /* abort processing corrupt packet */ return; } else if (md->packet_pbs.roof > md->message_pbs.roof) { /* * Some (old?) versions of the Cisco VPN client send an additional * 16 bytes of zero bytes - Complain but accept it */ DBG(DBG_CONTROL, { DBG_log( "size (%u) in received packet is larger than the size " "specified in ISAKMP HDR (%u) - ignoring extraneous bytes", (unsigned) pbs_room(&md->packet_pbs), md->hdr.isa_length); DBG_dump("extraneous bytes:", md->message_pbs.roof, md->packet_pbs.roof - md->message_pbs.roof); /* continue */ }); } maj = (md->hdr.isa_version >> ISA_MAJ_SHIFT); min = (md->hdr.isa_version & ISA_MIN_MASK); DBG(DBG_CONTROL, DBG_log( " processing version=%u.%u packet with exchange type=%s (%d)", maj, min, enum_name(&exchange_names_ikev1orv2, md->hdr.isa_xchg), md->hdr.isa_xchg)); switch (maj) { case ISAKMP_MAJOR_VERSION: process_v1_packet(mdp); break; case IKEv2_MAJOR_VERSION: process_v2_packet(mdp); break; default: /* * We should never get here? - above we only accept v1 or v2 */ libreswan_log("Unexpected IKE major '%d'",maj); SEND_NOTIFICATION(PAYLOAD_MALFORMED); return; } }
1
CVE-2013-4564
CWE-189
Numeric Errors
Weaknesses in this category are related to improper calculation or conversion of numbers.
Not Found in CWE Page
2,711
linux
b963a22e6d1a266a67e9eecc88134713fd54775c
static u32 apic_get_tmcct(struct kvm_lapic *apic) { ktime_t remaining; s64 ns; u32 tmcct; ASSERT(apic != NULL); /* if initial count is 0, current count should also be 0 */ if (kvm_apic_get_reg(apic, APIC_TMICT) == 0) return 0; remaining = hrtimer_get_remaining(&apic->lapic_timer.timer); if (ktime_to_ns(remaining) < 0) remaining = ktime_set(0, 0); ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period); tmcct = div64_u64(ns, (APIC_BUS_CYCLE_NS * apic->divide_count)); return tmcct; }
1
CVE-2013-6367
CWE-189
Numeric Errors
Weaknesses in this category are related to improper calculation or conversion of numbers.
Not Found in CWE Page
4,052
Pillow
f0436a4ddc954541fa10a531e2d9ea0c5ae2065d
int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = "tempfile.tif"; char *mode = "r"; TIFF *tiff; tsize_t size; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE(("in decoder: bytes %d\n", bytes)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n", im->image8, im->image32, im->image, im->block)); TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE(("Opening using fd: %d\n",clientstate->fp)); lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { TRACE(("Opening from string\n")); tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff){ TRACE(("Error, didn't get the tiff\n")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd){ int rv; uint32 ifdoffset = clientstate->ifd; TRACE(("reading tiff ifd %u\n", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv){ TRACE(("error in TIFFSetSubDirectory")); return -1; } } size = TIFFScanlineSize(tiff); TRACE(("ScanlineSize: %d \n", size)); if (size > state->bytes) { TRACE(("Error, scanline size > buffer size\n")); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } // Have to do this row by row and shove stuff into the buffer that way, // with shuffle. (or, just alloc a buffer myself, then figure out how to get it // back in. Can't use read encoded stripe. // This thing pretty much requires that I have the whole image in one shot. // Perhaps a stub version would work better??? while(state->y < state->ysize){ if (TIFFReadScanline(tiff, (tdata_t)state->buffer, (uint32)state->y, 0) == -1) { TRACE(("Decode Error, row %d\n", state->y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } /* TRACE(("Decoded row %d \n", state->y)); */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->y++; } TIFFClose(tiff); TRACE(("Done Decoding, Returning \n")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; }
1
CVE-2020-5310
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
Phase: Requirements Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol. Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. If possible, choose a language or compiler that performs automatic bounds checking. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Use libraries or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106] Phase: Implementation Strategy: Input Validation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range. Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values. Phase: Implementation Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation. Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Phase: Implementation Strategy: Compilation or Build Hardening Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
4,244
linux
f4020438fab05364018c91f7e02ebdd192085933
xfs_attr3_leaf_flipflags( struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf1; struct xfs_attr_leafblock *leaf2; struct xfs_attr_leaf_entry *entry1; struct xfs_attr_leaf_entry *entry2; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_buf *bp1; struct xfs_buf *bp2; int error; #ifdef DEBUG struct xfs_attr3_icleaf_hdr ichdr1; struct xfs_attr3_icleaf_hdr ichdr2; xfs_attr_leaf_name_local_t *name_loc; int namelen1, namelen2; char *name1, *name2; #endif /* DEBUG */ trace_xfs_attr_leaf_flipflags(args); /* * Read the block containing the "old" attr */ error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, &bp1); if (error) return error; /* * Read the block containing the "new" attr, if it is different */ if (args->blkno2 != args->blkno) { error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno2, &bp2); if (error) return error; } else { bp2 = bp1; } leaf1 = bp1->b_addr; entry1 = &xfs_attr3_leaf_entryp(leaf1)[args->index]; leaf2 = bp2->b_addr; entry2 = &xfs_attr3_leaf_entryp(leaf2)[args->index2]; #ifdef DEBUG xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr1, leaf1); ASSERT(args->index < ichdr1.count); ASSERT(args->index >= 0); xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr2, leaf2); ASSERT(args->index2 < ichdr2.count); ASSERT(args->index2 >= 0); if (entry1->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf1, args->index); namelen1 = name_loc->namelen; name1 = (char *)name_loc->nameval; } else { name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index); namelen1 = name_rmt->namelen; name1 = (char *)name_rmt->name; } if (entry2->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf2, args->index2); namelen2 = name_loc->namelen; name2 = (char *)name_loc->nameval; } else { name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2); namelen2 = name_rmt->namelen; name2 = (char *)name_rmt->name; } ASSERT(be32_to_cpu(entry1->hashval) == be32_to_cpu(entry2->hashval)); ASSERT(namelen1 == namelen2); ASSERT(memcmp(name1, name2, namelen1) == 0); #endif /* DEBUG */ ASSERT(entry1->flags & XFS_ATTR_INCOMPLETE); ASSERT((entry2->flags & XFS_ATTR_INCOMPLETE) == 0); entry1->flags &= ~XFS_ATTR_INCOMPLETE; xfs_trans_log_buf(args->trans, bp1, XFS_DA_LOGRANGE(leaf1, entry1, sizeof(*entry1))); if (args->rmtblkno) { ASSERT((entry1->flags & XFS_ATTR_LOCAL) == 0); name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index); name_rmt->valueblk = cpu_to_be32(args->rmtblkno); name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen); xfs_trans_log_buf(args->trans, bp1, XFS_DA_LOGRANGE(leaf1, name_rmt, sizeof(*name_rmt))); } entry2->flags |= XFS_ATTR_INCOMPLETE; xfs_trans_log_buf(args->trans, bp2, XFS_DA_LOGRANGE(leaf2, entry2, sizeof(*entry2))); if ((entry2->flags & XFS_ATTR_LOCAL) == 0) { name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2); name_rmt->valueblk = 0; name_rmt->valuelen = 0; xfs_trans_log_buf(args->trans, bp2, XFS_DA_LOGRANGE(leaf2, name_rmt, sizeof(*name_rmt))); } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,169
php-src
0da8b8b801f9276359262f1ef8274c7812d3dfda?w=1
static inline unsigned int get_next_char( enum entity_charset charset, const unsigned char *str, size_t str_len, size_t *cursor, int *status) { size_t pos = *cursor; unsigned int this_char = 0; *status = SUCCESS; assert(pos <= str_len); if (!CHECK_LEN(pos, 1)) MB_FAILURE(pos, 1); switch (charset) { case cs_utf_8: { /* We'll follow strategy 2. from section 3.6.1 of UTR #36: * "In a reported illegal byte sequence, do not include any * non-initial byte that encodes a valid character or is a leading * byte for a valid sequence." */ unsigned char c; c = str[pos]; if (c < 0x80) { this_char = c; pos++; } else if (c < 0xc2) { MB_FAILURE(pos, 1); } else if (c < 0xe0) { if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); if (!utf8_trail(str[pos + 1])) { MB_FAILURE(pos, utf8_lead(str[pos + 1]) ? 1 : 2); } this_char = ((c & 0x1f) << 6) | (str[pos + 1] & 0x3f); if (this_char < 0x80) { /* non-shortest form */ MB_FAILURE(pos, 2); } pos += 2; } else if (c < 0xf0) { size_t avail = str_len - pos; if (avail < 3 || !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2])) { if (avail < 2 || utf8_lead(str[pos + 1])) MB_FAILURE(pos, 1); else if (avail < 3 || utf8_lead(str[pos + 2])) MB_FAILURE(pos, 2); else MB_FAILURE(pos, 3); } this_char = ((c & 0x0f) << 12) | ((str[pos + 1] & 0x3f) << 6) | (str[pos + 2] & 0x3f); if (this_char < 0x800) { /* non-shortest form */ MB_FAILURE(pos, 3); } else if (this_char >= 0xd800 && this_char <= 0xdfff) { /* surrogate */ MB_FAILURE(pos, 3); } pos += 3; } else if (c < 0xf5) { size_t avail = str_len - pos; if (avail < 4 || !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2]) || !utf8_trail(str[pos + 3])) { if (avail < 2 || utf8_lead(str[pos + 1])) MB_FAILURE(pos, 1); else if (avail < 3 || utf8_lead(str[pos + 2])) MB_FAILURE(pos, 2); else if (avail < 4 || utf8_lead(str[pos + 3])) MB_FAILURE(pos, 3); else MB_FAILURE(pos, 4); } this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f); if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */ MB_FAILURE(pos, 4); } pos += 4; } else { MB_FAILURE(pos, 1); } } break; case cs_big5: /* reference http://demo.icu-project.org/icu-bin/convexp?conv=big5 */ { unsigned char c = str[pos]; if (c >= 0x81 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if ((next >= 0x40 && next <= 0x7E) || (next >= 0xA1 && next <= 0xFE)) { this_char = (c << 8) | next; } else { MB_FAILURE(pos, 1); } pos += 2; } else { this_char = c; pos += 1; } } break; case cs_big5hkscs: { unsigned char c = str[pos]; if (c >= 0x81 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if ((next >= 0x40 && next <= 0x7E) || (next >= 0xA1 && next <= 0xFE)) { this_char = (c << 8) | next; } else if (next != 0x80 && next != 0xFF) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else { this_char = c; pos += 1; } } break; case cs_gb2312: /* EUC-CN */ { unsigned char c = str[pos]; if (c >= 0xA1 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (gb2312_trail(next)) { this_char = (c << 8) | next; } else if (gb2312_lead(next)) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else if (gb2312_lead(c)) { this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; case cs_sjis: { unsigned char c = str[pos]; if ((c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC)) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (sjis_trail(next)) { this_char = (c << 8) | next; } else if (sjis_lead(next)) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else if (c < 0x80 || (c >= 0xA1 && c <= 0xDF)) { this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; case cs_eucjp: { unsigned char c = str[pos]; if (c >= 0xA1 && c <= 0xFE) { unsigned next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (next >= 0xA1 && next <= 0xFE) { /* this a jis kanji char */ this_char = (c << 8) | next; } else { MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); } pos += 2; } else if (c == 0x8E) { unsigned next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (next >= 0xA1 && next <= 0xDF) { /* JIS X 0201 kana */ this_char = (c << 8) | next; } else { MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); } pos += 2; } else if (c == 0x8F) { size_t avail = str_len - pos; if (avail < 3 || !(str[pos + 1] >= 0xA1 && str[pos + 1] <= 0xFE) || !(str[pos + 2] >= 0xA1 && str[pos + 2] <= 0xFE)) { if (avail < 2 || (str[pos + 1] != 0xA0 && str[pos + 1] != 0xFF)) MB_FAILURE(pos, 1); else if (avail < 3 || (str[pos + 2] != 0xA0 && str[pos + 2] != 0xFF)) MB_FAILURE(pos, 2); else MB_FAILURE(pos, 3); } else { /* JIS X 0212 hojo-kanji */ this_char = (c << 16) | (str[pos + 1] << 8) | str[pos + 2]; } pos += 3; } else if (c != 0xA0 && c != 0xFF) { /* character encoded in 1 code unit */ this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; default: /* single-byte charsets */ this_char = str[pos++]; break; } *cursor = pos; return this_char; }
1
CVE-2016-5094
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
Phase: Requirements Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol. Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. If possible, choose a language or compiler that performs automatic bounds checking. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Use libraries or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106] Phase: Implementation Strategy: Input Validation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range. Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values. Phase: Implementation Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation. Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Phase: Implementation Strategy: Compilation or Build Hardening Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
1,312
linux
0031c41be5c529f8329e327b63cde92ba1284842
void radeon_restore_bios_scratch_regs(struct radeon_device *rdev) { uint32_t scratch_reg; int i; if (rdev->family >= CHIP_R600) scratch_reg = R600_BIOS_0_SCRATCH; else scratch_reg = RADEON_BIOS_0_SCRATCH; for (i = 0; i < RADEON_BIOS_NUM_SCRATCH; i++) WREG32(scratch_reg + (i * 4), rdev->bios_scratch[i]); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,967
Chrome
8cfe2463cec6835c7b0b73dcb2ab2edaf035e3f9
void AppControllerImpl::GetApps( mojom::AppController::GetAppsCallback callback) { std::vector<chromeos::kiosk_next_home::mojom::AppPtr> app_list; app_service_proxy_->AppRegistryCache().ForEachApp( [this, &app_list](const apps::AppUpdate& update) { app_list.push_back(CreateAppPtr(update)); }); std::move(callback).Run(std::move(app_list)); }
1
CVE-2016-5183
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
9,026
Chrome
96dbafe288dbe2f0cc45fa3c39daf6d0c37acbab
_exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type) { if (dt == NULL) return 1; if ((type & XS_TIME) != XS_TIME) { dt->value.date.hour = 0; dt->value.date.min = 0; dt->value.date.sec = 0.0; } if ((type & XS_GDAY) != XS_GDAY) dt->value.date.day = 0; if ((type & XS_GMONTH) != XS_GMONTH) dt->value.date.mon = 0; if ((type & XS_GYEAR) != XS_GYEAR) dt->value.date.year = 0; dt->type = type; return 0; }
1
CVE-2016-1683
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
2,831
imageworsener
a00183107d4b84bc8a714290e824ca9c68dac738
void iwpvt_prng_destroy(struct iw_context *ctx, struct iw_prng *prng) { if(prng) iw_free(ctx,(void*)prng); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,488
libjpeg-turbo
dab6be4cfb2f9307b5378d2d1dc74d9080383dc2
static int setDecompDefaults(struct jpeg_decompress_struct *dinfo, int pixelFormat, int flags) { int retval=0; switch(pixelFormat) { case TJPF_GRAY: dinfo->out_color_space=JCS_GRAYSCALE; break; #if JCS_EXTENSIONS==1 case TJPF_RGB: dinfo->out_color_space=JCS_EXT_RGB; break; case TJPF_BGR: dinfo->out_color_space=JCS_EXT_BGR; break; case TJPF_RGBX: dinfo->out_color_space=JCS_EXT_RGBX; break; case TJPF_BGRX: dinfo->out_color_space=JCS_EXT_BGRX; break; case TJPF_XRGB: dinfo->out_color_space=JCS_EXT_XRGB; break; case TJPF_XBGR: dinfo->out_color_space=JCS_EXT_XBGR; break; #if JCS_ALPHA_EXTENSIONS==1 case TJPF_RGBA: dinfo->out_color_space=JCS_EXT_RGBA; break; case TJPF_BGRA: dinfo->out_color_space=JCS_EXT_BGRA; break; case TJPF_ARGB: dinfo->out_color_space=JCS_EXT_ARGB; break; case TJPF_ABGR: dinfo->out_color_space=JCS_EXT_ABGR; break; #endif #else case TJPF_RGB: case TJPF_BGR: case TJPF_RGBX: case TJPF_BGRX: case TJPF_XRGB: case TJPF_XBGR: case TJPF_RGBA: case TJPF_BGRA: case TJPF_ARGB: case TJPF_ABGR: dinfo->out_color_space=JCS_RGB; break; #endif case TJPF_CMYK: dinfo->out_color_space=JCS_CMYK; break; default: _throw("Unsupported pixel format"); } if(flags&TJFLAG_FASTDCT) dinfo->dct_method=JDCT_FASTEST; bailout: return retval; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,903
radare2
48f0ea79f99174fb0a62cb2354e13496ce5b7c44
RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) { if (!bin->entry_table) { return NULL; } RList *entries = r_list_newf (free); if (!entries) { return NULL; } RList *segments = r_bin_ne_get_segments (bin); if (!segments) { r_list_free (entries); return NULL; } if (bin->ne_header->csEntryPoint) { RBinAddr *entry = R_NEW0 (RBinAddr); if (!entry) { r_list_free (entries); return NULL; } entry->bits = 16; ut32 entry_cs = bin->ne_header->csEntryPoint; RBinSection *s = r_list_get_n (segments, entry_cs - 1); entry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0); r_list_append (entries, entry); } int off = 0; size_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset; while (off < bin->ne_header->EntryTableLength) { if (tableat + off >= r_buf_size (bin->buf)) { break; } ut8 bundle_length = *(ut8 *)(bin->entry_table + off); if (!bundle_length) { break; } off++; ut8 bundle_type = *(ut8 *)(bin->entry_table + off); off++; int i; for (i = 0; i < bundle_length; i++) { if (tableat + off + 4 >= r_buf_size (bin->buf)) { break; } RBinAddr *entry = R_NEW0 (RBinAddr); if (!entry) { r_list_free (entries); return NULL; } off++; if (!bundle_type) { // Skip off--; free (entry); break; } else if (bundle_type == 0xff) { // moveable off += 2; ut8 segnum = *(bin->entry_table + off); off++; if (off > bin->ne_header->EntryTableLength) { free (entry); break; } ut16 segoff = r_read_le16 (bin->entry_table + off); if (segnum > 0 && segnum < bin->ne_header->SegCount) { entry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff; } } else { // Fixed if (off + 2 >= bin->ne_header->EntryTableLength) { free (entry); break; } ut16 delta = r_read_le16 (bin->entry_table + off); if (bundle_type < bin->ne_header->SegCount) { entry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset * bin->alignment + delta; } } off += 2; r_list_append (entries, entry); } } r_list_free (segments); bin->entries = entries; return entries; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,371
openexr
5db6f7aee79e3e75e8c3780b18b28699614dd08e
lineBufferMinY (int y, int minY, int linesInLineBuffer) { return ((y - minY) / linesInLineBuffer) * linesInLineBuffer + minY; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,694
tensorflow
30721cf564cb029d34535446d6a5a6357bebc8e7
explicit EditDistanceOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("normalize", &normalize_)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,699
php-src
7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1
static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */
1
CVE-2016-5770
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
Phase: Requirements Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol. Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. If possible, choose a language or compiler that performs automatic bounds checking. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Use libraries or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106] Phase: Implementation Strategy: Input Validation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range. Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values. Phase: Implementation Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation. Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Phase: Implementation Strategy: Compilation or Build Hardening Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
9,124
linux
690b2549b19563ec5ad53e5c82f6a944d910086e
static irqreturn_t ismt_do_interrupt(int vec, void *data) { u32 val; struct ismt_priv *priv = data; /* * check to see it's our interrupt, return IRQ_NONE if not ours * since we are sharing interrupt */ val = readl(priv->smba + ISMT_MSTR_MSTS); if (!(val & (ISMT_MSTS_MIS | ISMT_MSTS_MEIS))) return IRQ_NONE; else writel(val | ISMT_MSTS_MIS | ISMT_MSTS_MEIS, priv->smba + ISMT_MSTR_MSTS); return ismt_handle_isr(priv); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,400
LuaJIT
53f82e6e2e858a0a62fd1a2ff47e9866693382e6
LJ_NOINLINE void lj_err_mem(lua_State *L) { if (L->status == LUA_ERRERR+1) /* Don't touch the stack during lua_open. */ lj_vm_unwind_c(L->cframe, LUA_ERRMEM); setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM)); lj_err_throw(L, LUA_ERRMEM); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,761
libarchive
dfd6b54ce33960e420fb206d8872fb759b577ad9
cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path is absolute"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); }
1
CVE-2016-5418
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
2,136
Chrome
62154472bd2c43e1790dd1bd8a527c1db9118d88
bool FakeCentral::IsPowered() const { switch (state_) { case mojom::CentralState::POWERED_OFF: return false; case mojom::CentralState::POWERED_ON: return true; case mojom::CentralState::ABSENT: NOTREACHED(); return false; } NOTREACHED(); return false; }
1
CVE-2017-5044
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
4,883
faad2
720f7004d6c4aabee19aad16e7c456ed76a3ebfa
uint32_t read_callback(void *user_data, void *buffer, uint32_t length) { return fread(buffer, 1, length, (FILE*)user_data); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,708
libvips
20d840e6da15c1574b3ed998bc92f91d1e36c2a5
vips_foreign_map( const char *base, VipsSListMap2Fn fn, void *a, void *b ) { GSList *files; void *result; files = NULL; (void) vips_class_map_all( g_type_from_name( base ), (VipsClassMapFn) file_add_class, (void *) &files ); files = g_slist_sort( files, (GCompareFunc) file_compare ); result = vips_slist_map2( files, fn, a, b ); g_slist_free( files ); return( result ); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,610
rsync
c8255147b06b74dad940d32f9cef5fbe17595239
static void hash_search(int f,struct sum_struct *s, struct map_struct *buf, OFF_T len) { OFF_T offset, aligned_offset, end; int32 k, want_i, aligned_i, backup; char sum2[SUM_LENGTH]; uint32 s1, s2, sum; int more; schar *map; /* want_i is used to encourage adjacent matches, allowing the RLL * coding of the output to work more efficiently. */ want_i = 0; if (verbose > 2) { rprintf(FINFO, "hash search b=%ld len=%.0f\n", (long)s->blength, (double)len); } k = (int32)MIN(len, (OFF_T)s->blength); map = (schar *)map_ptr(buf, 0, k); sum = get_checksum1((char *)map, k); s1 = sum & 0xFFFF; s2 = sum >> 16; if (verbose > 3) rprintf(FINFO, "sum=%.8x k=%ld\n", sum, (long)k); offset = aligned_offset = aligned_i = 0; end = len + 1 - s->sums[s->count-1].len; if (verbose > 3) { rprintf(FINFO, "hash search s->blength=%ld len=%.0f count=%.0f\n", (long)s->blength, (double)len, (double)s->count); } do { int done_csum2 = 0; int32 i; if (verbose > 4) { rprintf(FINFO, "offset=%.0f sum=%04x%04x\n", (double)offset, s2 & 0xFFFF, s1 & 0xFFFF); } if (tablesize == TRADITIONAL_TABLESIZE) { if ((i = hash_table[SUM2HASH2(s1,s2)]) < 0) goto null_hash; sum = (s1 & 0xffff) | (s2 << 16); } else { sum = (s1 & 0xffff) | (s2 << 16); if ((i = hash_table[BIG_SUM2HASH(sum)]) < 0) goto null_hash; } hash_hits++; do { int32 l; if (sum != s->sums[i].sum1) continue; /* also make sure the two blocks are the same length */ l = (int32)MIN((OFF_T)s->blength, len-offset); if (l != s->sums[i].len) continue; /* in-place: ensure chunk's offset is either >= our * offset or that the data didn't move. */ if (updating_basis_file && s->sums[i].offset < offset && !(s->sums[i].flags & SUMFLG_SAME_OFFSET)) continue; if (verbose > 3) { rprintf(FINFO, "potential match at %.0f i=%ld sum=%08x\n", (double)offset, (long)i, sum); } if (!done_csum2) { map = (schar *)map_ptr(buf,offset,l); get_checksum2((char *)map,l,sum2); done_csum2 = 1; } if (memcmp(sum2,s->sums[i].sum2,s->s2length) != 0) { false_alarms++; continue; } /* When updating in-place, the best possible match is * one with an identical offset, so we prefer that over * the adjacent want_i optimization. */ if (updating_basis_file) { /* All the generator's chunks start at blength boundaries. */ while (aligned_offset < offset) { aligned_offset += s->blength; aligned_i++; } if (offset == aligned_offset) { if (i != aligned_i) { if (sum != s->sums[aligned_i].sum1 || l != s->sums[aligned_i].len || memcmp(sum2, s->sums[aligned_i].sum2, s->s2length) != 0) goto check_want_i; i = aligned_i; } /* This identical chunk is in the same spot in the old and new file. */ s->sums[i].flags |= SUMFLG_SAME_OFFSET; want_i = i; } } check_want_i: /* we've found a match, but now check to see * if want_i can hint at a better match. */ if (i != want_i && want_i < s->count && (!updating_basis_file || s->sums[want_i].offset >= offset || s->sums[want_i].flags & SUMFLG_SAME_OFFSET) && sum == s->sums[want_i].sum1 && memcmp(sum2, s->sums[want_i].sum2, s->s2length) == 0) { /* we've found an adjacent match - the RLL coder * will be happy */ i = want_i; } want_i = i + 1; matched(f,s,buf,offset,i); offset += s->sums[i].len - 1; k = (int32)MIN((OFF_T)s->blength, len-offset); map = (schar *)map_ptr(buf, offset, k); sum = get_checksum1((char *)map, k); s1 = sum & 0xFFFF; s2 = sum >> 16; matches++; break; } while ((i = s->sums[i].chain) >= 0); null_hash: backup = (int32)(offset - last_match); /* We sometimes read 1 byte prior to last_match... */ if (backup < 0) backup = 0; /* Trim off the first byte from the checksum */ more = offset + k < len; map = (schar *)map_ptr(buf, offset - backup, k + more + backup) + backup; s1 -= map[0] + CHAR_OFFSET; s2 -= k * (map[0]+CHAR_OFFSET); /* Add on the next byte (if there is one) to the checksum */ if (more) { s1 += map[k] + CHAR_OFFSET; s2 += s1; } else --k; /* By matching early we avoid re-reading the data 3 times in the case where a token match comes a long way after last match. The 3 reads are caused by the running match, the checksum update and the literal send. */ if (backup >= s->blength+CHUNK_SIZE && end-offset > CHUNK_SIZE) matched(f, s, buf, offset - s->blength, -2); } while (++offset < end); matched(f, s, buf, len, -1); map_ptr(buf, len-1, 1); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,478
Chrome
fcd3a7a671ecf2d5f46ea34787d27507a914d2f5
void SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( const ModelTypeSet enabled_types) { if (initialized_ && enabled_types.Has(syncable::SESSIONS)) { WriteTransaction trans(FROM_HERE, GetUserShare()); WriteNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { LOG(WARNING) << "Unable to set 'sync_tabs' bit because Nigori node not " << "found."; return; } sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics()); specifics.set_sync_tabs(true); node.SetNigoriSpecifics(specifics); } }
1
CVE-2012-2880
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently.
Phase: Architecture and Design In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance. Phase: Architecture and Design Use thread-safe capabilities such as the data access abstraction in Spring. Phase: Architecture and Design Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring. Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400). Phase: Implementation When using multithreading and operating on shared variables, only use thread-safe functions. Phase: Implementation Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write. Phase: Implementation Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412. Phase: Implementation Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization. Phase: Implementation Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop. Phase: Implementation Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help. Phases: Architecture and Design; Operation Strategy: Environment Hardening Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations
2,807
linux
85dfb745ee40232876663ae206cba35f24ab2a40
static int key_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; if (c->data.byid && c->event == XFRM_MSG_DELPOLICY) out_hdr->sadb_msg_type = SADB_X_SPDDELETE2; else out_hdr->sadb_msg_type = event2poltype(c->event); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = c->seq; out_hdr->sadb_msg_pid = c->portid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xp_net(xp)); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,788
Chrome
dc7b094a338c6c521f918f478e993f0f74bbea0d
static void RegisterPropertiesHandler( void* object, const ImePropertyList& prop_list) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->RegisterProperties(prop_list); }
1
CVE-2011-2804
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
3,890
ntopng
01f47e04fd7c8d54399c9e465f823f0017069f8f
void lua_push_nil_table_entry(lua_State *L, const char *key) { if(L) { lua_pushstring(L, key); lua_pushnil(L); lua_settable(L, -3); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,263
linux
594cc251fdd0d231d342d88b2fdff4bc42fb0690
static inline u64 gen8_noncanonical_addr(u64 address) { return address & GENMASK_ULL(GEN8_HIGH_ADDRESS_BIT, 0); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,210
ImageMagick
d23beebe7b1179fb75db1e85fbca3100e49593d9
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,"wb"); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MaxTextExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf("Detected:%s \n",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent); /* Read nested image */ /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickString(image2->filename,image->filename,MaxTextExtent); (void) CopyMagickString(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickString(image2->magick,image->magick,MaxTextExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); }
1
CVE-2016-10145
CWE-189
Numeric Errors
Weaknesses in this category are related to improper calculation or conversion of numbers.
Not Found in CWE Page
6,523
Android
f22c2a0f0f9e030c240468d9d18b9297f001bcf0
OMX_ERRORTYPE omx_vdec::set_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_IN OMX_PTR paramData) { OMX_ERRORTYPE eRet = OMX_ErrorNone; int ret=0; struct v4l2_format fmt; #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; #endif if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Set Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_ERROR("Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } if ((m_state != OMX_StateLoaded) && BITMASK_ABSENT(&m_flags,OMX_COMPONENT_OUTPUT_ENABLE_PENDING) && (m_out_bEnabled == OMX_TRUE) && BITMASK_ABSENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING) && (m_inp_bEnabled == OMX_TRUE)) { DEBUG_PRINT_ERROR("Set Param in Invalid State"); return OMX_ErrorIncorrectStateOperation; } switch ((unsigned long)paramIndex) { case OMX_IndexParamPortDefinition: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_PORTDEFINITIONTYPE); OMX_PARAM_PORTDEFINITIONTYPE *portDefn; portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d", (int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nFrameWidth); if (OMX_DirOutput == portDefn->eDir) { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition OP port"); bool port_format_changed = false; m_display_id = portDefn->format.video.pNativeWindow; unsigned int buffer_size; /* update output port resolution with client supplied dimensions in case scaling is enabled, else it follows input resolution set */ if (is_down_scalar_enabled) { DEBUG_PRINT_LOW("SetParam OP: WxH(%u x %u)", (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight); if (portDefn->format.video.nFrameHeight != 0x0 && portDefn->format.video.nFrameWidth != 0x0) { memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Get Resolution failed"); eRet = OMX_ErrorHardware; break; } if ((portDefn->format.video.nFrameHeight != (unsigned int)fmt.fmt.pix_mp.height) || (portDefn->format.video.nFrameWidth != (unsigned int)fmt.fmt.pix_mp.width)) { port_format_changed = true; } update_resolution(portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight, portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight); /* set crop info */ rectangle.nLeft = 0; rectangle.nTop = 0; rectangle.nWidth = portDefn->format.video.nFrameWidth; rectangle.nHeight = portDefn->format.video.nFrameHeight; eRet = is_video_session_supported(); if (eRet) break; memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = capture_capability; DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d", fmt.fmt.pix_mp.height, fmt.fmt.pix_mp.width); ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set Resolution failed"); eRet = OMX_ErrorUnsupportedSetting; } else eRet = get_buffer_req(&drv_ctx.op_buf); } if (eRet) { break; } if (secure_mode) { struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_SECURE_SCALING_THRESHOLD; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting secure scaling threshold : %d, id was : %x", errno, control.id); eRet = OMX_ErrorHardware; } else { /* This is a workaround for a bug in fw which uses stride * and slice instead of width and height to check against * the threshold. */ OMX_U32 stride, slice; if (drv_ctx.output_format == VDEC_YUV_FORMAT_NV12) { stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, portDefn->format.video.nFrameWidth); slice = VENUS_Y_SCANLINES(COLOR_FMT_NV12, portDefn->format.video.nFrameHeight); } else { stride = portDefn->format.video.nFrameWidth; slice = portDefn->format.video.nFrameHeight; } DEBUG_PRINT_LOW("Stride is %d, slice is %d, sxs is %d\n", stride, slice, stride * slice); DEBUG_PRINT_LOW("Threshold value is %d\n", control.value); if (stride * slice <= (OMX_U32)control.value) { secure_scaling_to_non_secure_opb = true; DEBUG_PRINT_HIGH("Enabling secure scalar out of CPZ"); control.id = V4L2_CID_MPEG_VIDC_VIDEO_NON_SECURE_OUTPUT2; control.value = 1; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Enabling non-secure output2 failed"); eRet = OMX_ErrorUnsupportedSetting; } } } } } if (eRet) { break; } if (!client_buffers.get_buffer_req(buffer_size)) { DEBUG_PRINT_ERROR("Error in getting buffer requirements"); eRet = OMX_ErrorBadParameter; } else if (!port_format_changed) { if ( portDefn->nBufferCountActual >= drv_ctx.op_buf.mincount && portDefn->nBufferSize >= drv_ctx.op_buf.buffer_size ) { drv_ctx.op_buf.actualcount = portDefn->nBufferCountActual; drv_ctx.op_buf.buffer_size = portDefn->nBufferSize; drv_ctx.extradata_info.count = drv_ctx.op_buf.actualcount; drv_ctx.extradata_info.size = drv_ctx.extradata_info.count * drv_ctx.extradata_info.buffer_size; eRet = set_buffer_req(&drv_ctx.op_buf); if (eRet == OMX_ErrorNone) m_port_def = *portDefn; } else { DEBUG_PRINT_ERROR("ERROR: OP Requirements(#%d: %u) Requested(#%u: %u)", drv_ctx.op_buf.mincount, (unsigned int)drv_ctx.op_buf.buffer_size, (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; } } } else if (OMX_DirInput == portDefn->eDir) { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition IP port"); bool port_format_changed = false; if ((portDefn->format.video.xFramerate >> 16) > 0 && (portDefn->format.video.xFramerate >> 16) <= MAX_SUPPORTED_FPS) { DEBUG_PRINT_HIGH("set_parameter: frame rate set by omx client : %u", (unsigned int)portDefn->format.video.xFramerate >> 16); Q16ToFraction(portDefn->format.video.xFramerate, drv_ctx.frame_rate.fps_numerator, drv_ctx.frame_rate.fps_denominator); if (!drv_ctx.frame_rate.fps_numerator) { DEBUG_PRINT_ERROR("Numerator is zero setting to 30"); drv_ctx.frame_rate.fps_numerator = 30; } if (drv_ctx.frame_rate.fps_denominator) drv_ctx.frame_rate.fps_numerator = (int) drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator; drv_ctx.frame_rate.fps_denominator = 1; frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 / drv_ctx.frame_rate.fps_numerator; DEBUG_PRINT_LOW("set_parameter: frm_int(%u) fps(%.2f)", (unsigned int)frm_int, drv_ctx.frame_rate.fps_numerator / (float)drv_ctx.frame_rate.fps_denominator); struct v4l2_outputparm oparm; /*XXX: we're providing timing info as seconds per frame rather than frames * per second.*/ oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator; oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator; struct v4l2_streamparm sparm; sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; sparm.parm.output = oparm; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) { DEBUG_PRINT_ERROR("Unable to convey fps info to driver, performance might be affected"); eRet = OMX_ErrorHardware; break; } } if (drv_ctx.video_resolution.frame_height != portDefn->format.video.nFrameHeight || drv_ctx.video_resolution.frame_width != portDefn->format.video.nFrameWidth) { DEBUG_PRINT_LOW("SetParam IP: WxH(%u x %u)", (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight); port_format_changed = true; OMX_U32 frameWidth = portDefn->format.video.nFrameWidth; OMX_U32 frameHeight = portDefn->format.video.nFrameHeight; if (frameHeight != 0x0 && frameWidth != 0x0) { if (m_smoothstreaming_mode && ((frameWidth * frameHeight) < (m_smoothstreaming_width * m_smoothstreaming_height))) { frameWidth = m_smoothstreaming_width; frameHeight = m_smoothstreaming_height; DEBUG_PRINT_LOW("NOTE: Setting resolution %u x %u " "for adaptive-playback/smooth-streaming", (unsigned int)frameWidth, (unsigned int)frameHeight); } update_resolution(frameWidth, frameHeight, frameWidth, frameHeight); eRet = is_video_session_supported(); if (eRet) break; memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = output_capability; DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d",fmt.fmt.pix_mp.height,fmt.fmt.pix_mp.width); ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set Resolution failed"); eRet = OMX_ErrorUnsupportedSetting; } else { if (!is_down_scalar_enabled) eRet = get_buffer_req(&drv_ctx.op_buf); } } } if (m_custom_buffersize.input_buffersize && (portDefn->nBufferSize > m_custom_buffersize.input_buffersize)) { DEBUG_PRINT_ERROR("ERROR: Custom buffer size set by client: %d, trying to set: %d", m_custom_buffersize.input_buffersize, portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; break; } if (portDefn->nBufferCountActual >= drv_ctx.ip_buf.mincount || portDefn->nBufferSize != drv_ctx.ip_buf.buffer_size) { port_format_changed = true; vdec_allocatorproperty *buffer_prop = &drv_ctx.ip_buf; drv_ctx.ip_buf.actualcount = portDefn->nBufferCountActual; drv_ctx.ip_buf.buffer_size = (portDefn->nBufferSize + buffer_prop->alignment - 1) & (~(buffer_prop->alignment - 1)); eRet = set_buffer_req(buffer_prop); } if (false == port_format_changed) { DEBUG_PRINT_ERROR("ERROR: IP Requirements(#%d: %u) Requested(#%u: %u)", drv_ctx.ip_buf.mincount, (unsigned int)drv_ctx.ip_buf.buffer_size, (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; } } else if (portDefn->eDir == OMX_DirMax) { DEBUG_PRINT_ERROR(" Set_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } } break; case OMX_IndexParamVideoPortFormat: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE); OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; int ret=0; struct v4l2_format fmt; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat 0x%x, port: %u", portFmt->eColorFormat, (unsigned int)portFmt->nPortIndex); memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (1 == portFmt->nPortIndex) { fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = capture_capability; enum vdec_output_fromat op_format; if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m || portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView || portFmt->eColorFormat == OMX_COLOR_FormatYUV420Planar || portFmt->eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) op_format = (enum vdec_output_fromat)VDEC_YUV_FORMAT_NV12; else eRet = OMX_ErrorBadParameter; if (eRet == OMX_ErrorNone) { drv_ctx.output_format = op_format; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set output format failed"); eRet = OMX_ErrorUnsupportedSetting; /*TODO: How to handle this case */ } else { eRet = get_buffer_req(&drv_ctx.op_buf); } } if (eRet == OMX_ErrorNone) { if (!client_buffers.set_color_format(portFmt->eColorFormat)) { DEBUG_PRINT_ERROR("Set color format failed"); eRet = OMX_ErrorBadParameter; } } } } break; case OMX_QcomIndexPortDefn: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PARAM_PORTDEFINITIONTYPE); OMX_QCOM_PARAM_PORTDEFINITIONTYPE *portFmt = (OMX_QCOM_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexQcomParamPortDefinitionType %u", (unsigned int)portFmt->nFramePackingFormat); /* Input port */ if (portFmt->nPortIndex == 0) { if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_Arbitrary) { if (secure_mode) { arbitrary_bytes = false; DEBUG_PRINT_ERROR("setparameter: cannot set to arbitary bytes mode in secure session"); eRet = OMX_ErrorUnsupportedSetting; } else { arbitrary_bytes = true; } } else if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_OnlyOneCompleteFrame) { arbitrary_bytes = false; #ifdef _ANDROID_ property_get("vidc.dec.debug.arbitrarybytes.mode", property_value, "0"); if (atoi(property_value)) { DEBUG_PRINT_HIGH("arbitrary_bytes enabled via property command"); arbitrary_bytes = true; } #endif } else { DEBUG_PRINT_ERROR("Setparameter: unknown FramePacking format %u", (unsigned int)portFmt->nFramePackingFormat); eRet = OMX_ErrorUnsupportedSetting; } } else if (portFmt->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port"); if ( (portFmt->nMemRegion > OMX_QCOM_MemRegionInvalid && portFmt->nMemRegion < OMX_QCOM_MemRegionMax) && portFmt->nCacheAttr == OMX_QCOM_CacheAttrNone) { m_out_mem_region_smi = OMX_TRUE; if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) { DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port: out pmem set"); m_use_output_pmem = OMX_TRUE; } } } } break; case OMX_IndexParamStandardComponentRole: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_COMPONENTROLETYPE); OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s", comp_role->cRole); if ((m_state == OMX_StateLoaded)&& !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.h263",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if ((!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx",OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx311", OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx4", OMX_MAX_STRINGNAME_SIZE)) ) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if ( (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.wmv",OMX_MAX_STRINGNAME_SIZE)) ) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE) || (!strncmp((const char*)comp_role->cRole,"video_decoder.vpx",OMX_MAX_STRINGNAME_SIZE))) { strlcpy((char*)m_cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("Setparameter: unknown param %s", drv_ctx.kind); eRet = OMX_ErrorInvalidComponentName; } break; } case OMX_IndexParamPriorityMgmt: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE); if (m_state != OMX_StateLoaded) { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u", (unsigned int)priorityMgmtype->nGroupID); DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u", (unsigned int)priorityMgmtype->nGroupPriority); m_priority_mgm.nGroupID = priorityMgmtype->nGroupID; m_priority_mgm.nGroupPriority = priorityMgmtype->nGroupPriority; break; } case OMX_IndexParamCompBufferSupplier: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE); OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d", bufferSupplierType->eBufferSupplier); if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1) m_buffer_supplier.eBufferSupplier = bufferSupplierType->eBufferSupplier; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoAvc: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc %d", paramIndex); break; } case (OMX_INDEXTYPE)QOMX_IndexParamVideoMvc: { DEBUG_PRINT_LOW("set_parameter: QOMX_IndexParamVideoMvc %d", paramIndex); break; } case OMX_IndexParamVideoH263: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263 %d", paramIndex); break; } case OMX_IndexParamVideoMpeg4: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4 %d", paramIndex); break; } case OMX_IndexParamVideoMpeg2: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg2 %d", paramIndex); break; } case OMX_QcomIndexParamVideoDecoderPictureOrder: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_DECODER_PICTURE_ORDER); QOMX_VIDEO_DECODER_PICTURE_ORDER *pictureOrder = (QOMX_VIDEO_DECODER_PICTURE_ORDER *)paramData; struct v4l2_control control; int pic_order,rc=0; DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoDecoderPictureOrder %d", pictureOrder->eOutputPictureOrder); if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DISPLAY_ORDER) { pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DISPLAY; } else if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DECODE_ORDER) { pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE; time_stamp_dts.set_timestamp_reorder_mode(false); } else eRet = OMX_ErrorBadParameter; if (eRet == OMX_ErrorNone) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER; control.value = pic_order; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Set picture order failed"); eRet = OMX_ErrorUnsupportedSetting; } } break; } case OMX_QcomIndexParamConcealMBMapExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(VDEC_EXTRADATA_MB_ERROR_MAP, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamFrameInfoExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_ExtraDataFrameDimension: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEDIMENSION_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamInterlaceExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_INTERLACE_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamH264TimeInfo: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_TIMEINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoFramePackingExtradata: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEPACK_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoQPExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_QP_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoInputBitsInfoExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_BITSINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexEnableExtnUserData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_EXTNUSER_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamMpeg2SeqDispExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_MPEG2SEQDISP_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoDivx: { QOMX_VIDEO_PARAM_DIVXTYPE* divXType = (QOMX_VIDEO_PARAM_DIVXTYPE *) paramData; } break; case OMX_QcomIndexPlatformPvt: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PLATFORMPRIVATE_EXTN); DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port"); OMX_QCOM_PLATFORMPRIVATE_EXTN* entryType = (OMX_QCOM_PLATFORMPRIVATE_EXTN *) paramData; if (entryType->type != OMX_QCOM_PLATFORM_PRIVATE_PMEM) { DEBUG_PRINT_HIGH("set_parameter: Platform Private entry type (%d) not supported.", entryType->type); eRet = OMX_ErrorUnsupportedSetting; } else { m_out_pvt_entry_pmem = OMX_TRUE; if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port: out pmem set"); m_use_output_pmem = OMX_TRUE; } } } break; case OMX_QcomIndexParamVideoSyncFrameDecodingMode: { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoSyncFrameDecodingMode"); DEBUG_PRINT_HIGH("set idr only decoding for thumbnail mode"); struct v4l2_control control; int rc; drv_ctx.idr_only_decoding = 1; control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER; control.value = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Set picture order failed"); eRet = OMX_ErrorUnsupportedSetting; } else { control.id = V4L2_CID_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE; control.value = V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_ENABLE; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Sync frame setting failed"); eRet = OMX_ErrorUnsupportedSetting; } /*Setting sync frame decoding on driver might change buffer * requirements so update them here*/ if (get_buffer_req(&drv_ctx.ip_buf)) { DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer i/p requirements"); eRet = OMX_ErrorUnsupportedSetting; } if (get_buffer_req(&drv_ctx.op_buf)) { DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer o/p requirements"); eRet = OMX_ErrorUnsupportedSetting; } } } break; case OMX_QcomIndexParamIndexExtraDataType: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXEXTRADATATYPE); QOMX_INDEXEXTRADATATYPE *extradataIndexType = (QOMX_INDEXEXTRADATATYPE *) paramData; if ((extradataIndexType->nIndex == OMX_IndexParamPortDefinition) && (extradataIndexType->bEnabled == OMX_TRUE) && (extradataIndexType->nPortIndex == 1)) { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType SmoothStreaming"); eRet = enable_extradata(OMX_PORTDEF_EXTRADATA, false, extradataIndexType->bEnabled); } } break; case OMX_QcomIndexParamEnableSmoothStreaming: { #ifndef SMOOTH_STREAMING_DISABLED eRet = enable_smoothstreaming(); #else eRet = OMX_ErrorUnsupportedSetting; #endif } break; #if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_) /* Need to allow following two set_parameters even in Idle * state. This is ANDROID architecture which is not in sync * with openmax standard. */ case OMX_GoogleAndroidIndexEnableAndroidNativeBuffers: { VALIDATE_OMX_PARAM_DATA(paramData, EnableAndroidNativeBuffersParams); EnableAndroidNativeBuffersParams* enableNativeBuffers = (EnableAndroidNativeBuffersParams *) paramData; if (enableNativeBuffers) { m_enable_android_native_buffers = enableNativeBuffers->enable; } #if !defined(FLEXYUV_SUPPORTED) if (m_enable_android_native_buffers) { if(!client_buffers.set_color_format(getPreferredColorFormatDefaultMode(0))) { DEBUG_PRINT_ERROR("Failed to set native color format!"); eRet = OMX_ErrorUnsupportedSetting; } } #endif } break; case OMX_GoogleAndroidIndexUseAndroidNativeBuffer: { VALIDATE_OMX_PARAM_DATA(paramData, UseAndroidNativeBufferParams); eRet = use_android_native_buffer(hComp, paramData); } break; #endif case OMX_QcomIndexParamEnableTimeStampReorder: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXTIMESTAMPREORDER); QOMX_INDEXTIMESTAMPREORDER *reorder = (QOMX_INDEXTIMESTAMPREORDER *)paramData; if (drv_ctx.picture_order == (vdec_output_order)QOMX_VIDEO_DISPLAY_ORDER) { if (reorder->bEnable == OMX_TRUE) { frm_int =0; time_stamp_dts.set_timestamp_reorder_mode(true); } else time_stamp_dts.set_timestamp_reorder_mode(false); } else { time_stamp_dts.set_timestamp_reorder_mode(false); if (reorder->bEnable == OMX_TRUE) { eRet = OMX_ErrorUnsupportedSetting; } } } break; case OMX_IndexParamVideoProfileLevelCurrent: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE); OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; if (pParam) { m_profile_lvl.eProfile = pParam->eProfile; m_profile_lvl.eLevel = pParam->eLevel; } break; } case OMX_QcomIndexParamVideoMetaBufferMode: { VALIDATE_OMX_PARAM_DATA(paramData, StoreMetaDataInBuffersParams); StoreMetaDataInBuffersParams *metabuffer = (StoreMetaDataInBuffersParams *)paramData; if (!metabuffer) { DEBUG_PRINT_ERROR("Invalid param: %p", metabuffer); eRet = OMX_ErrorBadParameter; break; } if (m_disable_dynamic_buf_mode) { DEBUG_PRINT_HIGH("Dynamic buffer mode disabled by setprop"); eRet = OMX_ErrorUnsupportedSetting; break; } if (metabuffer->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { struct v4l2_control control; struct v4l2_format fmt; control.id = V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_OUTPUT; if (metabuffer->bStoreMetaData == true) { control.value = V4L2_MPEG_VIDC_VIDEO_DYNAMIC; } else { control.value = V4L2_MPEG_VIDC_VIDEO_STATIC; } int rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL,&control); if (!rc) { DEBUG_PRINT_HIGH("%s buffer mode", (metabuffer->bStoreMetaData == true)? "Enabled dynamic" : "Disabled dynamic"); dynamic_buf_mode = metabuffer->bStoreMetaData; } else { DEBUG_PRINT_ERROR("Failed to %s buffer mode", (metabuffer->bStoreMetaData == true)? "enable dynamic" : "disable dynamic"); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR( "OMX_QcomIndexParamVideoMetaBufferMode not supported for port: %u", (unsigned int)metabuffer->nPortIndex); eRet = OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamVideoDownScalar: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXDOWNSCALAR); QOMX_INDEXDOWNSCALAR* pParam = (QOMX_INDEXDOWNSCALAR*)paramData; struct v4l2_control control; int rc; if (pParam) { is_down_scalar_enabled = pParam->bEnable; if (is_down_scalar_enabled) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE; control.value = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY; DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoDownScalar value = %d", pParam->bEnable); rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc < 0) { DEBUG_PRINT_ERROR("Failed to set down scalar on driver."); eRet = OMX_ErrorUnsupportedSetting; } control.id = V4L2_CID_MPEG_VIDC_VIDEO_KEEP_ASPECT_RATIO; control.value = 1; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc < 0) { DEBUG_PRINT_ERROR("Failed to set keep aspect ratio on driver."); eRet = OMX_ErrorUnsupportedSetting; } } } break; } #ifdef ADAPTIVE_PLAYBACK_SUPPORTED case OMX_QcomIndexParamVideoAdaptivePlaybackMode: { VALIDATE_OMX_PARAM_DATA(paramData, PrepareForAdaptivePlaybackParams); DEBUG_PRINT_LOW("set_parameter: OMX_GoogleAndroidIndexPrepareForAdaptivePlayback"); PrepareForAdaptivePlaybackParams* pParams = (PrepareForAdaptivePlaybackParams *) paramData; if (pParams->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { if (!pParams->bEnable) { return OMX_ErrorNone; } if (pParams->nMaxFrameWidth > maxSmoothStreamingWidth || pParams->nMaxFrameHeight > maxSmoothStreamingHeight) { DEBUG_PRINT_ERROR( "Adaptive playback request exceeds max supported resolution : [%u x %u] vs [%u x %u]", (unsigned int)pParams->nMaxFrameWidth, (unsigned int)pParams->nMaxFrameHeight, (unsigned int)maxSmoothStreamingWidth, (unsigned int)maxSmoothStreamingHeight); eRet = OMX_ErrorBadParameter; } else { eRet = enable_adaptive_playback(pParams->nMaxFrameWidth, pParams->nMaxFrameHeight); } } else { DEBUG_PRINT_ERROR( "Prepare for adaptive playback supported only on output port"); eRet = OMX_ErrorBadParameter; } break; } #endif case OMX_QcomIndexParamVideoCustomBufferSize: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_CUSTOM_BUFFERSIZE); DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoCustomBufferSize"); QOMX_VIDEO_CUSTOM_BUFFERSIZE* pParam = (QOMX_VIDEO_CUSTOM_BUFFERSIZE*)paramData; if (pParam->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) { struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_BUFFER_SIZE_LIMIT; control.value = pParam->nBufferSize; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) { DEBUG_PRINT_ERROR("Failed to set input buffer size"); eRet = OMX_ErrorUnsupportedSetting; } else { eRet = get_buffer_req(&drv_ctx.ip_buf); if (eRet == OMX_ErrorNone) { m_custom_buffersize.input_buffersize = drv_ctx.ip_buf.buffer_size; DEBUG_PRINT_HIGH("Successfully set custom input buffer size = %d", m_custom_buffersize.input_buffersize); } else { DEBUG_PRINT_ERROR("Failed to get buffer requirement"); } } } else { DEBUG_PRINT_ERROR("ERROR: Custom buffer size in not supported on output port"); eRet = OMX_ErrorBadParameter; } break; } default: { DEBUG_PRINT_ERROR("Setparameter: unknown param %d", paramIndex); eRet = OMX_ErrorUnsupportedIndex; } } if (eRet != OMX_ErrorNone) DEBUG_PRINT_ERROR("set_parameter: Error: 0x%x, setting param 0x%x", eRet, paramIndex); return eRet; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,713
ImageMagick
30ccf9a0da1f47161b5935a95be854fe84e6c2a2
static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info, TIFF *tiff,TIFFInfo *tiff_info) { #define TIFFStripSizeDefault 1048576 const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) memset(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) { size_t extent; uint32 rows, rows_per_strip; extent=TIFFScanlineSize(tiff); rows_per_strip=TIFFStripSizeDefault/(extent == 0 ? 1 : (uint32) extent); rows_per_strip=16*(((rows_per_strip < 16 ? 16 : rows_per_strip)+1)/16); if ((TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows) == 1) && (rows_per_strip > rows)) rows_per_strip=rows; option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(uint32) strtoul(option,(char **) NULL,10); rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); return(MagickTrue); } /* Create tiled TIFF, ignore "tiff:rows-per-strip". */ flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; if ((TIFFScanlineSize(tiff) <= 0) || (TIFFTileSize(tiff) <= 0)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,968
vim
dc5490e2cbc8c16022a23b449b48c1bd0083f366
ex_copy(linenr_T line1, linenr_T line2, linenr_T n) { linenr_T count; char_u *p; count = line2 - line1 + 1; if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { curbuf->b_op_start.lnum = n + 1; curbuf->b_op_end.lnum = n + count; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; } /* * there are three situations: * 1. destination is above line1 * 2. destination is between line1 and line2 * 3. destination is below line2 * * n = destination (when starting) * curwin->w_cursor.lnum = destination (while copying) * line1 = start of source (while copying) * line2 = end of source (while copying) */ if (u_save(n, n + 1) == FAIL) return; curwin->w_cursor.lnum = n; while (line1 <= line2) { // need to use vim_strsave() because the line will be unlocked within // ml_append() p = vim_strsave(ml_get(line1)); if (p != NULL) { ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE); vim_free(p); } // situation 2: skip already copied lines if (line1 == n) line1 = curwin->w_cursor.lnum; ++line1; if (curwin->w_cursor.lnum < line1) ++line1; if (curwin->w_cursor.lnum < line2) ++line2; ++curwin->w_cursor.lnum; } appended_lines_mark(n, count); msgmore((long)count); }
1
CVE-2022-0361
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
6,038
ImageMagick
65f75a32a93ae4044c528a987a68366ecd4b46b9
ModuleExport size_t RegisterTGAImage(void) { MagickInfo *entry; entry=SetMagickInfo("ICB"); entry->decoder=(DecodeImageHandler *) ReadTGAImage; entry->encoder=(EncodeImageHandler *) WriteTGAImage; entry->adjoin=MagickFalse; entry->description=ConstantString("Truevision Targa image"); entry->module=ConstantString("TGA"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TGA"); entry->decoder=(DecodeImageHandler *) ReadTGAImage; entry->encoder=(EncodeImageHandler *) WriteTGAImage; entry->adjoin=MagickFalse; entry->description=ConstantString("Truevision Targa image"); entry->module=ConstantString("TGA"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("VDA"); entry->decoder=(DecodeImageHandler *) ReadTGAImage; entry->encoder=(EncodeImageHandler *) WriteTGAImage; entry->adjoin=MagickFalse; entry->description=ConstantString("Truevision Targa image"); entry->module=ConstantString("TGA"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("VST"); entry->decoder=(DecodeImageHandler *) ReadTGAImage; entry->encoder=(EncodeImageHandler *) WriteTGAImage; entry->adjoin=MagickFalse; entry->description=ConstantString("Truevision Targa image"); entry->module=ConstantString("TGA"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,525
Android
5a9753fca56f0eeb9f61e342b2fccffc364f9426
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); } if (cfg_.ts_number_layers > 1) { if (video->frame() == 1) { encoder->Control(VP9E_SET_SVC, 1); } vpx_svc_layer_id_t layer_id = {0, 0}; layer_id.spatial_layer_id = 0; frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers); layer_id.temporal_layer_id = SetLayerId(video->frame(), cfg_.ts_number_layers); if (video->frame() > 0) { encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id); } } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; }
1
CVE-2016-1621
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
1,596
yara
992480c30f75943e9cd6245bb2015c7737f9b661
int yr_re_fast_exec( uint8_t* code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args, int* matches) { RE_REPEAT_ANY_ARGS* repeat_any_args; uint8_t* code_stack[MAX_FAST_RE_STACK]; uint8_t* input_stack[MAX_FAST_RE_STACK]; int matches_stack[MAX_FAST_RE_STACK]; uint8_t* ip = code; uint8_t* input = input_data; uint8_t* next_input; uint8_t* next_opcode; uint8_t mask; uint8_t value; int i; int stop; int input_incr; int sp = 0; int bytes_matched; int max_bytes_matched; max_bytes_matched = flags & RE_FLAGS_BACKWARDS ? (int) input_backwards_size : (int) input_forwards_size; input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1; if (flags & RE_FLAGS_BACKWARDS) input--; code_stack[sp] = code; input_stack[sp] = input; matches_stack[sp] = 0; sp++; while (sp > 0) { sp--; ip = code_stack[sp]; input = input_stack[sp]; bytes_matched = matches_stack[sp]; stop = FALSE; while(!stop) { if (*ip == RE_OPCODE_MATCH) { if (flags & RE_FLAGS_EXHAUSTIVE) { FAIL_ON_ERROR(callback( flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data, bytes_matched, flags, callback_args)); break; } else { if (matches != NULL) *matches = bytes_matched; return ERROR_SUCCESS; } } if (bytes_matched >= max_bytes_matched) break; switch(*ip) { case RE_OPCODE_LITERAL: if (*input == *(ip + 1)) { bytes_matched++; input += input_incr; ip += 2; } else { stop = TRUE; } break; case RE_OPCODE_MASKED_LITERAL: value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; if ((*input & mask) == value) { bytes_matched++; input += input_incr; ip += 3; } else { stop = TRUE; } break; case RE_OPCODE_ANY: bytes_matched++; input += input_incr; ip += 1; break; case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1); next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS); for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++) { next_input = input + i * input_incr; if (bytes_matched + i >= max_bytes_matched) break; if ( *(next_opcode) != RE_OPCODE_LITERAL || (*(next_opcode) == RE_OPCODE_LITERAL && *(next_opcode + 1) == *next_input)) { if (sp >= MAX_FAST_RE_STACK) return -4; code_stack[sp] = next_opcode; input_stack[sp] = next_input; matches_stack[sp] = bytes_matched + i; sp++; } } input += input_incr * repeat_any_args->min; bytes_matched += repeat_any_args->min; ip = next_opcode; break; default: assert(FALSE); } } } if (matches != NULL) *matches = -1; return ERROR_SUCCESS; }
1
CVE-2017-9465
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
2,717
claws
e3ffcb455e0376053451ce968e6c71ef37708222
void conv_code_converter_destroy(CodeConverter *conv) { g_free(conv->charset_str); g_free(conv); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,795
linux
919f4ebc598701670e80e31573a58f1f2d2bf918
static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx) { struct kvm_vcpu *vcpu; struct kvm_vcpu_hv_synic *synic; vcpu = get_vcpu_by_vpidx(kvm, vpidx); if (!vcpu) return NULL; synic = to_hv_synic(vcpu); return (synic->active) ? synic : NULL; }
1
CVE-2021-30178
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
1,356
mod_auth_openidc
03e6bfb446f4e3f27c003d30d6a433e5dd8e2b3d
int oidc_content_handler(request_rec *r) { oidc_cfg *c = ap_get_module_config(r->server->module_config, &auth_openidc_module); int rc = DECLINED; /* track if the session needs to be updated/saved into the cache */ apr_byte_t needs_save = FALSE; oidc_session_t *session = NULL; if (oidc_enabled(r) == TRUE) { if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c)) == TRUE) { if (oidc_util_request_has_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO)) { oidc_session_load(r, &session); rc = oidc_handle_existing_session(r, c, session, &needs_save); if (rc == OK) /* handle request for session info */ rc = oidc_handle_info_request(r, c, session, needs_save); /* free resources allocated for the session */ oidc_session_free(r, session); } else if (oidc_util_request_has_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS)) { /* handle JWKs request */ rc = oidc_handle_jwks(r, c); } else { rc = OK; } } else if (oidc_request_state_get(r, OIDC_REQUEST_STATE_KEY_DISCOVERY) != NULL) { rc = oidc_discovery(r, c); } else if (oidc_request_state_get(r, OIDC_REQUEST_STATE_KEY_AUTHN) != NULL) { rc = OK; } } return rc; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,088
linux
a8b0ca17b80e92faab46ee7179ba9e99ccb61233
static int cop1Emulate(struct pt_regs *xcp, struct mips_fpu_struct *ctx, void *__user *fault_addr) { mips_instruction ir; unsigned long emulpc, contpc; unsigned int cond; if (!access_ok(VERIFY_READ, xcp->cp0_epc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGSEGV; } /* XXX NEC Vr54xx bug workaround */ if ((xcp->cp0_cause & CAUSEF_BD) && !isBranchInstr(&ir)) xcp->cp0_cause &= ~CAUSEF_BD; if (xcp->cp0_cause & CAUSEF_BD) { /* * The instruction to be emulated is in a branch delay slot * which means that we have to emulate the branch instruction * BEFORE we do the cop1 instruction. * * This branch could be a COP1 branch, but in that case we * would have had a trap for that instruction, and would not * come through this route. * * Linux MIPS branch emulator operates on context, updating the * cp0_epc. */ emulpc = xcp->cp0_epc + 4; /* Snapshot emulation target */ if (__compute_return_epc(xcp)) { #ifdef CP1DBG printk("failed to emulate branch at %p\n", (void *) (xcp->cp0_epc)); #endif return SIGILL; } if (!access_ok(VERIFY_READ, emulpc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)emulpc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) emulpc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)emulpc; return SIGSEGV; } /* __compute_return_epc() will have updated cp0_epc */ contpc = xcp->cp0_epc; /* In order not to confuse ptrace() et al, tweak context */ xcp->cp0_epc = emulpc - 4; } else { emulpc = xcp->cp0_epc; contpc = xcp->cp0_epc + 4; } emul: perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, xcp, 0); MIPS_FPU_EMU_INC_STATS(emulated); switch (MIPSInst_OPCODE(ir)) { case ldc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } DITOREG(val, MIPSInst_RT(ir)); break; } case sdc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(stores); DIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case lwc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } SITOREG(val, MIPSInst_RT(ir)); break; } case swc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(stores); SIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case cop1_op: switch (MIPSInst_RS(ir)) { #if defined(__mips64) case dmfc_op: /* copregister fs -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { DIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case dmtc_op: /* copregister fs <- rt */ DITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; #endif case mfc_op: /* copregister rd -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { SIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case mtc_op: /* copregister rd <- rt */ SITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; case cfc_op:{ /* cop control register rd -> gpr[rt] */ u32 value; if (MIPSInst_RD(ir) == FPCREG_CSR) { value = ctx->fcr31; value = (value & ~FPU_CSR_RM) | mips_rm[modeindex(value)]; #ifdef CSRTRACE printk("%p gpr[%d]<-csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif } else if (MIPSInst_RD(ir) == FPCREG_RID) value = 0; else value = 0; if (MIPSInst_RT(ir)) xcp->regs[MIPSInst_RT(ir)] = value; break; } case ctc_op:{ /* copregister rd <- rt */ u32 value; if (MIPSInst_RT(ir) == 0) value = 0; else value = xcp->regs[MIPSInst_RT(ir)]; /* we only have one writable control reg */ if (MIPSInst_RD(ir) == FPCREG_CSR) { #ifdef CSRTRACE printk("%p gpr[%d]->csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif /* * Don't write reserved bits, * and convert to ieee library modes */ ctx->fcr31 = (value & ~(FPU_CSR_RSVD | FPU_CSR_RM)) | ieee_rm[modeindex(value)]; } if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { return SIGFPE; } break; } case bc_op:{ int likely = 0; if (xcp->cp0_cause & CAUSEF_BD) return SIGILL; #if __mips >= 4 cond = ctx->fcr31 & fpucondbit[MIPSInst_RT(ir) >> 2]; #else cond = ctx->fcr31 & FPU_CSR_COND; #endif switch (MIPSInst_RT(ir) & 3) { case bcfl_op: likely = 1; case bcf_op: cond = !cond; break; case bctl_op: likely = 1; case bct_op: break; default: /* thats an illegal instruction */ return SIGILL; } xcp->cp0_cause |= CAUSEF_BD; if (cond) { /* branch taken: emulate dslot * instruction */ xcp->cp0_epc += 4; contpc = (xcp->cp0_epc + (MIPSInst_SIMM(ir) << 2)); if (!access_ok(VERIFY_READ, xcp->cp0_epc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGSEGV; } switch (MIPSInst_OPCODE(ir)) { case lwc1_op: case swc1_op: #if (__mips >= 2 || defined(__mips64)) case ldc1_op: case sdc1_op: #endif case cop1_op: #if __mips >= 4 && __mips != 32 case cop1x_op: #endif /* its one of ours */ goto emul; #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) == movc_op) goto emul; break; #endif } /* * Single step the non-cp1 * instruction in the dslot */ return mips_dsemul(xcp, ir, contpc); } else { /* branch not taken */ if (likely) { /* * branch likely nullifies * dslot if not taken */ xcp->cp0_epc += 4; contpc += 4; /* * else continue & execute * dslot as normal insn */ } } break; } default: if (!(MIPSInst_RS(ir) & 0x10)) return SIGILL; { int sig; /* a real fpu computation instruction */ if ((sig = fpu_emu(xcp, ctx, ir))) return sig; } } break; #if __mips >= 4 && __mips != 32 case cop1x_op:{ int sig = fpux_emu(xcp, ctx, ir, fault_addr); if (sig) return sig; break; } #endif #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) != movc_op) return SIGILL; cond = fpucondbit[MIPSInst_RT(ir) >> 2]; if (((ctx->fcr31 & cond) != 0) == ((MIPSInst_RT(ir) & 1) != 0)) xcp->regs[MIPSInst_RD(ir)] = xcp->regs[MIPSInst_RS(ir)]; break; #endif default: return SIGILL; } /* we did it !! */ xcp->cp0_epc = contpc; xcp->cp0_cause &= ~CAUSEF_BD; return 0; }
1
CVE-2011-2918
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
1,693
Android
6d0249be2275fd4086783f259f4e2c54722a7c55
ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1) : mIsValid(false), mData(NULL), mSize(0), mFirstFrameOffset(0), mVersion(ID3_UNKNOWN), mRawSize(0) { sp<MemorySource> source = new MemorySource(data, size); mIsValid = parseV2(source, 0); if (!mIsValid && !ignoreV1) { mIsValid = parseV1(source); } }
1
CVE-2016-3920
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
7,116
Chrome
18c5c5dcef9cfccff64f0c23f920ef22822271a9
void InstallTemplateURLWithNewTabPage(GURL new_tab_page_url) { TemplateURLServiceFactory::GetInstance()->SetTestingFactoryAndUse( profile(), base::BindRepeating(&TemplateURLServiceFactory::BuildInstanceFor)); TemplateURLService* template_url_service = TemplateURLServiceFactory::GetForProfile(browser()->profile()); search_test_utils::WaitForTemplateURLServiceToLoad(template_url_service); TemplateURLData data; data.SetShortName(base::ASCIIToUTF16("foo.com")); data.SetURL("http://foo.com/url?bar={searchTerms}"); data.new_tab_url = new_tab_page_url.spec(); TemplateURL* template_url = template_url_service->Add(std::make_unique<TemplateURL>(data)); template_url_service->SetUserSelectedDefaultSearchProvider(template_url); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,784
Chrome
116d0963cadfbf55ef2ec3d13781987c4d80517a
void PrintPreviewDataService::RemoveEntry( const std::string& preview_ui_addr_str) { PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str); if (it != data_store_map_.end()) data_store_map_.erase(it); }
1
CVE-2012-2891
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Phase: Architecture and Design Strategy: Separation of Privilege Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges.
8,236
pam_tacplus
4a9852c31c2fd0c0e72fbb689a586aabcfb11cb0
char *_pam_get_user(pam_handle_t *pamh) { int retval; char *user; retval = pam_get_user(pamh, (void *) &user, "Username: "); if (retval != PAM_SUCCESS || user == NULL || *user == '\0') { _pam_log(LOG_ERR, "unable to obtain username"); user = NULL; } return user; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,697
linux
f6bbf0010ba004f5e90c7aefdebc0ee4bd3283b9
static void vhost_vdpa_config_put(struct vhost_vdpa *v) { if (v->config_ctx) eventfd_ctx_put(v->config_ctx); }
1
CVE-2021-29266
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
3,167
ImageMagick
7fd419441bc7103398e313558171d342c6315f44
static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MagickPathExtent], id[MagickPathExtent], keyword[MagickPathExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; StringInfo *profile; unsigned int signature; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(cache_filename,image->filename,MagickPathExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MagickPathExtent; options=AcquireString((char *) NULL); signature=GetMagickSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MagickPathExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MagickPathExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MagickPathExtent; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MagickPathExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'a': case 'A': { if (LocaleCompare(keyword,"alpha-trait") == 0) { ssize_t alpha_trait; alpha_trait=ParseCommandOption(MagickPixelTraitOptions, MagickFalse,options); if (alpha_trait < 0) break; image->alpha_trait=(PixelTrait) alpha_trait; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->background_color,exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->border_color,exception); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MagickPathExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"mattecolor") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->matte_color,exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'n': case 'N': { if (LocaleCompare(keyword,"number-channels") == 0) { image->number_channels=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"number-meta-channels") == 0) { image->number_meta_channels=StringToUnsignedLong(options); if (image->number_meta_channels > MaxPixelChannels) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); break; } break; } case 'o': case 'O': { if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile,exception); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions, MagickFalse,options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } default: { (void) SetImageProperty(image,keyword,options,exception); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (signature != GetMagickSignature((const StringInfo *) NULL)) ThrowReaderException(CacheError,"IncompatibleAPI"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MagickPathExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MagickPathExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MagickPathExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); count=ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ image->colormap=(PixelInfo *) AcquireQuantumMemory(image->colors+1, sizeof(*image->colormap)); if (image->colormap == (PixelInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=colormap; switch (depth) { default: colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,071
tensorflow
b432a38fe0e1b4b904a6c222cbce794c39703e87
explicit DrawBoundingBoxesOp(OpKernelConstruction* context) : OpKernel(context) {}
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,018
linux
34b3be18a04ecdc610aae4c48e5d1b799d8689f6
int sdma_send_txreq(struct sdma_engine *sde, struct iowait_work *wait, struct sdma_txreq *tx, bool pkts_sent) { int ret = 0; u16 tail; unsigned long flags; /* user should have supplied entire packet */ if (unlikely(tx->tlen)) return -EINVAL; tx->wait = iowait_ioww_to_iow(wait); spin_lock_irqsave(&sde->tail_lock, flags); retry: if (unlikely(!__sdma_running(sde))) goto unlock_noconn; if (unlikely(tx->num_desc > sde->desc_avail)) goto nodesc; tail = submit_tx(sde, tx); if (wait) iowait_sdma_inc(iowait_ioww_to_iow(wait)); sdma_update_tail(sde, tail); unlock: spin_unlock_irqrestore(&sde->tail_lock, flags); return ret; unlock_noconn: if (wait) iowait_sdma_inc(iowait_ioww_to_iow(wait)); tx->next_descq_idx = 0; #ifdef CONFIG_HFI1_DEBUG_SDMA_ORDER tx->sn = sde->tail_sn++; trace_hfi1_sdma_in_sn(sde, tx->sn); #endif spin_lock(&sde->flushlist_lock); list_add_tail(&tx->list, &sde->flushlist); spin_unlock(&sde->flushlist_lock); iowait_inc_wait_count(wait, tx->num_desc); queue_work_on(sde->cpu, system_highpri_wq, &sde->flush_worker); ret = -ECOMM; goto unlock; nodesc: ret = sdma_check_progress(sde, wait, tx, pkts_sent); if (ret == -EAGAIN) { ret = 0; goto retry; } sde->descq_full_count++; goto unlock; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,925
liblouis
dbfa58bb128cae86729578ac596056b3385817ef
parseChars(FileInfo *nested, CharsString *result, CharsString *token) { int in = 0; int out = 0; int lastOutSize = 0; int lastIn; unsigned int ch = 0; int numBytes = 0; unsigned int utf32 = 0; int k; while (in < token->length) { ch = token->chars[in++] & 0xff; if (ch < 128) { if (ch == '\\') { /* escape sequence */ switch (ch = token->chars[in]) { case '\\': break; case 'e': ch = 0x1b; break; case 'f': ch = 12; break; case 'n': ch = 10; break; case 'r': ch = 13; break; case 's': ch = ' '; break; case 't': ch = 9; break; case 'v': ch = 11; break; case 'w': ch = ENDSEGMENT; break; case 34: ch = QUOTESUB; break; case 'X': case 'x': if (token->length - in > 4) { ch = hexValue(nested, &token->chars[in + 1], 4); in += 4; } break; case 'y': case 'Y': if (CHARSIZE == 2) { not32: compileError(nested, "liblouis has not been compiled for 32-bit Unicode"); break; } if (token->length - in > 5) { ch = hexValue(nested, &token->chars[in + 1], 5); in += 5; } break; case 'z': case 'Z': if (CHARSIZE == 2) goto not32; if (token->length - in > 8) { ch = hexValue(nested, &token->chars[in + 1], 8); in += 8; } break; default: compileError(nested, "invalid escape sequence '\\%c'", ch); break; } in++; } if (out >= MAXSTRING) { result->length = out; return 1; } result->chars[out++] = (widechar)ch; continue; } lastOutSize = out; lastIn = in; for (numBytes = MAXBYTES - 1; numBytes > 0; numBytes--) if (ch >= first0Bit[numBytes]) break; utf32 = ch & (0XFF - first0Bit[numBytes]); for (k = 0; k < numBytes; k++) { if (in >= MAXSTRING) break; if (out >= MAXSTRING) { result->length = lastOutSize; return 1; } if (token->chars[in] < 128 || (token->chars[in] & 0x0040)) { compileWarning(nested, "invalid UTF-8. Assuming Latin-1."); result->chars[out++] = token->chars[lastIn]; in = lastIn + 1; continue; } utf32 = (utf32 << 6) + (token->chars[in++] & 0x3f); } if (out >= MAXSTRING) { result->length = lastOutSize; return 1; } if (CHARSIZE == 2 && utf32 > 0xffff) utf32 = 0xffff; result->chars[out++] = (widechar)utf32; } result->length = out; return 1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,622
linux
3e4c56d41eef5595035872a2ec5a483f42e8917f
static int ocfs2_expand_nonsparse_inode(struct inode *inode, struct buffer_head *di_bh, loff_t pos, unsigned len, struct ocfs2_write_ctxt *wc) { int ret; loff_t newsize = pos + len; BUG_ON(ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb))); if (newsize <= i_size_read(inode)) return 0; ret = ocfs2_extend_no_holes(inode, di_bh, newsize, pos); if (ret) mlog_errno(ret); /* There is no wc if this is call from direct. */ if (wc) wc->w_first_new_cpos = ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)); return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,844
linux
3151527ee007b73a0ebd296010f1c0454a919c7d
static int change_mount_flags(struct vfsmount *mnt, int ms_flags) { int error = 0; int readonly_request = 0; if (ms_flags & MS_RDONLY) readonly_request = 1; if (readonly_request == __mnt_is_readonly(mnt)) return 0; if (readonly_request) error = mnt_make_readonly(real_mount(mnt)); else __mnt_unmake_readonly(real_mount(mnt)); return error; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,900
LibRaw-demosaic-pack-GPL2
194f592e205990ea8fce72b6c571c14350aca716
void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); if (type == 2) { fread (meta_data, 1, meta_length, ifp); for (i=0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64) 301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free (meta_data); meta_data = (char *) malloc (meta_length = wide*high*3/2); merror (meta_data, "foveon_load_camf()"); foveon_huff (huff); get4(); getbits(-1); for (j=row=0; row < high; row++) { for (col=0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } else fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type); }
1
CVE-2017-6890
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
2,539
krb5
83ed75feba32e46f736fcce0d96a0445f29b96c2
chrand_principal3_2_svc(chrand3_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, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, &k, &nkeys); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_randkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, &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; }
1
CVE-2015-8631
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
4,179
qemu
5519724a13664b43e225ca05351c60b4468e4555
static void xgmac_enet_send(XgmacState *s) { struct desc bd; int frame_size; int len; uint8_t frame[8192]; uint8_t *ptr; ptr = frame; frame_size = 0; while (1) { xgmac_read_desc(s, &bd, 0); if ((bd.ctl_stat & 0x80000000) == 0) { /* Run out of descriptors to transmit. */ break; } len = (bd.buffer1_size & 0xfff) + (bd.buffer2_size & 0xfff); if ((bd.buffer1_size & 0xfff) > 2048) { DEBUGF_BRK("qemu:%s:ERROR...ERROR...ERROR... -- " "xgmac buffer 1 len on send > 2048 (0x%x)\n", __func__, bd.buffer1_size & 0xfff); } if ((bd.buffer2_size & 0xfff) != 0) { DEBUGF_BRK("qemu:%s:ERROR...ERROR...ERROR... -- " "xgmac buffer 2 len on send != 0 (0x%x)\n", __func__, bd.buffer2_size & 0xfff); } if (len >= sizeof(frame)) { DEBUGF_BRK("qemu:%s: buffer overflow %d read into %zu " "buffer\n" , __func__, len, sizeof(frame)); DEBUGF_BRK("qemu:%s: buffer1.size=%d; buffer2.size=%d\n", __func__, bd.buffer1_size, bd.buffer2_size); } cpu_physical_memory_read(bd.buffer1_addr, ptr, len); ptr += len; frame_size += len; if (bd.ctl_stat & 0x20000000) { /* Last buffer in frame. */ qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->regs[DMA_STATUS] |= DMA_STATUS_TI | DMA_STATUS_NIS; } bd.ctl_stat &= ~0x80000000; /* Write back the modified descriptor. */ xgmac_write_desc(s, &bd, 0); } }
1
CVE-2020-15863
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
1,387
linux
cabfb3680f78981d26c078a26e5c748531257ebb
static void unicode_ssetup_strings(char **pbcc_area, struct cifs_ses *ses, const struct nls_table *nls_cp) { char *bcc_ptr = *pbcc_area; int bytes_ret = 0; /* BB FIXME add check that strings total less than 335 or will need to send them as arrays */ /* unicode strings, must be word aligned before the call */ /* if ((long) bcc_ptr % 2) { *bcc_ptr = 0; bcc_ptr++; } */ /* copy user */ if (ses->user_name == NULL) { /* null user mount */ *bcc_ptr = 0; *(bcc_ptr+1) = 0; } else { bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->user_name, CIFS_MAX_USERNAME_LEN, nls_cp); } bcc_ptr += 2 * bytes_ret; bcc_ptr += 2; /* account for null termination */ unicode_domain_string(&bcc_ptr, ses, nls_cp); unicode_oslm_strings(&bcc_ptr, nls_cp); *pbcc_area = bcc_ptr; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,992
krb5
c2ccf4197f697c4ff143b8a786acdd875e70a89d
initialize_realms(krb5_context kcontext, int argc, char **argv) { int c; char *db_name = (char *) NULL; char *lrealm = (char *) NULL; char *mkey_name = (char *) NULL; krb5_error_code retval; krb5_enctype menctype = ENCTYPE_UNKNOWN; kdc_realm_t *rdatap = NULL; krb5_boolean manual = FALSE; krb5_boolean def_restrict_anon; char *default_udp_ports = 0; char *default_tcp_ports = 0; krb5_pointer aprof; const char *hierarchy[3]; char *no_refrls = NULL; char *host_based_srvcs = NULL; int db_args_size = 0; char **db_args = NULL; extern char *optarg; if (!krb5_aprof_init(DEFAULT_KDC_PROFILE, KDC_PROFILE_ENV, &aprof)) { hierarchy[0] = KRB5_CONF_KDCDEFAULTS; hierarchy[1] = KRB5_CONF_KDC_PORTS; hierarchy[2] = (char *) NULL; if (krb5_aprof_get_string(aprof, hierarchy, TRUE, &default_udp_ports)) default_udp_ports = 0; hierarchy[1] = KRB5_CONF_KDC_TCP_PORTS; if (krb5_aprof_get_string(aprof, hierarchy, TRUE, &default_tcp_ports)) default_tcp_ports = 0; hierarchy[1] = KRB5_CONF_MAX_DGRAM_REPLY_SIZE; if (krb5_aprof_get_int32(aprof, hierarchy, TRUE, &max_dgram_reply_size)) max_dgram_reply_size = MAX_DGRAM_SIZE; hierarchy[1] = KRB5_CONF_RESTRICT_ANONYMOUS_TO_TGT; if (krb5_aprof_get_boolean(aprof, hierarchy, TRUE, &def_restrict_anon)) def_restrict_anon = FALSE; hierarchy[1] = KRB5_CONF_NO_HOST_REFERRAL; if (krb5_aprof_get_string_all(aprof, hierarchy, &no_refrls)) no_refrls = 0; if (!no_refrls || krb5_match_config_pattern(no_refrls, KRB5_CONF_ASTERISK) == FALSE) { hierarchy[1] = KRB5_CONF_HOST_BASED_SERVICES; if (krb5_aprof_get_string_all(aprof, hierarchy, &host_based_srvcs)) host_based_srvcs = 0; } krb5_aprof_finish(aprof); } if (default_udp_ports == 0) { default_udp_ports = strdup(DEFAULT_KDC_UDP_PORTLIST); if (default_udp_ports == 0) { fprintf(stderr, _(" KDC cannot initialize. Not enough memory\n")); exit(1); } } if (default_tcp_ports == 0) { default_tcp_ports = strdup(DEFAULT_KDC_TCP_PORTLIST); if (default_tcp_ports == 0) { fprintf(stderr, _(" KDC cannot initialize. Not enough memory\n")); exit(1); } } /* * Loop through the option list. Each time we encounter a realm name, * use the previously scanned options to fill in for defaults. */ while ((c = getopt(argc, argv, "x:r:d:mM:k:R:e:P:p:s:nw:4:X3")) != -1) { switch(c) { case 'x': db_args_size++; { char **temp = realloc( db_args, sizeof(char*) * (db_args_size+1)); /* one for NULL */ if( temp == NULL ) { fprintf(stderr, _("%s: KDC cannot initialize. Not enough " "memory\n"), argv[0]); exit(1); } db_args = temp; } db_args[db_args_size-1] = optarg; db_args[db_args_size] = NULL; break; case 'r': /* realm name for db */ if (!find_realm_data(optarg, (krb5_ui_4) strlen(optarg))) { if ((rdatap = (kdc_realm_t *) malloc(sizeof(kdc_realm_t)))) { if ((retval = init_realm(rdatap, optarg, mkey_name, menctype, default_udp_ports, default_tcp_ports, manual, def_restrict_anon, db_args, no_refrls, host_based_srvcs))) { fprintf(stderr, _("%s: cannot initialize realm %s - " "see log file for details\n"), argv[0], optarg); exit(1); } kdc_realmlist[kdc_numrealms] = rdatap; kdc_numrealms++; free(db_args), db_args=NULL, db_args_size = 0; } else { fprintf(stderr, _("%s: cannot initialize realm %s. Not " "enough memory\n"), argv[0], optarg); exit(1); } } break; case 'd': /* pathname for db */ /* now db_name is not a seperate argument. * It has to be passed as part of the db_args */ if( db_name == NULL ) { if (asprintf(&db_name, "dbname=%s", optarg) < 0) { fprintf(stderr, _("%s: KDC cannot initialize. Not enough " "memory\n"), argv[0]); exit(1); } } db_args_size++; { char **temp = realloc( db_args, sizeof(char*) * (db_args_size+1)); /* one for NULL */ if( temp == NULL ) { fprintf(stderr, _("%s: KDC cannot initialize. Not enough " "memory\n"), argv[0]); exit(1); } db_args = temp; } db_args[db_args_size-1] = db_name; db_args[db_args_size] = NULL; break; case 'm': /* manual type-in of master key */ manual = TRUE; if (menctype == ENCTYPE_UNKNOWN) menctype = ENCTYPE_DES_CBC_CRC; break; case 'M': /* master key name in DB */ mkey_name = optarg; break; case 'n': nofork++; /* don't detach from terminal */ break; case 'w': /* create multiple worker processes */ workers = atoi(optarg); if (workers <= 0) usage(argv[0]); break; case 'k': /* enctype for master key */ if (krb5_string_to_enctype(optarg, &menctype)) com_err(argv[0], 0, _("invalid enctype %s"), optarg); break; case 'R': /* Replay cache name; defunct since we don't use a replay cache. */ break; case 'P': pid_file = optarg; break; case 'p': if (default_udp_ports) free(default_udp_ports); default_udp_ports = strdup(optarg); if (!default_udp_ports) { fprintf(stderr, _(" KDC cannot initialize. Not enough " "memory\n")); exit(1); } #if 0 /* not yet */ if (default_tcp_ports) free(default_tcp_ports); default_tcp_ports = strdup(optarg); #endif break; case '4': break; case 'X': break; case '?': default: usage(argv[0]); } } /* * Check to see if we processed any realms. */ if (kdc_numrealms == 0) { /* no realm specified, use default realm */ if ((retval = krb5_get_default_realm(kcontext, &lrealm))) { com_err(argv[0], retval, _("while attempting to retrieve default realm")); fprintf (stderr, _("%s: %s, attempting to retrieve default realm\n"), argv[0], krb5_get_error_message(kcontext, retval)); exit(1); } if ((rdatap = (kdc_realm_t *) malloc(sizeof(kdc_realm_t)))) { if ((retval = init_realm(rdatap, lrealm, mkey_name, menctype, default_udp_ports, default_tcp_ports, manual, def_restrict_anon, db_args, no_refrls, host_based_srvcs))) { fprintf(stderr, _("%s: cannot initialize realm %s - see log " "file for details\n"), argv[0], lrealm); exit(1); } kdc_realmlist[0] = rdatap; kdc_numrealms++; } krb5_free_default_realm(kcontext, lrealm); } /* Ensure that this is set for our first request. */ kdc_active_realm = kdc_realmlist[0]; if (default_udp_ports) free(default_udp_ports); if (default_tcp_ports) free(default_tcp_ports); if (db_args) free(db_args); if (db_name) free(db_name); if (host_based_srvcs) free(host_based_srvcs); if (no_refrls) free(no_refrls); return; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,424
Chrome
9785a8b9672f6f35f5a401a86251c4109eda4175
AwFeatureListCreator::AwFeatureListCreator() : aw_field_trials_(std::make_unique<AwFieldTrials>()) {}
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,129
mosh
9791768705528e911bfca6c4d8aa88139035060e
void Dispatcher::collect( const Parser::Collect *act ) { assert( act->char_present ); if ( ( dispatch_chars.length() < 8 ) /* never should need more than 2 */ && ( act->ch <= 255 ) ) { /* ignore non-8-bit */ dispatch_chars.push_back( act->ch ); act->handled = true; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,612
gpac
44fdc3d972c31c56efe73e1a3b63438d46087652
void gf_fs_push_arg(GF_FilterSession *session, const char *szArg, u32 was_found, u32 type) { if (session->flags & GF_FS_FLAG_NO_ARG_CHECK) return; if (!was_found) { Bool afound = GF_FALSE; u32 k, acount; if (!session->parsed_args) session->parsed_args = gf_list_new(); acount = gf_list_count(session->parsed_args); for (k=0; k<acount; k++) { GF_FSArgItem *ai = gf_list_get(session->parsed_args, k); if (!strcmp(ai->argname, szArg)) { afound = GF_TRUE; if ((ai->type==2) && (type==2) && (ai->found_type==1)) ai->found_type = 0; break; } } if (!afound) { GF_FSArgItem *ai; GF_SAFEALLOC(ai, GF_FSArgItem); if (ai) { ai->argname = gf_strdup(szArg); ai->type = type; gf_list_add(session->parsed_args, ai ); } } } else { u32 k, acount; Bool found = GF_FALSE; if (!session->parsed_args) session->parsed_args = gf_list_new(); acount = gf_list_count(session->parsed_args); for (k=0; k<acount; k++) { GF_FSArgItem *ai = gf_list_get(session->parsed_args, k); if (!strcmp(ai->argname, szArg)) { ai->found_type = was_found; found = GF_TRUE; break; } } if (!found) { GF_FSArgItem *ai; GF_SAFEALLOC(ai, GF_FSArgItem); if (ai) { ai->argname = gf_strdup(szArg); ai->type = type; ai->found_type = was_found; gf_list_add(session->parsed_args, ai ); } } } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,343
Chrome
1c40f9042ae2d6ee7483d72998aabb5e73b2ff60
Response InspectorNetworkAgent::GetResponseBody(const String& request_id, String* content, bool* base64_encoded) { NetworkResourcesData::ResourceData const* resource_data = resources_data_->Data(request_id); if (!resource_data) { return Response::Error("No resource with given identifier found"); } if (resource_data->HasContent()) { *content = resource_data->Content(); *base64_encoded = resource_data->Base64Encoded(); return Response::OK(); } if (resource_data->IsContentEvicted()) { return Response::Error("Request content was evicted from inspector cache"); } if (resource_data->Buffer() && !resource_data->TextEncodingName().IsNull()) { bool success = InspectorPageAgent::SharedBufferContent( resource_data->Buffer(), resource_data->MimeType(), resource_data->TextEncodingName(), content, base64_encoded); DCHECK(success); return Response::OK(); } if (resource_data->CachedResource() && InspectorPageAgent::CachedResourceContent(resource_data->CachedResource(), content, base64_encoded)) { return Response::OK(); } return Response::Error("No data found for resource with given identifier"); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,151
gpac
71460d72ec07df766dab0a4d52687529f3efcf0a
ISOMChannel *isor_create_channel(ISOMReader *read, GF_FilterPid *pid, u32 track, u32 item_id, Bool force_no_extractors) { ISOMChannel *ch; const GF_PropertyValue *p; s64 ts_shift; if (!read->mov) return NULL; GF_SAFEALLOC(ch, ISOMChannel); if (!ch) { return NULL; } ch->owner = read; ch->pid = pid; ch->to_init = GF_TRUE; gf_list_add(read->channels, ch); ch->track = track; ch->item_id = item_id; ch->nalu_extract_mode = 0; ch->track_id = gf_isom_get_track_id(read->mov, ch->track); switch (gf_isom_get_media_type(ch->owner->mov, ch->track)) { case GF_ISOM_MEDIA_OCR: ch->streamType = GF_STREAM_OCR; break; case GF_ISOM_MEDIA_SCENE: ch->streamType = GF_STREAM_SCENE; break; case GF_ISOM_MEDIA_VISUAL: case GF_ISOM_MEDIA_AUXV: case GF_ISOM_MEDIA_PICT: gf_isom_get_reference(ch->owner->mov, ch->track, GF_ISOM_REF_BASE, 1, &ch->base_track); //use base track only if avc/svc or hevc/lhvc. If avc+lhvc we need different rules if ( gf_isom_get_avc_svc_type(ch->owner->mov, ch->base_track, 1) == GF_ISOM_AVCTYPE_AVC_ONLY) { if ( gf_isom_get_hevc_lhvc_type(ch->owner->mov, ch->track, 1) >= GF_ISOM_HEVCTYPE_HEVC_ONLY) { ch->base_track=0; } } ch->next_track = 0; /*in scalable mode add SPS/PPS in-band*/ if (ch->base_track) ch->nalu_extract_mode = GF_ISOM_NALU_EXTRACT_INBAND_PS_FLAG /*| GF_ISOM_NALU_EXTRACT_ANNEXB_FLAG*/; break; } if (!read->noedit) { ch->ts_offset = 0; ch->has_edit_list = gf_isom_get_edit_list_type(ch->owner->mov, ch->track, &ch->ts_offset) ? GF_TRUE : GF_FALSE; if (!ch->has_edit_list && ch->ts_offset) { //if >0 this is a hold, we signal positive delay //if <0 this is a skip, we signal negative delay gf_filter_pid_set_property(pid, GF_PROP_PID_DELAY, &PROP_LONGSINT( ch->ts_offset) ); } } else ch->has_edit_list = GF_FALSE; ch->has_rap = (gf_isom_has_sync_points(ch->owner->mov, ch->track)==1) ? GF_TRUE : GF_FALSE; gf_filter_pid_set_property(pid, GF_PROP_PID_HAS_SYNC, &PROP_BOOL(ch->has_rap) ); //some fragmented files do not advertize a sync sample table (legal) so we need to update as soon as we fetch a fragment //to see if we are all-intra (as detected here) or not if (!ch->has_rap && ch->owner->frag_type) ch->check_has_rap = GF_TRUE; ch->timescale = gf_isom_get_media_timescale(ch->owner->mov, ch->track); ts_shift = gf_isom_get_cts_to_dts_shift(ch->owner->mov, ch->track); if (ts_shift) { gf_filter_pid_set_property(pid, GF_PROP_PID_CTS_SHIFT, &PROP_UINT((u32) ts_shift) ); } if (!track || !gf_isom_is_track_encrypted(read->mov, track)) { if (force_no_extractors) { ch->nalu_extract_mode = GF_ISOM_NALU_EXTRACT_LAYER_ONLY; } else { switch (read->smode) { case MP4DMX_SPLIT_EXTRACTORS: ch->nalu_extract_mode = GF_ISOM_NALU_EXTRACT_INSPECT | GF_ISOM_NALU_EXTRACT_TILE_ONLY; break; case MP4DMX_SPLIT: ch->nalu_extract_mode = GF_ISOM_NALU_EXTRACT_LAYER_ONLY | GF_ISOM_NALU_EXTRACT_TILE_ONLY; break; default: break; } } if (ch->nalu_extract_mode) { gf_isom_set_nalu_extract_mode(ch->owner->mov, ch->track, ch->nalu_extract_mode); } return ch; } if (ch->owner->nocrypt) { ch->is_encrypted = GF_FALSE; return ch; } ch->is_encrypted = GF_TRUE; p = gf_filter_pid_get_property(pid, GF_PROP_PID_STREAM_TYPE); if (p) gf_filter_pid_set_property(pid, GF_PROP_PID_ORIG_STREAM_TYPE, &PROP_UINT(p->value.uint) ); gf_filter_pid_set_property(pid, GF_PROP_PID_STREAM_TYPE, &PROP_UINT(GF_STREAM_ENCRYPTED) ); isor_set_crypt_config(ch); if (ch->nalu_extract_mode) { if (ch->is_encrypted) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[IsoMedia] using sample NAL rewrite with encryption is not yet supported, patch welcome\n")); } else { gf_isom_set_nalu_extract_mode(ch->owner->mov, ch->track, ch->nalu_extract_mode); } } return ch; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,199
linux
b4a1b4f5047e4f54e194681125c74c0aa64d637d
long keyctl_keyring_link(key_serial_t id, key_serial_t ringid) { key_ref_t keyring_ref, key_ref; long ret; keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); goto error; } key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE, KEY_NEED_LINK); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); goto error2; } ret = key_link(key_ref_to_ptr(keyring_ref), key_ref_to_ptr(key_ref)); key_ref_put(key_ref); error2: key_ref_put(keyring_ref); error: return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,473
net
85f1bd9a7b5a79d5baa8bf44af19658f7bf77bfa
int ip_mc_output(struct net *net, struct sock *sk, struct sk_buff *skb) { struct rtable *rt = skb_rtable(skb); struct net_device *dev = rt->dst.dev; /* * If the indicated interface is up and running, send the packet. */ IP_UPD_PO_STATS(net, IPSTATS_MIB_OUT, skb->len); skb->dev = dev; skb->protocol = htons(ETH_P_IP); /* * Multicasts are looped back for other local users */ if (rt->rt_flags&RTCF_MULTICAST) { if (sk_mc_loop(sk) #ifdef CONFIG_IP_MROUTE /* Small optimization: do not loopback not local frames, which returned after forwarding; they will be dropped by ip_mr_input in any case. Note, that local frames are looped back to be delivered to local recipients. This check is duplicated in ip_mr_input at the moment. */ && ((rt->rt_flags & RTCF_LOCAL) || !(IPCB(skb)->flags & IPSKB_FORWARDED)) #endif ) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); if (newskb) NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, sk, newskb, NULL, newskb->dev, ip_mc_finish_output); } /* Multicasts with ttl 0 must not go beyond the host */ if (ip_hdr(skb)->ttl == 0) { kfree_skb(skb); return 0; } } if (rt->rt_flags&RTCF_BROADCAST) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); if (newskb) NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, sk, newskb, NULL, newskb->dev, ip_mc_finish_output); } return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, sk, skb, NULL, skb->dev, ip_finish_output, !(IPCB(skb)->flags & IPSKB_REROUTED)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,619
wireshark
b8e0d416898bb975a02c1b55883342edc5b4c9c0
parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 *level, guint8 *codepage_stag, guint8 *codepage_attr) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; guint32 tag_len; /* Length of the idx (uintvar) from a LITERAL tag */ guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */ guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */ const char *tag_save_literal; /* Will contain the LITERAL tag identity */ const char *tag_new_literal; /* Will contain the LITERAL tag identity */ char *tag_save_buf = NULL; /* Will contain "tag_0x%02X" */ char *tag_new_buf = NULL; /* Will contain "tag_0x%02X" */ guint8 parsing_tag_content = FALSE; /* Are we parsing content from a tag with content: <x>Content</x> The initial state is FALSE. This state will trigger recursion. */ tag_save_literal = NULL; /* Prevents compiler warning */ DebugLog(("parse_wbxml_tag (level = %u, offset = %u)\n", *level, offset)); while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n", *level, peek, off, tvb_len)); if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG but not the LITERAL tokens */ case 0x00: /* SWITCH_PAGE */ *codepage_stag = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Tag | T -->%3d " "| SWITCH_PAGE (Tag code page) " "|", *codepage_stag); off += 2; break; case 0x01: /* END: only possible for Tag with Content */ if (tag_save_known) { /* Known TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Known Tag 0x%02X) " "| %s</%s>", *level, *codepage_stag, tag_save_known, Indent (*level), tag_save_literal); /* We already looked it up! */ } else { /* Literal TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s</%s>", *level, *codepage_stag, Indent (*level), tag_save_literal ? tag_save_literal : ""); } (*level)--; off++; /* Reset code page: not needed as return from recursion */ DebugLog(("STAG: level = %u, Return: len = %u\n", *level, off - offset)); return (off - offset); case 0x02: /* ENTITY */ ent = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| ENTITY " "| %s'&#%u;'", *level, *codepage_stag, Indent (*level), ent); off += 1+len; break; case 0x03: /* STR_I */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| STR_I (Inline string) " "| %s\'%s\'", *level, *codepage_stag, Indent(*level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x40: /* EXT_I_0 */ case 0x41: /* EXT_I_1 */ case 0x42: /* EXT_I_2 */ /* Extension tokens */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_I_%1x (Extension Token) " "| %s(Inline string extension: \'%s\')", *level, *codepage_stag, peek & 0x0f, Indent (*level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x43: /* PI */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| PI (XML Processing Instruction) " "| %s<?xml", *level, *codepage_stag, Indent (*level)); len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (PI) " "| %s?>", *level, *codepage_stag, Indent (*level)); break; case 0x80: /* EXT_T_0 */ case 0x81: /* EXT_T_1 */ case 0x82: /* EXT_T_2 */ /* Extension tokens */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_T_%1x (Extension Token) " "| %s(Extension Token, integer value: %u)", *level, *codepage_stag, peek & 0x0f, Indent (*level), idx); off += 1+len; break; case 0x83: /* STR_T */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| STR_T (Tableref string) " "| %s\'%s\'", *level, *codepage_stag, Indent (*level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| EXT_%1x (Extension Token) " "| %s(Single-byte extension)", *level, *codepage_stag, peek & 0x0f, Indent (*level)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1 + len + idx, " %3d | Tag | T %3d " "| OPAQUE (Opaque data) " "| %s(%d bytes of opaque data)", *level, *codepage_stag, Indent (*level), idx); off += 1+len+idx; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", *level, *codepage_stag); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("STAG: level = %u, Return: len = %u\n", *level, off - offset)); return (off - offset); } break; /* No default clause, as all cases have been treated */ } else { /* LITERAL or Known TAG */ /* We must store the initial tag, and also retrieve the new tag. * For efficiency reasons, we store the literal tag representation * for known tags too, so we can easily close the tag without the * need of a new lookup and avoiding storage of token codepage. * * There are 4 possibilities: * * 1. Known tag followed by a known tag * 2. Known tag followed by a LITERAL tag * 3. LITERAL tag followed by Known tag * 4. LITERAL tag followed by LITERAL tag */ /* Store the new tag */ tag_len = 0; if ((peek & 0x3F) == 4) { /* LITERAL */ DebugLog(("STAG: LITERAL tag (peek = 0x%02X, off = %u)" " - TableRef follows!\n", peek, off)); idx = tvb_get_guintvar (tvb, off+1, &tag_len); str_len = tvb_strsize (tvb, str_tbl+idx); tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len); tag_new_known = 0; /* invalidate known tag_new */ } else { /* Known tag */ tag_new_known = peek & 0x3F; tag_new_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X", tag_new_known); tag_new_literal = tag_new_buf; /* Stored looked up tag name string */ } /* Parsing of TAG starts HERE */ if (peek & 0x40) { /* Content present */ /* Content follows * [!] An explicit END token is expected in these cases! * ==> Recursion possible if we encounter a tag with content; * recursion will return at the explicit END token. */ if (parsing_tag_content) { /* Recurse */ DebugLog(("STAG: Tag in Tag - RECURSE! (off = %u)\n", off)); /* Do not process the attribute list: * recursion will take care of it */ (*level)++; len = parse_wbxml_tag (tree, tvb, off, str_tbl, level, codepage_stag, codepage_attr); off += len; } else { /* Now we will have content to parse */ /* Save the start tag so we can properly close it later. */ if ((peek & 0x3F) == 4) { /* Literal tag */ tag_save_literal = tag_new_literal; tag_save_known = 0; } else { /* Known tag */ tag_save_known = tag_new_known; tag_save_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X", tag_new_known); tag_save_literal = tag_save_buf; /* The last statement avoids needless lookups */ } /* Process the attribute list if present */ if (peek & 0x80) { /* Content and Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (AC) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_AC (Literal tag) (AC) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (attribute list) " "| %s>", *level, *codepage_stag, Indent (*level)); } else { /* Content, no Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (.C) " "| %s<%s>", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_C (Literal Tag) (.C) " "| %s<%s>", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } /* The data that follows in the parsing process * represents content for the opening tag * we've just processed in the lines above. * Next time we encounter a tag with content: recurse */ parsing_tag_content = TRUE; DebugLog(("Tag in Tag - No recursion this time! " "(off = %u)\n", off)); } } else { /* No Content */ DebugLog(("<Tag/> in Tag - No recursion! (off = %u)\n", off)); (*level)++; if (peek & 0x80) { /* No Content, Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (A.) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Known Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_A (Literal Tag) (A.) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } } else { /* No Content, No Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02x (..) " "| %s<%s />", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL (Literal Tag) (..) " "| %s<%s />", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } (*level)--; /* TODO: Do I have to reset code page here? */ } } /* if (tag & 0x3F) >= 5 */ } /* while */ DebugLog(("STAG: level = %u, Return: len = %u (end of function body)\n", *level, off - offset)); return (off - offset); }
1
CVE-2016-5359
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
6,708
poppler
b224e2f5739fe61de9fa69955d016725b2a4b78d
static void splashOutBlendHue(SplashColorPtr src, SplashColorPtr dest, SplashColorPtr blend, SplashColorMode cm) { unsigned char r0, g0, b0; #ifdef SPLASH_CMYK unsigned char r1, g1, b1; int i; SplashColor src2, dest2; #endif switch (cm) { case splashModeMono1: case splashModeMono8: blend[0] = dest[0]; break; case splashModeXBGR8: src[3] = 255; // fallthrough case splashModeRGB8: case splashModeBGR8: setSat(src[0], src[1], src[2], getSat(dest[0], dest[1], dest[2]), &r0, &g0, &b0); setLum(r0, g0, b0, getLum(dest[0], dest[1], dest[2]), &blend[0], &blend[1], &blend[2]); break; #ifdef SPLASH_CMYK case splashModeCMYK8: case splashModeDeviceN8: for (i = 0; i < 4; i++) { // convert to additive src2[i] = 0xff - src[i]; dest2[i] = 0xff - dest[i]; } // NB: inputs have already been converted to additive mode setSat(src2[0], src2[1], src2[2], getSat(dest2[0], dest2[1], dest2[2]), &r0, &g0, &b0); setLum(r0, g0, b0, getLum(dest2[0], dest2[1], dest2[2]), &r1, &g1, &b1); blend[0] = r1; blend[1] = g1; blend[2] = b1; blend[3] = dest2[3]; for (i = 0; i < 4; i++) { // convert back to subtractive blend[i] = 0xff - blend[i]; } break; #endif } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,794
linux
4d8df8cbb9156b0a0ab3f802b80cb5db57acc0bf
static int ib_prctl_get(struct task_struct *task) { if (!boot_cpu_has_bug(X86_BUG_SPECTRE_V2)) return PR_SPEC_NOT_AFFECTED; if (spectre_v2_user_ibpb == SPECTRE_V2_USER_NONE && spectre_v2_user_stibp == SPECTRE_V2_USER_NONE) return PR_SPEC_ENABLE; else if (spectre_v2_user_ibpb == SPECTRE_V2_USER_STRICT || spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT || spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT_PREFERRED) return PR_SPEC_DISABLE; else if (spectre_v2_user_ibpb == SPECTRE_V2_USER_PRCTL || spectre_v2_user_ibpb == SPECTRE_V2_USER_SECCOMP || spectre_v2_user_stibp == SPECTRE_V2_USER_PRCTL || spectre_v2_user_stibp == SPECTRE_V2_USER_SECCOMP) { if (task_spec_ib_force_disable(task)) return PR_SPEC_PRCTL | PR_SPEC_FORCE_DISABLE; if (task_spec_ib_disable(task)) return PR_SPEC_PRCTL | PR_SPEC_DISABLE; return PR_SPEC_PRCTL | PR_SPEC_ENABLE; } else return PR_SPEC_NOT_AFFECTED; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,669
linux
ee8413b01045c74340aa13ad5bdf905de32be736
void snd_timer_interrupt(struct snd_timer * timer, unsigned long ticks_left) { struct snd_timer_instance *ti, *ts, *tmp; unsigned long resolution, ticks; struct list_head *p, *ack_list_head; unsigned long flags; int use_tasklet = 0; if (timer == NULL) return; spin_lock_irqsave(&timer->lock, flags); /* remember the current resolution */ if (timer->hw.c_resolution) resolution = timer->hw.c_resolution(timer); else resolution = timer->hw.resolution; /* loop for all active instances * Here we cannot use list_for_each_entry because the active_list of a * processed instance is relinked to done_list_head before the callback * is called. */ list_for_each_entry_safe(ti, tmp, &timer->active_list_head, active_list) { if (!(ti->flags & SNDRV_TIMER_IFLG_RUNNING)) continue; ti->pticks += ticks_left; ti->resolution = resolution; if (ti->cticks < ticks_left) ti->cticks = 0; else ti->cticks -= ticks_left; if (ti->cticks) /* not expired */ continue; if (ti->flags & SNDRV_TIMER_IFLG_AUTO) { ti->cticks = ti->ticks; } else { ti->flags &= ~SNDRV_TIMER_IFLG_RUNNING; if (--timer->running) list_del(&ti->active_list); } if ((timer->hw.flags & SNDRV_TIMER_HW_TASKLET) || (ti->flags & SNDRV_TIMER_IFLG_FAST)) ack_list_head = &timer->ack_list_head; else ack_list_head = &timer->sack_list_head; if (list_empty(&ti->ack_list)) list_add_tail(&ti->ack_list, ack_list_head); list_for_each_entry(ts, &ti->slave_active_head, active_list) { ts->pticks = ti->pticks; ts->resolution = resolution; if (list_empty(&ts->ack_list)) list_add_tail(&ts->ack_list, ack_list_head); } } if (timer->flags & SNDRV_TIMER_FLG_RESCHED) snd_timer_reschedule(timer, timer->sticks); if (timer->running) { if (timer->hw.flags & SNDRV_TIMER_HW_STOP) { timer->hw.stop(timer); timer->flags |= SNDRV_TIMER_FLG_CHANGE; } if (!(timer->hw.flags & SNDRV_TIMER_HW_AUTO) || (timer->flags & SNDRV_TIMER_FLG_CHANGE)) { /* restart timer */ timer->flags &= ~SNDRV_TIMER_FLG_CHANGE; timer->hw.start(timer); } } else { timer->hw.stop(timer); } /* now process all fast callbacks */ while (!list_empty(&timer->ack_list_head)) { p = timer->ack_list_head.next; /* get first item */ ti = list_entry(p, struct snd_timer_instance, ack_list); /* remove from ack_list and make empty */ list_del_init(p); ticks = ti->pticks; ti->pticks = 0; ti->flags |= SNDRV_TIMER_IFLG_CALLBACK; spin_unlock(&timer->lock); if (ti->callback) ti->callback(ti, resolution, ticks); spin_lock(&timer->lock); ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK; } /* do we have any slow callbacks? */ use_tasklet = !list_empty(&timer->sack_list_head); spin_unlock_irqrestore(&timer->lock, flags); if (use_tasklet) tasklet_schedule(&timer->task_queue); }
1
CVE-2016-2545
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently.
Phase: Architecture and Design In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance. Phase: Architecture and Design Use thread-safe capabilities such as the data access abstraction in Spring. Phase: Architecture and Design Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring. Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400). Phase: Implementation When using multithreading and operating on shared variables, only use thread-safe functions. Phase: Implementation Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write. Phase: Implementation Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412. Phase: Implementation Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization. Phase: Implementation Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop. Phase: Implementation Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help. Phases: Architecture and Design; Operation Strategy: Environment Hardening Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations
1,813
linux
c3c87e770458aa004bd7ed3f29945ff436fd6511
list_del_event(struct perf_event *event, struct perf_event_context *ctx) { struct perf_cpu_context *cpuctx; /* * We can have double detach due to exit/hot-unplug + close. */ if (!(event->attach_state & PERF_ATTACH_CONTEXT)) return; event->attach_state &= ~PERF_ATTACH_CONTEXT; if (is_cgroup_event(event)) { ctx->nr_cgroups--; cpuctx = __get_cpu_context(ctx); /* * if there are no more cgroup events * then cler cgrp to avoid stale pointer * in update_cgrp_time_from_cpuctx() */ if (!ctx->nr_cgroups) cpuctx->cgrp = NULL; } if (has_branch_stack(event)) ctx->nr_branch_stack--; ctx->nr_events--; if (event->attr.inherit_stat) ctx->nr_stat--; list_del_rcu(&event->event_entry); if (event->group_leader == event) list_del_init(&event->group_entry); update_group_times(event); /* * If event was in error state, then keep it * that way, otherwise bogus counts will be * returned on read(). The only way to get out * of error state is by explicit re-enabling * of the event */ if (event->state > PERF_EVENT_STATE_OFF) event->state = PERF_EVENT_STATE_OFF; ctx->generation++; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,307
linux
a8b0ca17b80e92faab46ee7179ba9e99ccb61233
asmlinkage void do_sparc_fault(struct pt_regs *regs, int text_fault, int write, unsigned long address) { struct vm_area_struct *vma; struct task_struct *tsk = current; struct mm_struct *mm = tsk->mm; unsigned int fixup; unsigned long g2; int from_user = !(regs->psr & PSR_PS); int fault, code; if(text_fault) address = regs->pc; /* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd. * * NOTE! We MUST NOT take any locks for this case. We may * be in an interrupt or a critical region, and should * only copy the information from the master page table, * nothing more. */ code = SEGV_MAPERR; if (!ARCH_SUN4C && address >= TASK_SIZE) goto vmalloc_fault; /* * If we're in an interrupt or have no user * context, we must not take the fault.. */ if (in_atomic() || !mm) goto no_context; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address); down_read(&mm->mmap_sem); /* * The kernel referencing a bad kernel pointer can lock up * a sun4c machine completely, so we must attempt recovery. */ if(!from_user && address >= PAGE_OFFSET) goto bad_area; vma = find_vma(mm, address); if(!vma) goto bad_area; if(vma->vm_start <= address) goto good_area; if(!(vma->vm_flags & VM_GROWSDOWN)) goto bad_area; if(expand_stack(vma, address)) goto bad_area; /* * Ok, we have a good vm_area for this memory access, so * we can handle it.. */ good_area: code = SEGV_ACCERR; if(write) { if(!(vma->vm_flags & VM_WRITE)) goto bad_area; } else { /* Allow reads even for write-only mappings */ if(!(vma->vm_flags & (VM_READ | VM_EXEC))) goto bad_area; } /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault. */ fault = handle_mm_fault(mm, vma, address, write ? FAULT_FLAG_WRITE : 0); if (unlikely(fault & VM_FAULT_ERROR)) { if (fault & VM_FAULT_OOM) goto out_of_memory; else if (fault & VM_FAULT_SIGBUS) goto do_sigbus; BUG(); } if (fault & VM_FAULT_MAJOR) { current->maj_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, address); } else { current->min_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, address); } up_read(&mm->mmap_sem); return; /* * Something tried to access memory that isn't in our memory map.. * Fix it, but check if it's kernel or user first.. */ bad_area: up_read(&mm->mmap_sem); bad_area_nosemaphore: /* User mode accesses just cause a SIGSEGV */ if (from_user) { do_fault_siginfo(code, SIGSEGV, regs, text_fault); return; } /* Is this in ex_table? */ no_context: g2 = regs->u_regs[UREG_G2]; if (!from_user) { fixup = search_extables_range(regs->pc, &g2); if (fixup > 10) { /* Values below are reserved for other things */ extern const unsigned __memset_start[]; extern const unsigned __memset_end[]; extern const unsigned __csum_partial_copy_start[]; extern const unsigned __csum_partial_copy_end[]; #ifdef DEBUG_EXCEPTIONS printk("Exception: PC<%08lx> faddr<%08lx>\n", regs->pc, address); printk("EX_TABLE: insn<%08lx> fixup<%08x> g2<%08lx>\n", regs->pc, fixup, g2); #endif if ((regs->pc >= (unsigned long)__memset_start && regs->pc < (unsigned long)__memset_end) || (regs->pc >= (unsigned long)__csum_partial_copy_start && regs->pc < (unsigned long)__csum_partial_copy_end)) { regs->u_regs[UREG_I4] = address; regs->u_regs[UREG_I5] = regs->pc; } regs->u_regs[UREG_G2] = g2; regs->pc = fixup; regs->npc = regs->pc + 4; return; } } unhandled_fault (address, tsk, regs); do_exit(SIGKILL); /* * We ran out of memory, or some other thing happened to us that made * us unable to handle the page fault gracefully. */ out_of_memory: up_read(&mm->mmap_sem); if (from_user) { pagefault_out_of_memory(); return; } goto no_context; do_sigbus: up_read(&mm->mmap_sem); do_fault_siginfo(BUS_ADRERR, SIGBUS, regs, text_fault); if (!from_user) goto no_context; vmalloc_fault: { /* * Synchronize this task's top level page-table * with the 'reference' page table. */ int offset = pgd_index(address); pgd_t *pgd, *pgd_k; pmd_t *pmd, *pmd_k; pgd = tsk->active_mm->pgd + offset; pgd_k = init_mm.pgd + offset; if (!pgd_present(*pgd)) { if (!pgd_present(*pgd_k)) goto bad_area_nosemaphore; pgd_val(*pgd) = pgd_val(*pgd_k); return; } pmd = pmd_offset(pgd, address); pmd_k = pmd_offset(pgd_k, address); if (pmd_present(*pmd) || !pmd_present(*pmd_k)) goto bad_area_nosemaphore; *pmd = *pmd_k; return; } }
1
CVE-2011-2918
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
3,812
w3m
9cf6926c5d947371dc9e44f32bc7a2fbfca5d469
wc_push_to_iso2022(Str os, wc_wchar_t cc, wc_status *st) { wc_uchar g = 0; wc_bool is_wide = WC_FALSE, retry = WC_FALSE; wc_wchar_t cc2; while (1) { switch (WC_CCS_TYPE(cc.ccs)) { case WC_CCS_A_CS94: if (cc.ccs == WC_CCS_US_ASCII) cc.ccs = st->g0_ccs; g = cs94_gmap[WC_CCS_INDEX(cc.ccs) - WC_F_ISO_BASE]; break; case WC_CCS_A_CS94W: is_wide = 1; switch (cc.ccs) { #ifdef USE_UNICODE case WC_CCS_JIS_X_0212: if (!WcOption.use_jisx0212 && WcOption.use_jisx0213 && WcOption.ucs_conv) { cc2 = wc_jisx0212_to_jisx0213(cc); if (cc2.ccs == WC_CCS_JIS_X_0213_1 || cc2.ccs == WC_CCS_JIS_X_0213_2) { cc = cc2; continue; } } break; case WC_CCS_JIS_X_0213_1: case WC_CCS_JIS_X_0213_2: if (!WcOption.use_jisx0213 && WcOption.use_jisx0212 && WcOption.ucs_conv) { cc2 = wc_jisx0213_to_jisx0212(cc); if (cc2.ccs == WC_CCS_JIS_X_0212) { cc = cc2; continue; } } break; #endif } g = cs94w_gmap[WC_CCS_INDEX(cc.ccs) - WC_F_ISO_BASE]; break; case WC_CCS_A_CS96: g = cs96_gmap[WC_CCS_INDEX(cc.ccs) - WC_F_ISO_BASE]; break; case WC_CCS_A_CS96W: is_wide = 1; g = cs96w_gmap[WC_CCS_INDEX(cc.ccs) - WC_F_ISO_BASE]; break; case WC_CCS_A_CS942: g = cs942_gmap[WC_CCS_INDEX(cc.ccs) - WC_F_ISO_BASE]; break; case WC_CCS_A_UNKNOWN_W: if (WcOption.no_replace) return; is_wide = 1; cc.ccs = WC_CCS_US_ASCII; g = cs94_gmap[WC_CCS_INDEX(cc.ccs) - WC_F_ISO_BASE]; cc.code = ((wc_uint32)WC_REPLACE_W[0] << 8) | WC_REPLACE_W[1]; break; case WC_CCS_A_UNKNOWN: if (WcOption.no_replace) return; cc.ccs = WC_CCS_US_ASCII; g = cs94_gmap[WC_CCS_INDEX(cc.ccs) - WC_F_ISO_BASE]; cc.code = (wc_uint32)WC_REPLACE[0]; break; default: if ((cc.ccs == WC_CCS_JOHAB || cc.ccs == WC_CCS_JOHAB_1 || cc.ccs == WC_CCS_JOHAB_2 || cc.ccs == WC_CCS_JOHAB_3) && cs94w_gmap[WC_F_KS_X_1001 - WC_F_ISO_BASE]) { wc_wchar_t cc2 = wc_johab_to_ksx1001(cc); if (cc2.ccs == WC_CCS_KS_X_1001) { cc = cc2; continue; } } #ifdef USE_UNICODE if (WcOption.ucs_conv) cc = wc_any_to_iso2022(cc, st); else #endif cc.ccs = WC_CCS_IS_WIDE(cc.ccs) ? WC_CCS_UNKNOWN_W : WC_CCS_UNKNOWN; continue; } if (! g) { #ifdef USE_UNICODE if (WcOption.ucs_conv && ! retry) cc = wc_any_to_any_ces(cc, st); else #endif cc.ccs = WC_CCS_IS_WIDE(cc.ccs) ? WC_CCS_UNKNOWN_W : WC_CCS_UNKNOWN; retry = WC_TRUE; continue; } wc_push_iso2022_esc(os, cc.ccs, g, 1, st); if (is_wide) Strcat_char(os, (char)((cc.code >> 8) & 0x7f)); Strcat_char(os, (char)(cc.code & 0x7f)); return; } }
1
CVE-2016-9433
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
9,331
php-src
6c5211a0cef0cc2854eaa387e0eb036e012904d0?w=1
PHP_FUNCTION(mcrypt_module_get_algo_block_size) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir)); }
1
CVE-2016-5769
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
Phase: Requirements Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol. Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. If possible, choose a language or compiler that performs automatic bounds checking. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Use libraries or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106] Phase: Implementation Strategy: Input Validation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range. Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values. Phase: Implementation Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation. Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Phase: Implementation Strategy: Compilation or Build Hardening Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
8,648
libssh-mirror
10b3ebbe61a7031a3dae97f05834442220447181
int ssh_buffer_add_data(struct ssh_buffer_struct *buffer, const void *data, uint32_t len) { buffer_verify(buffer); if (data == NULL) { return -1; } if (buffer->used + len < len) { return -1; } if (buffer->allocated < (buffer->used + len)) { if(buffer->pos > 0) buffer_shift(buffer); if (realloc_buffer(buffer, buffer->used + len) < 0) { return -1; } } memcpy(buffer->data+buffer->used, data, len); buffer->used+=len; buffer_verify(buffer); return 0; }
1
CVE-2020-16135
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
813
FFmpeg
e371f031b942d73e02c090170975561fabd5c264
static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length, AVFrame *p) { int ret; size_t byte_depth = s->bit_depth > 8 ? 2 : 1; if (!(s->state & PNG_IHDR)) { av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n"); return AVERROR_INVALIDDATA; } if (!(s->state & PNG_IDAT)) { /* init image info */ avctx->width = s->width; avctx->height = s->height; s->channels = ff_png_get_nb_channels(s->color_type); s->bits_per_pixel = s->bit_depth * s->channels; s->bpp = (s->bits_per_pixel + 7) >> 3; s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3; if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_RGB) { avctx->pix_fmt = AV_PIX_FMT_RGB24; } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_RGBA; } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_GRAY) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_GRAY) { avctx->pix_fmt = AV_PIX_FMT_GRAY16BE; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_RGB) { avctx->pix_fmt = AV_PIX_FMT_RGB48BE; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_RGBA64BE; } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) && s->color_type == PNG_COLOR_TYPE_PALETTE) { avctx->pix_fmt = AV_PIX_FMT_PAL8; } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) { avctx->pix_fmt = AV_PIX_FMT_MONOBLACK; } else if (s->bit_depth == 8 && s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_YA8; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_YA16BE; } else { av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d " "and color type %d\n", s->bit_depth, s->color_type); return AVERROR_INVALIDDATA; } if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) { switch (avctx->pix_fmt) { case AV_PIX_FMT_RGB24: avctx->pix_fmt = AV_PIX_FMT_RGBA; break; case AV_PIX_FMT_RGB48BE: avctx->pix_fmt = AV_PIX_FMT_RGBA64BE; break; case AV_PIX_FMT_GRAY8: avctx->pix_fmt = AV_PIX_FMT_YA8; break; case AV_PIX_FMT_GRAY16BE: avctx->pix_fmt = AV_PIX_FMT_YA16BE; break; default: avpriv_request_sample(avctx, "bit depth %d " "and color type %d with TRNS", s->bit_depth, s->color_type); return AVERROR_INVALIDDATA; } s->bpp += byte_depth; } if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) { ff_thread_release_buffer(avctx, &s->previous_picture); if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; } ff_thread_finish_setup(avctx); p->pict_type = AV_PICTURE_TYPE_I; p->key_frame = 1; p->interlaced_frame = !!s->interlace_type; /* compute the compressed row size */ if (!s->interlace_type) { s->crow_size = s->row_size + 1; } else { s->pass = 0; s->pass_row_size = ff_png_pass_row_size(s->pass, s->bits_per_pixel, s->cur_w); s->crow_size = s->pass_row_size + 1; } ff_dlog(avctx, "row_size=%d crow_size =%d\n", s->row_size, s->crow_size); s->image_buf = p->data[0]; s->image_linesize = p->linesize[0]; /* copy the palette if needed */ if (avctx->pix_fmt == AV_PIX_FMT_PAL8) memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t)); /* empty row is used if differencing to the first row */ av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size); if (!s->last_row) return AVERROR_INVALIDDATA; if (s->interlace_type || s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size); if (!s->tmp_row) return AVERROR_INVALIDDATA; } /* compressed row */ av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16); if (!s->buffer) return AVERROR(ENOMEM); /* we want crow_buf+1 to be 16-byte aligned */ s->crow_buf = s->buffer + 15; s->zstream.avail_out = s->crow_size; s->zstream.next_out = s->crow_buf; } s->state |= PNG_IDAT; /* set image to non-transparent bpp while decompressing */ if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) s->bpp -= byte_depth; ret = png_decode_idat(s, length); if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) s->bpp += byte_depth; if (ret < 0) return ret; bytestream2_skip(&s->gb, 4); /* crc */ return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,975
varnish-cache
c5fd097e5cce8b461c6443af02b3448baef2491d
http_EstimateWS(const struct http *fm, unsigned how) { unsigned u, l; l = 4; CHECK_OBJ_NOTNULL(fm, HTTP_MAGIC); for (u = 0; u < fm->nhd; u++) { if (u == HTTP_HDR_METHOD || u == HTTP_HDR_URL) continue; Tcheck(fm->hd[u]); if (http_isfiltered(fm, u, how)) continue; l += Tlen(fm->hd[u]) + 1L; } return (PRNDUP(l + 1L)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,085
krb5
5e6d1796106df8ba6bc1973ee0917c170d929086
add_pa_data_element(krb5_pa_data ***list, krb5_pa_data *pa) { size_t count; krb5_pa_data **newlist; for (count = 0; *list != NULL && (*list)[count] != NULL; count++); newlist = realloc(*list, (count + 2) * sizeof(*newlist)); if (newlist == NULL) { free(pa->contents); free(pa); return ENOMEM; } newlist[count] = pa; newlist[count + 1] = NULL; *list = newlist; return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,048
tensorflow
6c0b2b70eeee588591680f5b7d5d38175fd7cdf6
TfLiteStatus EvalFloat(TfLiteContext* context, TfLiteNode* node, TfLiteFullyConnectedParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output) { float output_activation_min, output_activation_max; CalculateActivationRange(params->activation, &output_activation_min, &output_activation_max); if (kernel_type == kReference) { FullyConnectedParams op_params; op_params.float_activation_min = output_activation_min; op_params.float_activation_max = output_activation_max; if (filter->sparsity != nullptr) { const auto& sparsity = *filter->sparsity; reference_ops::FullyConnectedSparseWeight( sparsity, op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(filter), GetTensorData<float>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output)); } else { reference_ops::FullyConnected( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(filter), GetTensorData<float>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output)); } } else if (kernel_type == kLegacyPie) { return EvalPie(context, node, params, data, input, filter, bias, output); } else { FullyConnectedParams op_params; op_params.float_activation_min = output_activation_min; op_params.float_activation_max = output_activation_max; if (filter->sparsity != nullptr) { const auto& sparsity = *filter->sparsity; if (!SupportedSparsityFormat(sparsity)) { TF_LITE_KERNEL_LOG(context, "Unsupported sparse fully-connected weight format."); return kTfLiteError; } if (sparsity.dim_metadata_size == kDimMetadataSizeRandomSparse) { // Random sparse. optimized_ops::FullyConnectedSparseWeight( sparsity, op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(filter), GetTensorData<float>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output)); } else if (sparsity.dim_metadata_size == kDimMetadataSizeBlockSparse && sparsity.dim_metadata[2].dense_size == 4) { // Block sparse with block size of 1x4. optimized_ops::FullyConnectedSparseWeight1x4( sparsity, op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(filter), GetTensorData<float>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output), CpuBackendContext::GetFromContext(context)); } else { TF_LITE_KERNEL_LOG(context, "Unsupported sparse fully-connected weight format."); return kTfLiteError; } } else { op_params.lhs_cacheable = IsConstantTensor(filter); op_params.rhs_cacheable = IsConstantTensor(input); optimized_ops::FullyConnected( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(filter), GetTensorData<float>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output), CpuBackendContext::GetFromContext(context)); } } return kTfLiteOk; }
1
CVE-2022-23561
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
6,150
neomutt
6f163e07ae68654d7ac5268cbb7565f6df79ad85
void test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } }
1
CVE-2018-14359
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
2,138