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
|
---|---|---|---|---|---|---|---|---|---|
FreeRDP | e7bffa64ef5ed70bac94f823e2b95262642f5296 | static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
BOOL rc;
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
UINT32 new_len;
BYTE* new_data;
CACHE_BITMAP_V3_ORDER* cache_bitmap_v3;
if (!update || !s)
return NULL;
cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER));
if (!cache_bitmap_v3)
goto fail;
cache_bitmap_v3->cacheId = flags & 0x00000003;
cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7;
bitsPerPixelId = (flags & 0x00000078) >> 3;
cache_bitmap_v3->bpp = get_cbr2_bpp(bitsPerPixelId, &rc);
if (!rc)
goto fail;
if (Stream_GetRemainingLength(s) < 21)
goto fail;
Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
bitmapData = &cache_bitmap_v3->bitmapData;
Stream_Read_UINT8(s, bitmapData->bpp);
if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32))
{
WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp);
goto fail;
}
Stream_Seek_UINT8(s); /* reserved1 (1 byte) */
Stream_Seek_UINT8(s); /* reserved2 (1 byte) */
Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Read_UINT32(s, new_len); /* length (4 bytes) */
if ((new_len == 0) || (Stream_GetRemainingLength(s) < new_len))
goto fail;
new_data = (BYTE*)realloc(bitmapData->data, new_len);
if (!new_data)
goto fail;
bitmapData->data = new_data;
bitmapData->length = new_len;
Stream_Read(s, bitmapData->data, bitmapData->length);
return cache_bitmap_v3;
fail:
free_cache_bitmap_v3_order(update->context, cache_bitmap_v3);
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,309 |
cryptopp | 07dbcc3d9644b18e05c1776db2a57fe04d780965 | void Inflator::OutputByte(byte b)
{
m_window[m_current++] = b;
if (m_current == m_window.size())
{
ProcessDecompressedData(m_window + m_lastFlush, m_window.size() - m_lastFlush);
m_lastFlush = 0;
m_current = 0;
m_wrappedAround = true;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,382 |
linux | 2a3f7221acddfe1caa9ff09b3a8158c39b2fdeac | card_id_show_attr(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct snd_card *card = container_of(dev, struct snd_card, card_dev);
return scnprintf(buf, PAGE_SIZE, "%s\n", card->id);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,384 |
linux | 0d0e57697f162da4aa218b5feafe614fb666db07 | static bool is_spillable_regtype(enum bpf_reg_type type)
{
switch (type) {
case PTR_TO_MAP_VALUE:
case PTR_TO_MAP_VALUE_OR_NULL:
case PTR_TO_MAP_VALUE_ADJ:
case PTR_TO_STACK:
case PTR_TO_CTX:
case PTR_TO_PACKET:
case PTR_TO_PACKET_END:
case FRAME_PTR:
case CONST_PTR_TO_MAP:
return true;
default:
return false;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,790 |
openvpn | 37bc691e7d26ea4eb61a8a434ebd7a9ae76225ab | int_compare_function(const void *key1, const void *key2)
{
return (unsigned long)key1 == (unsigned long)key2;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,476 |
tensorflow | 002408c3696b173863228223d535f9de72a101a9 | void Compute(OpKernelContext* context) override {
// Here's the basic idea:
// Batch and depth dimension are independent from row and col dimension. And
// because FractionalAvgPool currently only support pooling along row and
// col, we can basically think of this 4D tensor backpropagation as
// operation of a series of 2D planes.
//
// For each element of a 'slice' (2D plane) of output_backprop, we need to
// figure out its contributors when doing FractionalAvgPool operation. This
// can be done based on row_pooling_sequence, col_pooling_seq and
// overlapping.
// Once we figure out the original contributors, we just need to evenly
// divide the value of this element among these contributors.
//
// Internally, we divide the out_backprop tensor and store it in a temporary
// tensor of double type. And cast it to the corresponding type.
typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
ConstEigenMatrixMap;
typedef Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>>
EigenDoubleMatrixMap;
// Grab the inputs.
const Tensor& orig_input_tensor_shape = context->input(0);
OP_REQUIRES(context,
orig_input_tensor_shape.dims() == 1 &&
orig_input_tensor_shape.NumElements() == 4,
errors::InvalidArgument("original input tensor shape must be"
"1-dimensional and 4 elements"));
const Tensor& out_backprop = context->input(1);
const Tensor& row_seq_tensor = context->input(2);
const Tensor& col_seq_tensor = context->input(3);
const int64_t out_batch = out_backprop.dim_size(0);
const int64_t out_rows = out_backprop.dim_size(1);
const int64_t out_cols = out_backprop.dim_size(2);
const int64_t out_depth = out_backprop.dim_size(3);
OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,
errors::InvalidArgument("Given out_backprop shape ",
out_backprop.shape().DebugString(),
", row_seq_tensor must have at least ",
out_rows + 1, " elements, but got ",
row_seq_tensor.NumElements()));
OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,
errors::InvalidArgument("Given out_backprop shape ",
out_backprop.shape().DebugString(),
", col_seq_tensor must have at least ",
out_cols + 1, " elements, but got ",
col_seq_tensor.NumElements()));
auto row_seq_tensor_flat = row_seq_tensor.flat<int64_t>();
auto col_seq_tensor_flat = col_seq_tensor.flat<int64_t>();
auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat<int64_t>();
const int64_t in_batch = orig_input_tensor_shape_flat(0);
const int64_t in_rows = orig_input_tensor_shape_flat(1);
const int64_t in_cols = orig_input_tensor_shape_flat(2);
const int64_t in_depth = orig_input_tensor_shape_flat(3);
OP_REQUIRES(
context, in_batch != 0,
errors::InvalidArgument("Batch dimension of input must not be 0"));
OP_REQUIRES(
context, in_rows != 0,
errors::InvalidArgument("Rows dimension of input must not be 0"));
OP_REQUIRES(
context, in_cols != 0,
errors::InvalidArgument("Columns dimension of input must not be 0"));
OP_REQUIRES(
context, in_depth != 0,
errors::InvalidArgument("Depth dimension of input must not be 0"));
constexpr int tensor_in_and_out_dims = 4;
// Transform orig_input_tensor_shape into TensorShape
TensorShape in_shape;
for (auto i = 0; i < tensor_in_and_out_dims; ++i) {
in_shape.AddDim(orig_input_tensor_shape_flat(i));
}
// Create intermediate in_backprop.
Tensor in_backprop_tensor_temp;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(
{0}, DataTypeToEnum<double>::v(), in_shape,
&in_backprop_tensor_temp));
in_backprop_tensor_temp.flat<double>().setZero();
// Transform 4D tensor to 2D matrix.
EigenDoubleMatrixMap in_backprop_tensor_temp_mat(
in_backprop_tensor_temp.flat<double>().data(), in_depth,
in_cols * in_rows * in_batch);
ConstEigenMatrixMap out_backprop_mat(out_backprop.flat<T>().data(),
out_depth,
out_cols * out_rows * out_batch);
// Loop through each element of out_backprop and evenly distribute the
// element to the corresponding pooling cell.
const int64_t in_max_row_index = in_rows - 1;
const int64_t in_max_col_index = in_cols - 1;
for (int64_t b = 0; b < out_batch; ++b) {
for (int64_t r = 0; r < out_rows; ++r) {
const int64_t in_row_start = row_seq_tensor_flat(r);
int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)
: row_seq_tensor_flat(r + 1) - 1;
in_row_end = std::min(in_row_end, in_max_row_index);
OP_REQUIRES(context, in_row_start >= 0 && in_row_end >= 0,
errors::InvalidArgument(
"Row sequence tensor values must not be negative, got ",
row_seq_tensor_flat));
for (int64_t c = 0; c < out_cols; ++c) {
const int64_t in_col_start = col_seq_tensor_flat(c);
int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)
: col_seq_tensor_flat(c + 1) - 1;
in_col_end = std::min(in_col_end, in_max_col_index);
OP_REQUIRES(
context, in_col_start >= 0 && in_col_end >= 0,
errors::InvalidArgument(
"Column sequence tensor values must not be negative, got ",
col_seq_tensor_flat));
const int64_t num_elements_in_pooling_cell =
(in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);
const int64_t out_index = (b * out_rows + r) * out_cols + c;
// Now we can evenly distribute out_backprop(b, h, w, *) to
// in_backprop(b, hs:he, ws:we, *).
for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) {
for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) {
const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c;
// Walk through each channel (depth).
for (int64_t d = 0; d < out_depth; ++d) {
const double out_backprop_element = static_cast<double>(
out_backprop_mat.coeffRef(d, out_index));
double& in_backprop_ref =
in_backprop_tensor_temp_mat.coeffRef(d, in_index);
in_backprop_ref +=
out_backprop_element / num_elements_in_pooling_cell;
}
}
}
}
}
}
// Depending on the type, cast double to type T.
Tensor* in_backprop_tensor = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 0, in_shape, &in_backprop_tensor));
auto in_backprop_tensor_flat = in_backprop_tensor->flat<T>();
auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat<double>();
for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) {
in_backprop_tensor_flat(i) =
static_cast<T>(in_backprop_tensor_temp_flat(i));
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,104 |
vim | 57df9e8a9f9ae1aafdde9b86b10ad907627a87dc | free_operatorfunc_option(void)
{
# ifdef FEAT_EVAL
free_callback(&opfunc_cb);
# endif
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,845 |
exim | e2f5dc151e2e79058e93924e6d35510557f0535d | find_option(uschar *name, optionlist *ol, int last)
{
int first = 0;
while (last > first)
{
int middle = (first + last)/2;
int c = Ustrcmp(name, ol[middle].name);
if (c == 0) return ol + middle;
else if (c > 0) first = middle + 1;
else last = middle;
}
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,532 |
linux | 2b472611a32a72f4a118c069c2d62a1a3f087afd | static ssize_t sleep_millisecs_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,546 |
linux | 362bca57f5d78220f8b5907b875961af9436e229 | static void snd_pcm_substream_proc_status_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_substream *substream = entry->private_data;
struct snd_pcm_runtime *runtime;
struct snd_pcm_status status;
int err;
mutex_lock(&substream->pcm->open_mutex);
runtime = substream->runtime;
if (!runtime) {
snd_iprintf(buffer, "closed\n");
goto unlock;
}
memset(&status, 0, sizeof(status));
err = snd_pcm_status(substream, &status);
if (err < 0) {
snd_iprintf(buffer, "error %d\n", err);
goto unlock;
}
snd_iprintf(buffer, "state: %s\n", snd_pcm_state_name(status.state));
snd_iprintf(buffer, "owner_pid : %d\n", pid_vnr(substream->pid));
snd_iprintf(buffer, "trigger_time: %ld.%09ld\n",
status.trigger_tstamp.tv_sec, status.trigger_tstamp.tv_nsec);
snd_iprintf(buffer, "tstamp : %ld.%09ld\n",
status.tstamp.tv_sec, status.tstamp.tv_nsec);
snd_iprintf(buffer, "delay : %ld\n", status.delay);
snd_iprintf(buffer, "avail : %ld\n", status.avail);
snd_iprintf(buffer, "avail_max : %ld\n", status.avail_max);
snd_iprintf(buffer, "-----\n");
snd_iprintf(buffer, "hw_ptr : %ld\n", runtime->status->hw_ptr);
snd_iprintf(buffer, "appl_ptr : %ld\n", runtime->control->appl_ptr);
unlock:
mutex_unlock(&substream->pcm->open_mutex);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,098 |
krb5 | f0c094a1b745d91ef2f9a4eae2149aac026a5789 | krb5_anonymous_realm()
{
return &anon_realm_data;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,140 |
Chrome | 04aaacb936a08d70862d6d9d7e8354721ae46be8 | void AppCache::RemoveEntry(const GURL& url) {
auto found = entries_.find(url);
DCHECK(found != entries_.end());
cache_size_ -= found->second.response_size();
entries_.erase(found);
}
| 1 | CVE-2019-5837 | 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. | 7,352 |
sudo | fa8ffeb17523494f0e8bb49a25e53635f4509078 | tgetpass_display_error(enum tgetpass_errval errval)
{
debug_decl(tgetpass_display_error, SUDO_DEBUG_CONV);
switch (errval) {
case TGP_ERRVAL_NOERROR:
break;
case TGP_ERRVAL_TIMEOUT:
sudo_warnx(U_("timed out reading password"));
break;
case TGP_ERRVAL_NOPASSWORD:
sudo_warnx(U_("no password was provided"));
break;
case TGP_ERRVAL_READERROR:
sudo_warn(U_("unable to read password"));
break;
}
debug_return;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,249 |
vim | 05b27615481e72e3b338bb12990fb3e0c2ecc2a9 | frame_setwidth(frame_T *curfrp, int width)
{
int room; // total number of lines available
int take; // number of lines taken from other windows
int run;
frame_T *frp;
int w;
int room_reserved;
// If the width already is the desired value, nothing to do.
if (curfrp->fr_width == width)
return;
if (curfrp->fr_parent == NULL)
// topframe: can't change width
return;
if (curfrp->fr_parent->fr_layout == FR_COL)
{
// Column of frames: Also need to resize frames above and below of
// this one. First check for the minimal width of these.
w = frame_minwidth(curfrp->fr_parent, NULL);
if (width < w)
width = w;
frame_setwidth(curfrp->fr_parent, width);
}
else
{
/*
* Row of frames: try to change only frames in this row.
*
* Do this twice:
* 1: compute room available, if it's not enough try resizing the
* containing frame.
* 2: compute the room available and adjust the width to it.
*/
for (run = 1; run <= 2; ++run)
{
room = 0;
room_reserved = 0;
FOR_ALL_FRAMES(frp, curfrp->fr_parent->fr_child)
{
if (frp != curfrp
&& frp->fr_win != NULL
&& frp->fr_win->w_p_wfw)
room_reserved += frp->fr_width;
room += frp->fr_width;
if (frp != curfrp)
room -= frame_minwidth(frp, NULL);
}
if (width <= room)
break;
if (run == 2 || curfrp->fr_height >= ROWS_AVAIL)
{
if (width > room)
width = room;
break;
}
frame_setwidth(curfrp->fr_parent, width
+ frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1);
}
/*
* Compute the number of lines we will take from others frames (can be
* negative!).
*/
take = width - curfrp->fr_width;
// If there is not enough room, also reduce the width of a window
// with 'winfixwidth' set.
if (width > room - room_reserved)
room_reserved = room - width;
// If there is only a 'winfixwidth' window and making the
// window smaller, need to make the other window narrower.
if (take < 0 && room - curfrp->fr_width < room_reserved)
room_reserved = 0;
/*
* set the current frame to the new width
*/
frame_new_width(curfrp, width, FALSE, FALSE);
/*
* First take lines from the frames right of the current frame. If
* that is not enough, takes lines from frames left of the current
* frame.
*/
for (run = 0; run < 2; ++run)
{
if (run == 0)
frp = curfrp->fr_next; // 1st run: start with next window
else
frp = curfrp->fr_prev; // 2nd run: start with prev window
while (frp != NULL && take != 0)
{
w = frame_minwidth(frp, NULL);
if (room_reserved > 0
&& frp->fr_win != NULL
&& frp->fr_win->w_p_wfw)
{
if (room_reserved >= frp->fr_width)
room_reserved -= frp->fr_width;
else
{
if (frp->fr_width - room_reserved > take)
room_reserved = frp->fr_width - take;
take -= frp->fr_width - room_reserved;
frame_new_width(frp, room_reserved, FALSE, FALSE);
room_reserved = 0;
}
}
else
{
if (frp->fr_width - take < w)
{
take -= frp->fr_width - w;
frame_new_width(frp, w, FALSE, FALSE);
}
else
{
frame_new_width(frp, frp->fr_width - take,
FALSE, FALSE);
take = 0;
}
}
if (run == 0)
frp = frp->fr_next;
else
frp = frp->fr_prev;
}
}
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,656 |
libxml2 | f1063fdbe7fa66332bbb76874101c2a7b51b519f | xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
const xmlChar **URI, int *tlen) {
const xmlChar *localname;
const xmlChar *prefix;
const xmlChar *attname;
const xmlChar *aprefix;
const xmlChar *nsname;
xmlChar *attvalue;
const xmlChar **atts = ctxt->atts;
int maxatts = ctxt->maxatts;
int nratts, nbatts, nbdef;
int i, j, nbNs, attval, oldline, oldcol;
const xmlChar *base;
unsigned long cur;
int nsNr = ctxt->nsNr;
if (RAW != '<') return(NULL);
NEXT1;
/*
* NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that
* point since the attribute values may be stored as pointers to
* the buffer and calling SHRINK would destroy them !
* The Shrinking is only possible once the full set of attribute
* callbacks have been done.
*/
reparse:
SHRINK;
base = ctxt->input->base;
cur = ctxt->input->cur - ctxt->input->base;
oldline = ctxt->input->line;
oldcol = ctxt->input->col;
nbatts = 0;
nratts = 0;
nbdef = 0;
nbNs = 0;
attval = 0;
/* Forget any namespaces added during an earlier parse of this element. */
ctxt->nsNr = nsNr;
localname = xmlParseQName(ctxt, &prefix);
if (localname == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"StartTag: invalid element name\n");
return(NULL);
}
*tlen = ctxt->input->cur - ctxt->input->base - cur;
/*
* Now parse the attributes, it ends up with the ending
*
* (S Attribute)* S?
*/
SKIP_BLANKS;
GROW;
if (ctxt->input->base != base) goto base_changed;
while (((RAW != '>') &&
((RAW != '/') || (NXT(1) != '>')) &&
(IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *q = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
int len = -1, alloc = 0;
attname = xmlParseAttribute2(ctxt, prefix, localname,
&aprefix, &attvalue, &len, &alloc);
if (ctxt->input->base != base) {
if ((attvalue != NULL) && (alloc != 0))
xmlFree(attvalue);
attvalue = NULL;
goto base_changed;
}
if ((attname != NULL) && (attvalue != NULL)) {
if (len < 0) len = xmlStrlen(attvalue);
if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
xmlURIPtr uri;
if (URL == NULL) {
xmlErrMemory(ctxt, "dictionary allocation failure");
if ((attvalue != NULL) && (alloc != 0))
xmlFree(attvalue);
return(NULL);
}
if (*URL != 0) {
uri = xmlParseURI((const char *) URL);
if (uri == NULL) {
xmlNsErr(ctxt, XML_WAR_NS_URI,
"xmlns: '%s' is not a valid URI\n",
URL, NULL, NULL);
} else {
if (uri->scheme == NULL) {
xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
"xmlns: URI %s is not absolute\n",
URL, NULL, NULL);
}
xmlFreeURI(uri);
}
if (URL == ctxt->str_xml_ns) {
if (attname != ctxt->str_xml) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace URI cannot be the default namespace\n",
NULL, NULL, NULL);
}
goto skip_default_ns;
}
if ((len == 29) &&
(xmlStrEqual(URL,
BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"reuse of the xmlns namespace name is forbidden\n",
NULL, NULL, NULL);
goto skip_default_ns;
}
}
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
break;
if (j <= nbNs)
xmlErrAttributeDup(ctxt, NULL, attname);
else
if (nsPush(ctxt, NULL, URL) > 0) nbNs++;
skip_default_ns:
if (alloc != 0) xmlFree(attvalue);
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
SKIP_BLANKS;
continue;
}
if (aprefix == ctxt->str_xmlns) {
const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
xmlURIPtr uri;
if (attname == ctxt->str_xml) {
if (URL != ctxt->str_xml_ns) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace prefix mapped to wrong URI\n",
NULL, NULL, NULL);
}
/*
* Do not keep a namespace definition node
*/
goto skip_ns;
}
if (URL == ctxt->str_xml_ns) {
if (attname != ctxt->str_xml) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace URI mapped to wrong prefix\n",
NULL, NULL, NULL);
}
goto skip_ns;
}
if (attname == ctxt->str_xmlns) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"redefinition of the xmlns prefix is forbidden\n",
NULL, NULL, NULL);
goto skip_ns;
}
if ((len == 29) &&
(xmlStrEqual(URL,
BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"reuse of the xmlns namespace name is forbidden\n",
NULL, NULL, NULL);
goto skip_ns;
}
if ((URL == NULL) || (URL[0] == 0)) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xmlns:%s: Empty XML namespace is not allowed\n",
attname, NULL, NULL);
goto skip_ns;
} else {
uri = xmlParseURI((const char *) URL);
if (uri == NULL) {
xmlNsErr(ctxt, XML_WAR_NS_URI,
"xmlns:%s: '%s' is not a valid URI\n",
attname, URL, NULL);
} else {
if ((ctxt->pedantic) && (uri->scheme == NULL)) {
xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
"xmlns:%s: URI %s is not absolute\n",
attname, URL, NULL);
}
xmlFreeURI(uri);
}
}
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
break;
if (j <= nbNs)
xmlErrAttributeDup(ctxt, aprefix, attname);
else
if (nsPush(ctxt, attname, URL) > 0) nbNs++;
skip_ns:
if (alloc != 0) xmlFree(attvalue);
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
SKIP_BLANKS;
if (ctxt->input->base != base) goto base_changed;
continue;
}
/*
* Add the pair to atts
*/
if ((atts == NULL) || (nbatts + 5 > maxatts)) {
if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
if (attvalue[len] == 0)
xmlFree(attvalue);
goto failed;
}
maxatts = ctxt->maxatts;
atts = ctxt->atts;
}
ctxt->attallocs[nratts++] = alloc;
atts[nbatts++] = attname;
atts[nbatts++] = aprefix;
atts[nbatts++] = NULL; /* the URI will be fetched later */
atts[nbatts++] = attvalue;
attvalue += len;
atts[nbatts++] = attvalue;
/*
* tag if some deallocation is needed
*/
if (alloc != 0) attval = 1;
} else {
if ((attvalue != NULL) && (attvalue[len] == 0))
xmlFree(attvalue);
}
failed:
GROW
if (ctxt->instate == XML_PARSER_EOF)
break;
if (ctxt->input->base != base) goto base_changed;
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
SKIP_BLANKS;
if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
(attname == NULL) && (attvalue == NULL)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseStartTag: problem parsing attributes\n");
break;
}
GROW;
if (ctxt->input->base != base) goto base_changed;
}
/*
* The attributes defaulting
*/
if (ctxt->attsDefault != NULL) {
xmlDefAttrsPtr defaults;
defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
if (defaults != NULL) {
for (i = 0;i < defaults->nbAttrs;i++) {
attname = defaults->values[5 * i];
aprefix = defaults->values[5 * i + 1];
/*
* special work for namespaces defaulted defs
*/
if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
break;
if (j <= nbNs) continue;
nsname = xmlGetNamespace(ctxt, NULL);
if (nsname != defaults->values[5 * i + 2]) {
if (nsPush(ctxt, NULL,
defaults->values[5 * i + 2]) > 0)
nbNs++;
}
} else if (aprefix == ctxt->str_xmlns) {
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
break;
if (j <= nbNs) continue;
nsname = xmlGetNamespace(ctxt, attname);
if (nsname != defaults->values[2]) {
if (nsPush(ctxt, attname,
defaults->values[5 * i + 2]) > 0)
nbNs++;
}
} else {
/*
* check that it's not a defined attribute
*/
for (j = 0;j < nbatts;j+=5) {
if ((attname == atts[j]) && (aprefix == atts[j+1]))
break;
}
if (j < nbatts) continue;
if ((atts == NULL) || (nbatts + 5 > maxatts)) {
if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
return(NULL);
}
maxatts = ctxt->maxatts;
atts = ctxt->atts;
}
atts[nbatts++] = attname;
atts[nbatts++] = aprefix;
if (aprefix == NULL)
atts[nbatts++] = NULL;
else
atts[nbatts++] = xmlGetNamespace(ctxt, aprefix);
atts[nbatts++] = defaults->values[5 * i + 2];
atts[nbatts++] = defaults->values[5 * i + 3];
if ((ctxt->standalone == 1) &&
(defaults->values[5 * i + 4] != NULL)) {
xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED,
"standalone: attribute %s on %s defaulted from external subset\n",
attname, localname);
}
nbdef++;
}
}
}
}
/*
* The attributes checkings
*/
for (i = 0; i < nbatts;i += 5) {
/*
* The default namespace does not apply to attribute names.
*/
if (atts[i + 1] != NULL) {
nsname = xmlGetNamespace(ctxt, atts[i + 1]);
if (nsname == NULL) {
xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
"Namespace prefix %s for %s on %s is not defined\n",
atts[i + 1], atts[i], localname);
}
atts[i + 2] = nsname;
} else
nsname = NULL;
/*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same
* start-tag or empty-element tag.
* As extended by the Namespace in XML REC.
*/
for (j = 0; j < i;j += 5) {
if (atts[i] == atts[j]) {
if (atts[i+1] == atts[j+1]) {
xmlErrAttributeDup(ctxt, atts[i+1], atts[i]);
break;
}
if ((nsname != NULL) && (atts[j + 2] == nsname)) {
xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
"Namespaced Attribute %s in '%s' redefined\n",
atts[i], nsname, NULL);
break;
}
}
}
}
nsname = xmlGetNamespace(ctxt, prefix);
if ((prefix != NULL) && (nsname == NULL)) {
xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
"Namespace prefix %s on %s is not defined\n",
prefix, localname, NULL);
}
*pref = prefix;
*URI = nsname;
/*
* SAX: Start of Element !
*/
if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) &&
(!ctxt->disableSAX)) {
if (nbNs > 0)
ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs],
nbatts / 5, nbdef, atts);
else
ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
nsname, 0, NULL, nbatts / 5, nbdef, atts);
}
/*
* Free up attribute allocated strings if needed
*/
if (attval != 0) {
for (i = 3,j = 0; j < nratts;i += 5,j++)
if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
xmlFree((xmlChar *) atts[i]);
}
return(localname);
base_changed:
/*
* the attribute strings are valid iif the base didn't changed
*/
if (attval != 0) {
for (i = 3,j = 0; j < nratts;i += 5,j++)
if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
xmlFree((xmlChar *) atts[i]);
}
ctxt->input->cur = ctxt->input->base + cur;
ctxt->input->line = oldline;
ctxt->input->col = oldcol;
if (ctxt->wellFormed == 1) {
goto reparse;
}
return(NULL);
} | 1 | CVE-2015-7500 | 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,506 |
linux | a117dacde0288f3ec60b6e5bcedae8fa37ee0dfc | static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
unsigned long arg, int ifreq_len)
{
struct tun_file *tfile = file->private_data;
struct tun_struct *tun;
void __user* argp = (void __user*)arg;
struct sock_fprog fprog;
struct ifreq ifr;
int sndbuf;
int vnet_hdr_sz;
int ret;
if (cmd == TUNSETIFF || _IOC_TYPE(cmd) == 0x89)
if (copy_from_user(&ifr, argp, ifreq_len))
return -EFAULT;
if (cmd == TUNGETFEATURES) {
/* Currently this just means: "what IFF flags are valid?".
* This is needed because we never checked for invalid flags on
* TUNSETIFF. */
return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
IFF_VNET_HDR,
(unsigned int __user*)argp);
}
rtnl_lock();
tun = __tun_get(tfile);
if (cmd == TUNSETIFF && !tun) {
ifr.ifr_name[IFNAMSIZ-1] = '\0';
ret = tun_set_iff(tfile->net, file, &ifr);
if (ret)
goto unlock;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
goto unlock;
}
ret = -EBADFD;
if (!tun)
goto unlock;
tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %d\n", cmd);
ret = 0;
switch (cmd) {
case TUNGETIFF:
ret = tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
if (ret)
break;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
break;
case TUNSETNOCSUM:
/* Disable/Enable checksum */
/* [unimplemented] */
tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
arg ? "disabled" : "enabled");
break;
case TUNSETPERSIST:
/* Disable/Enable persist mode */
if (arg)
tun->flags |= TUN_PERSIST;
else
tun->flags &= ~TUN_PERSIST;
tun_debug(KERN_INFO, tun, "persist %s\n",
arg ? "enabled" : "disabled");
break;
case TUNSETOWNER:
/* Set owner of the device */
tun->owner = (uid_t) arg;
tun_debug(KERN_INFO, tun, "owner set to %d\n", tun->owner);
break;
case TUNSETGROUP:
/* Set group of the device */
tun->group= (gid_t) arg;
tun_debug(KERN_INFO, tun, "group set to %d\n", tun->group);
break;
case TUNSETLINK:
/* Only allow setting the type when the interface is down */
if (tun->dev->flags & IFF_UP) {
tun_debug(KERN_INFO, tun,
"Linktype set failed because interface is up\n");
ret = -EBUSY;
} else {
tun->dev->type = (int) arg;
tun_debug(KERN_INFO, tun, "linktype set to %d\n",
tun->dev->type);
ret = 0;
}
break;
#ifdef TUN_DEBUG
case TUNSETDEBUG:
tun->debug = arg;
break;
#endif
case TUNSETOFFLOAD:
ret = set_offload(tun, arg);
break;
case TUNSETTXFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = update_filter(&tun->txflt, (void __user *)arg);
break;
case SIOCGIFHWADDR:
/* Get hw address */
memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
ifr.ifr_hwaddr.sa_family = tun->dev->type;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
break;
case SIOCSIFHWADDR:
/* Set hw address */
tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
ifr.ifr_hwaddr.sa_data);
ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
break;
case TUNGETSNDBUF:
sndbuf = tun->socket.sk->sk_sndbuf;
if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
ret = -EFAULT;
break;
case TUNSETSNDBUF:
if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
ret = -EFAULT;
break;
}
tun->socket.sk->sk_sndbuf = sndbuf;
break;
case TUNGETVNETHDRSZ:
vnet_hdr_sz = tun->vnet_hdr_sz;
if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
ret = -EFAULT;
break;
case TUNSETVNETHDRSZ:
if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
ret = -EFAULT;
break;
}
if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
ret = -EINVAL;
break;
}
tun->vnet_hdr_sz = vnet_hdr_sz;
break;
case TUNATTACHFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = -EFAULT;
if (copy_from_user(&fprog, argp, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, tun->socket.sk);
break;
case TUNDETACHFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = sk_detach_filter(tun->socket.sk);
break;
default:
ret = -EINVAL;
break;
}
unlock:
rtnl_unlock();
if (tun)
tun_put(tun);
return ret;
}
| 1 | CVE-2012-6547 | 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. | 5,705 |
linux | fa00c437eef8dc2e7b25f8cd868cfa405fcc2bb3 | static int aac_send_raw_srb(struct aac_dev* dev, void __user * arg)
{
struct fib* srbfib;
int status;
struct aac_srb *srbcmd = NULL;
struct user_aac_srb *user_srbcmd = NULL;
struct user_aac_srb __user *user_srb = arg;
struct aac_srb_reply __user *user_reply;
struct aac_srb_reply* reply;
u32 fibsize = 0;
u32 flags = 0;
s32 rcode = 0;
u32 data_dir;
void __user *sg_user[32];
void *sg_list[32];
u32 sg_indx = 0;
u32 byte_count = 0;
u32 actual_fibsize64, actual_fibsize = 0;
int i;
if (dev->in_reset) {
dprintk((KERN_DEBUG"aacraid: send raw srb -EBUSY\n"));
return -EBUSY;
}
if (!capable(CAP_SYS_ADMIN)){
dprintk((KERN_DEBUG"aacraid: No permission to send raw srb\n"));
return -EPERM;
}
/*
* Allocate and initialize a Fib then setup a SRB command
*/
if (!(srbfib = aac_fib_alloc(dev))) {
return -ENOMEM;
}
aac_fib_init(srbfib);
/* raw_srb FIB is not FastResponseCapable */
srbfib->hw_fib_va->header.XferState &= ~cpu_to_le32(FastResponseCapable);
srbcmd = (struct aac_srb*) fib_data(srbfib);
memset(sg_list, 0, sizeof(sg_list)); /* cleanup may take issue */
if(copy_from_user(&fibsize, &user_srb->count,sizeof(u32))){
dprintk((KERN_DEBUG"aacraid: Could not copy data size from user\n"));
rcode = -EFAULT;
goto cleanup;
}
if ((fibsize < (sizeof(struct user_aac_srb) - sizeof(struct user_sgentry))) ||
(fibsize > (dev->max_fib_size - sizeof(struct aac_fibhdr)))) {
rcode = -EINVAL;
goto cleanup;
}
user_srbcmd = kmalloc(fibsize, GFP_KERNEL);
if (!user_srbcmd) {
dprintk((KERN_DEBUG"aacraid: Could not make a copy of the srb\n"));
rcode = -ENOMEM;
goto cleanup;
}
if(copy_from_user(user_srbcmd, user_srb,fibsize)){
dprintk((KERN_DEBUG"aacraid: Could not copy srb from user\n"));
rcode = -EFAULT;
goto cleanup;
}
user_reply = arg+fibsize;
flags = user_srbcmd->flags; /* from user in cpu order */
// Fix up srb for endian and force some values
srbcmd->function = cpu_to_le32(SRBF_ExecuteScsi); // Force this
srbcmd->channel = cpu_to_le32(user_srbcmd->channel);
srbcmd->id = cpu_to_le32(user_srbcmd->id);
srbcmd->lun = cpu_to_le32(user_srbcmd->lun);
srbcmd->timeout = cpu_to_le32(user_srbcmd->timeout);
srbcmd->flags = cpu_to_le32(flags);
srbcmd->retry_limit = 0; // Obsolete parameter
srbcmd->cdb_size = cpu_to_le32(user_srbcmd->cdb_size);
memcpy(srbcmd->cdb, user_srbcmd->cdb, sizeof(srbcmd->cdb));
switch (flags & (SRB_DataIn | SRB_DataOut)) {
case SRB_DataOut:
data_dir = DMA_TO_DEVICE;
break;
case (SRB_DataIn | SRB_DataOut):
data_dir = DMA_BIDIRECTIONAL;
break;
case SRB_DataIn:
data_dir = DMA_FROM_DEVICE;
break;
default:
data_dir = DMA_NONE;
}
if (user_srbcmd->sg.count > ARRAY_SIZE(sg_list)) {
dprintk((KERN_DEBUG"aacraid: too many sg entries %d\n",
le32_to_cpu(srbcmd->sg.count)));
rcode = -EINVAL;
goto cleanup;
}
actual_fibsize = sizeof(struct aac_srb) - sizeof(struct sgentry) +
((user_srbcmd->sg.count & 0xff) * sizeof(struct sgentry));
actual_fibsize64 = actual_fibsize + (user_srbcmd->sg.count & 0xff) *
(sizeof(struct sgentry64) - sizeof(struct sgentry));
/* User made a mistake - should not continue */
if ((actual_fibsize != fibsize) && (actual_fibsize64 != fibsize)) {
dprintk((KERN_DEBUG"aacraid: Bad Size specified in "
"Raw SRB command calculated fibsize=%lu;%lu "
"user_srbcmd->sg.count=%d aac_srb=%lu sgentry=%lu;%lu "
"issued fibsize=%d\n",
actual_fibsize, actual_fibsize64, user_srbcmd->sg.count,
sizeof(struct aac_srb), sizeof(struct sgentry),
sizeof(struct sgentry64), fibsize));
rcode = -EINVAL;
goto cleanup;
}
if ((data_dir == DMA_NONE) && user_srbcmd->sg.count) {
dprintk((KERN_DEBUG"aacraid: SG with no direction specified in Raw SRB command\n"));
rcode = -EINVAL;
goto cleanup;
}
byte_count = 0;
if (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) {
struct user_sgmap64* upsg = (struct user_sgmap64*)&user_srbcmd->sg;
struct sgmap64* psg = (struct sgmap64*)&srbcmd->sg;
/*
* This should also catch if user used the 32 bit sgmap
*/
if (actual_fibsize64 == fibsize) {
actual_fibsize = actual_fibsize64;
for (i = 0; i < upsg->count; i++) {
u64 addr;
void* p;
if (upsg->sg[i].count >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
/* Does this really need to be GFP_DMA? */
p = kmalloc(upsg->sg[i].count,GFP_KERNEL|__GFP_DMA);
if(!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
upsg->sg[i].count,i,upsg->count));
rcode = -ENOMEM;
goto cleanup;
}
addr = (u64)upsg->sg[i].addr[0];
addr += ((u64)upsg->sg[i].addr[1]) << 32;
sg_user[i] = (void __user *)(uintptr_t)addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir);
psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff);
psg->sg[i].addr[1] = cpu_to_le32(addr>>32);
byte_count += upsg->sg[i].count;
psg->sg[i].count = cpu_to_le32(upsg->sg[i].count);
}
} else {
struct user_sgmap* usg;
usg = kmemdup(upsg,
actual_fibsize - sizeof(struct aac_srb)
+ sizeof(struct sgmap), GFP_KERNEL);
if (!usg) {
dprintk((KERN_DEBUG"aacraid: Allocation error in Raw SRB command\n"));
rcode = -ENOMEM;
goto cleanup;
}
actual_fibsize = actual_fibsize64;
for (i = 0; i < usg->count; i++) {
u64 addr;
void* p;
if (usg->sg[i].count >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
kfree(usg);
rcode = -EINVAL;
goto cleanup;
}
/* Does this really need to be GFP_DMA? */
p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA);
if(!p) {
dprintk((KERN_DEBUG "aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
usg->sg[i].count,i,usg->count));
kfree(usg);
rcode = -ENOMEM;
goto cleanup;
}
sg_user[i] = (void __user *)(uintptr_t)usg->sg[i].addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){
kfree (usg);
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir);
psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff);
psg->sg[i].addr[1] = cpu_to_le32(addr>>32);
byte_count += usg->sg[i].count;
psg->sg[i].count = cpu_to_le32(usg->sg[i].count);
}
kfree (usg);
}
srbcmd->count = cpu_to_le32(byte_count);
if (user_srbcmd->sg.count)
psg->count = cpu_to_le32(sg_indx+1);
else
psg->count = 0;
status = aac_fib_send(ScsiPortCommand64, srbfib, actual_fibsize, FsaNormal, 1, 1,NULL,NULL);
} else {
struct user_sgmap* upsg = &user_srbcmd->sg;
struct sgmap* psg = &srbcmd->sg;
if (actual_fibsize64 == fibsize) {
struct user_sgmap64* usg = (struct user_sgmap64 *)upsg;
for (i = 0; i < upsg->count; i++) {
uintptr_t addr;
void* p;
if (usg->sg[i].count >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
/* Does this really need to be GFP_DMA? */
p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA);
if(!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
usg->sg[i].count,i,usg->count));
rcode = -ENOMEM;
goto cleanup;
}
addr = (u64)usg->sg[i].addr[0];
addr += ((u64)usg->sg[i].addr[1]) << 32;
sg_user[i] = (void __user *)addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if(copy_from_user(p,sg_user[i],usg->sg[i].count)){
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir);
psg->sg[i].addr = cpu_to_le32(addr & 0xffffffff);
byte_count += usg->sg[i].count;
psg->sg[i].count = cpu_to_le32(usg->sg[i].count);
}
} else {
for (i = 0; i < upsg->count; i++) {
dma_addr_t addr;
void* p;
if (upsg->sg[i].count >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
p = kmalloc(upsg->sg[i].count, GFP_KERNEL);
if (!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
upsg->sg[i].count, i, upsg->count));
rcode = -ENOMEM;
goto cleanup;
}
sg_user[i] = (void __user *)(uintptr_t)upsg->sg[i].addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if(copy_from_user(p, sg_user[i],
upsg->sg[i].count)) {
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p,
upsg->sg[i].count, data_dir);
psg->sg[i].addr = cpu_to_le32(addr);
byte_count += upsg->sg[i].count;
psg->sg[i].count = cpu_to_le32(upsg->sg[i].count);
}
}
srbcmd->count = cpu_to_le32(byte_count);
if (user_srbcmd->sg.count)
psg->count = cpu_to_le32(sg_indx+1);
else
psg->count = 0;
status = aac_fib_send(ScsiPortCommand, srbfib, actual_fibsize, FsaNormal, 1, 1, NULL, NULL);
}
if (status == -ERESTARTSYS) {
rcode = -ERESTARTSYS;
goto cleanup;
}
if (status != 0){
dprintk((KERN_DEBUG"aacraid: Could not send raw srb fib to hba\n"));
rcode = -ENXIO;
goto cleanup;
}
if (flags & SRB_DataIn) {
for(i = 0 ; i <= sg_indx; i++){
byte_count = le32_to_cpu(
(dev->adapter_info.options & AAC_OPT_SGMAP_HOST64)
? ((struct sgmap64*)&srbcmd->sg)->sg[i].count
: srbcmd->sg.sg[i].count);
if(copy_to_user(sg_user[i], sg_list[i], byte_count)){
dprintk((KERN_DEBUG"aacraid: Could not copy sg data to user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
}
reply = (struct aac_srb_reply *) fib_data(srbfib);
if(copy_to_user(user_reply,reply,sizeof(struct aac_srb_reply))){
dprintk((KERN_DEBUG"aacraid: Could not copy reply to user\n"));
rcode = -EFAULT;
goto cleanup;
}
cleanup:
kfree(user_srbcmd);
for(i=0; i <= sg_indx; i++){
kfree(sg_list[i]);
}
if (rcode != -ERESTARTSYS) {
aac_fib_complete(srbfib);
aac_fib_free(srbfib);
}
return rcode;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,146 |
openssl | 4b390b6c3f8df925dc92a3dd6b022baa9a2f4650 | MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
{
int al;
long remain;
remain = PACKET_remaining(pkt);
/*
* 'Change Cipher Spec' is just a single byte, which should already have
* been consumed by ssl_get_message() so there should be no bytes left,
* unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
*/
if (SSL_IS_DTLS(s)) {
if ((s->version == DTLS1_BAD_VER
&& remain != DTLS1_CCS_HEADER_LENGTH + 1)
|| (s->version != DTLS1_BAD_VER
&& remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
SSL_R_BAD_CHANGE_CIPHER_SPEC);
goto f_err;
}
} else {
if (remain != 0) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
SSL_R_BAD_CHANGE_CIPHER_SPEC);
goto f_err;
}
}
/* Check we have a cipher to change to */
if (s->s3->tmp.new_cipher == NULL) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
goto f_err;
}
s->s3->change_cipher_spec = 1;
if (!ssl3_do_change_cipher_spec(s)) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
goto f_err;
}
if (SSL_IS_DTLS(s)) {
dtls1_reset_seq_numbers(s, SSL3_CC_READ);
if (s->version == DTLS1_BAD_VER)
s->d1->handshake_read_seq++;
#ifndef OPENSSL_NO_SCTP
/*
* Remember that a CCS has been received, so that an old key of
* SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
* SCTP is used
*/
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
#endif
}
return MSG_PROCESS_CONTINUE_READING;
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
ossl_statem_set_error(s);
return MSG_PROCESS_ERROR;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,020 |
linux | 86acdca1b63e6890540fa19495cfc708beff3d8b | static void *proc_pid_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct inode *inode = dentry->d_inode;
int error = -EACCES;
/* We don't need a base pointer in the /proc filesystem */
path_put(&nd->path);
/* Are we allowed to snoop on the tasks file descriptors? */
if (!proc_fd_access_allowed(inode))
goto out;
error = PROC_I(inode)->op.proc_get_link(inode, &nd->path);
nd->last_type = LAST_BIND;
out:
return ERR_PTR(error);
}
| 1 | CVE-2014-0203 | 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,332 |
libgit2 | c1577110467b701dcbcf9439ac225ea851b47d22 | int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0;
#define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; }
if (cmd & 0x01) ADD_DELTA(off, 0UL);
if (cmd & 0x02) ADD_DELTA(off, 8UL);
if (cmd & 0x04) ADD_DELTA(off, 16UL);
if (cmd & 0x08) ADD_DELTA(off, 24UL);
if (cmd & 0x10) ADD_DELTA(len, 0UL);
if (cmd & 0x20) ADD_DELTA(len, 8UL);
if (cmd & 0x40) ADD_DELTA(len, 16UL);
if (!len) len = 0x10000;
#undef ADD_DELTA
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
| 1 | CVE-2018-10887 | 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. | 87 |
linux | 64f3b9e203bd06855072e295557dca1485a2ecba | static inline u8 ip4_frag_ecn(u8 tos)
{
tos = (tos & INET_ECN_MASK) + 1;
/*
* After the last operation we have (in binary):
* INET_ECN_NOT_ECT => 001
* INET_ECN_ECT_1 => 010
* INET_ECN_ECT_0 => 011
* INET_ECN_CE => 100
*/
return (tos & 2) ? 0 : tos;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,739 |
libfep | 293d9d3f | fep_client_open (const char *address)
{
FepClient *client;
struct sockaddr_un sun;
ssize_t sun_len;
int retval;
if (!address)
address = getenv ("LIBFEP_CONTROL_SOCK");
if (!address)
return NULL;
if (strlen (address) + 1 >= sizeof(sun.sun_path))
{
fep_log (FEP_LOG_LEVEL_WARNING,
"unix domain socket path too long: %d + 1 >= %d",
strlen (address),
sizeof (sun.sun_path));
free (address);
return NULL;
}
client = xzalloc (sizeof(FepClient));
client->filter_running = false;
client->messages = NULL;
memset (&sun, 0, sizeof(struct sockaddr_un));
sun.sun_family = AF_UNIX;
#ifdef __linux__
sun.sun_path[0] = '\0';
memcpy (sun.sun_path + 1, address, strlen (address));
sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (address) + 1;
#else
memcpy (sun.sun_path, address, strlen (address));
sun_len = sizeof (struct sockaddr_un);
#endif
client->control = socket (AF_UNIX, SOCK_STREAM, 0);
if (client->control < 0)
{
free (client);
return NULL;
}
retval = connect (client->control,
(const struct sockaddr *) &sun,
sun_len);
if (retval < 0)
{
close (client->control);
free (client);
return NULL;
}
return client;
}
| 1 | CVE-2014-3980 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 4,330 |
core | 2c3f37672277b1f73f84722802aaa0ab1ab3e413 | auth_request_get_var_expand_table_full(const struct auth_request *auth_request,
auth_request_escape_func_t *escape_func,
unsigned int *count)
{
const unsigned int auth_count =
N_ELEMENTS(auth_request_var_expand_static_tab);
struct var_expand_table *tab, *ret_tab;
const char *orig_user, *auth_user;
if (escape_func == NULL)
escape_func = escape_none;
/* keep the extra fields at the beginning. the last static_tab field
contains the ending NULL-fields. */
tab = ret_tab = t_malloc((*count + auth_count) * sizeof(*tab));
memset(tab, 0, *count * sizeof(*tab));
tab += *count;
*count += auth_count;
memcpy(tab, auth_request_var_expand_static_tab,
auth_count * sizeof(*tab));
tab[0].value = escape_func(auth_request->user, auth_request);
tab[1].value = escape_func(t_strcut(auth_request->user, '@'),
auth_request);
tab[2].value = strchr(auth_request->user, '@');
if (tab[2].value != NULL)
tab[2].value = escape_func(tab[2].value+1, auth_request);
tab[3].value = escape_func(auth_request->service, auth_request);
/* tab[4] = we have no home dir */
if (auth_request->local_ip.family != 0)
tab[5].value = net_ip2addr(&auth_request->local_ip);
if (auth_request->remote_ip.family != 0)
tab[6].value = net_ip2addr(&auth_request->remote_ip);
tab[7].value = dec2str(auth_request->client_pid);
if (auth_request->mech_password != NULL) {
tab[8].value = escape_func(auth_request->mech_password,
auth_request);
}
if (auth_request->userdb_lookup) {
tab[9].value = auth_request->userdb == NULL ? "" :
dec2str(auth_request->userdb->userdb->id);
} else {
tab[9].value = auth_request->passdb == NULL ? "" :
dec2str(auth_request->passdb->passdb->id);
}
tab[10].value = auth_request->mech_name == NULL ? "" :
escape_func(auth_request->mech_name, auth_request);
tab[11].value = auth_request->secured ? "secured" : "";
tab[12].value = dec2str(auth_request->local_port);
tab[13].value = dec2str(auth_request->remote_port);
tab[14].value = auth_request->valid_client_cert ? "valid" : "";
if (auth_request->requested_login_user != NULL) {
const char *login_user = auth_request->requested_login_user;
tab[15].value = escape_func(login_user, auth_request);
tab[16].value = escape_func(t_strcut(login_user, '@'),
auth_request);
tab[17].value = strchr(login_user, '@');
if (tab[17].value != NULL) {
tab[17].value = escape_func(tab[17].value+1,
auth_request);
}
}
tab[18].value = auth_request->session_id == NULL ? NULL :
escape_func(auth_request->session_id, auth_request);
if (auth_request->real_local_ip.family != 0)
tab[19].value = net_ip2addr(&auth_request->real_local_ip);
if (auth_request->real_remote_ip.family != 0)
tab[20].value = net_ip2addr(&auth_request->real_remote_ip);
tab[21].value = dec2str(auth_request->real_local_port);
tab[22].value = dec2str(auth_request->real_remote_port);
tab[23].value = strchr(auth_request->user, '@');
if (tab[23].value != NULL) {
tab[23].value = escape_func(t_strcut(tab[23].value+1, '@'),
auth_request);
}
tab[24].value = strrchr(auth_request->user, '@');
if (tab[24].value != NULL)
tab[24].value = escape_func(tab[24].value+1, auth_request);
tab[25].value = auth_request->master_user == NULL ? NULL :
escape_func(auth_request->master_user, auth_request);
tab[26].value = auth_request->session_pid == (pid_t)-1 ? NULL :
dec2str(auth_request->session_pid);
orig_user = auth_request->original_username != NULL ?
auth_request->original_username : auth_request->user;
tab[27].value = escape_func(orig_user, auth_request);
tab[28].value = escape_func(t_strcut(orig_user, '@'), auth_request);
tab[29].value = strchr(orig_user, '@');
if (tab[29].value != NULL)
tab[29].value = escape_func(tab[29].value+1, auth_request);
if (auth_request->master_user != NULL)
auth_user = auth_request->master_user;
else
auth_user = orig_user;
tab[30].value = escape_func(auth_user, auth_request);
tab[31].value = escape_func(t_strcut(auth_user, '@'), auth_request);
tab[32].value = strchr(auth_user, '@');
if (tab[32].value != NULL)
tab[32].value = escape_func(tab[32].value+1, auth_request);
if (auth_request->local_name != NULL)
tab[33].value = escape_func(auth_request->local_name, auth_request);
else
tab[33].value = "";
return ret_tab;
} | 1 | CVE-2016-8652 | 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. | 5,178 |
sqlite | 8654186b0236d556aa85528c2573ee0b6ab71be3 | void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,313 |
Chrome | 116d0963cadfbf55ef2ec3d13781987c4d80517a | void PrintMsg_Print_Params::Reset() {
page_size = gfx::Size();
content_size = gfx::Size();
printable_area = gfx::Rect();
margin_top = 0;
margin_left = 0;
dpi = 0;
min_shrink = 0;
max_shrink = 0;
desired_dpi = 0;
document_cookie = 0;
selection_only = false;
supports_alpha_blend = false;
preview_ui_addr = std::string();
preview_request_id = 0;
is_first_request = false;
print_scaling_option = WebKit::WebPrintScalingOptionSourceSize;
print_to_pdf = false;
display_header_footer = false;
date = string16();
title = string16();
url = string16();
}
| 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. | 6,575 |
linux | 8275cdd0e7ac550dcce2b3ef6d2fb3b808c1ae59 | xfs_attr_shortform_addname(xfs_da_args_t *args)
{
int newsize, forkoff, retval;
trace_xfs_attr_sf_addname(args);
retval = xfs_attr_shortform_lookup(args);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
return(retval);
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE)
return(retval);
retval = xfs_attr_shortform_remove(args);
ASSERT(retval == 0);
}
if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX ||
args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return(XFS_ERROR(ENOSPC));
newsize = XFS_ATTR_SF_TOTSIZE(args->dp);
newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize);
if (!forkoff)
return(XFS_ERROR(ENOSPC));
xfs_attr_shortform_add(args, forkoff);
return(0);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,682 |
OpenSC | c3f23b836e5a1766c36617fe1da30d22f7b63de2 | static u8 acl_to_byte(const sc_acl_entry_t *e)
{
switch (e->method) {
case SC_AC_NONE:
return 0x00;
case SC_AC_CHV:
switch (e->key_ref) {
case 1:
return 0x01;
break;
case 2:
return 0x02;
break;
default:
return 0x00;
}
break;
case SC_AC_TERM:
return 0x04;
case SC_AC_NEVER:
return 0x0F;
}
return 0x00;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,787 |
qemu | 065e6298a75164b4347682b63381dbe752c2b156 | int qemu_fdt_nop_node(void *fdt, const char *node_path)
{
int r;
r = fdt_nop_node(fdt, findnode_nofail(fdt, node_path));
if (r < 0) {
error_report("%s: Couldn't nop node %s: %s", __func__, node_path,
fdt_strerror(r));
exit(1);
}
return r;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,703 |
Chrome | 805eabb91d386c86bd64336c7643f6dfa864151d | void DidCreateTemporary(File::Error error,
const FilePath& path) {
error_ = error;
path_ = path;
MessageLoop::current()->QuitWhenIdle();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,854 |
FFmpeg | e43a0a232dbf6d3c161823c2e07c52e76227a1bc | static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
DelogoContext *s = inlink->dst->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
AVFrame *out;
int hsub0 = desc->log2_chroma_w;
int vsub0 = desc->log2_chroma_h;
int direct = 0;
int plane;
AVRational sar;
if (av_frame_is_writable(in)) {
direct = 1;
out = in;
} else {
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
}
sar = in->sample_aspect_ratio;
/* Assume square pixels if SAR is unknown */
if (!sar.num)
sar.num = sar.den = 1;
for (plane = 0; plane < 4 && in->data[plane]; plane++) {
int hsub = plane == 1 || plane == 2 ? hsub0 : 0;
int vsub = plane == 1 || plane == 2 ? vsub0 : 0;
apply_delogo(out->data[plane], out->linesize[plane],
in ->data[plane], in ->linesize[plane],
FF_CEIL_RSHIFT(inlink->w, hsub),
FF_CEIL_RSHIFT(inlink->h, vsub),
sar, s->x>>hsub, s->y>>vsub,
/* Up and left borders were rounded down, inject lost bits
* into width and height to avoid error accumulation */
FF_CEIL_RSHIFT(s->w + (s->x & ((1<<hsub)-1)), hsub),
FF_CEIL_RSHIFT(s->h + (s->y & ((1<<vsub)-1)), vsub),
s->band>>FFMIN(hsub, vsub),
s->show, direct);
}
if (!direct)
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
| 1 | CVE-2013-4263 | 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). | 3,469 |
ImageMagick | f595a1985233c399a05c0c37cc41de16a90dd025 | MagickExport MagickBooleanType AnnotateImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
char
*p,
primitive[MagickPathExtent],
*text,
**textlist;
DrawInfo
*annotate,
*annotate_info;
GeometryInfo
geometry_info;
MagickBooleanType
status;
PointInfo
offset;
RectangleInfo
geometry;
register ssize_t
i;
TypeMetric
metrics;
size_t
height,
number_lines;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->text == (char *) NULL)
return(MagickFalse);
if (*draw_info->text == '\0')
return(MagickTrue);
annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
text=annotate->text;
annotate->text=(char *) NULL;
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
number_lines=1;
for (p=text; *p != '\0'; p++)
if (*p == '\n')
number_lines++;
textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist));
if (textlist == (char **) NULL)
return(MagickFalse);
p=text;
for (i=0; i < number_lines; i++)
{
char
*q;
textlist[i]=p;
for (q=p; *q != '\0'; q++)
if ((*q == '\r') || (*q == '\n'))
break;
if (*q == '\r')
{
*q='\0';
q++;
}
*q='\0';
p=q+1;
}
textlist[i]=(char *) NULL;
SetGeometry(image,&geometry);
SetGeometryInfo(&geometry_info);
if (annotate_info->geometry != (char *) NULL)
{
(void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
exception);
(void) ParseGeometry(annotate_info->geometry,&geometry_info);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics,exception);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+
annotate_info->affine.ry*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-
annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-
annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.alpha != TransparentAlpha)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MagickPathExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info,exception);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics,exception);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
}
| 1 | CVE-2019-13301 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 9,463 |
Chrome | 6a310d99a741f9ba5e4e537c5ec49d3adbe5876f | void AXTree::UpdateData(const AXTreeData& new_data) {
if (data_ == new_data)
return;
AXTreeData old_data = data_;
data_ = new_data;
for (AXTreeObserver& observer : observers_)
observer.OnTreeDataChanged(this, old_data, new_data);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,091 |
libarchive | ba641f73f3d758d9032b3f0e5597a9c6e593a505 | process_extra(struct archive_read *a, const char *p, size_t extra_length, struct zip_entry* zip_entry)
{
unsigned offset = 0;
if (extra_length == 0) {
return ARCHIVE_OK;
}
if (extra_length < 4) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Too-small extra data: Need at least 4 bytes, but only found %d bytes", (int)extra_length);
return ARCHIVE_FAILED;
}
while (offset <= extra_length - 4) {
unsigned short headerid = archive_le16dec(p + offset);
unsigned short datasize = archive_le16dec(p + offset + 2);
offset += 4;
if (offset + datasize > extra_length) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Extra data overflow: Need %d bytes but only found %d bytes",
(int)datasize, (int)(extra_length - offset));
return ARCHIVE_FAILED;
}
#ifdef DEBUG
fprintf(stderr, "Header id 0x%04x, length %d\n",
headerid, datasize);
#endif
switch (headerid) {
case 0x0001:
/* Zip64 extended information extra field. */
zip_entry->flags |= LA_USED_ZIP64;
if (zip_entry->uncompressed_size == 0xffffffff) {
uint64_t t = 0;
if (datasize < 8
|| (t = archive_le64dec(p + offset)) > INT64_MAX) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Malformed 64-bit uncompressed size");
return ARCHIVE_FAILED;
}
zip_entry->uncompressed_size = t;
offset += 8;
datasize -= 8;
}
if (zip_entry->compressed_size == 0xffffffff) {
uint64_t t = 0;
if (datasize < 8
|| (t = archive_le64dec(p + offset)) > INT64_MAX) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Malformed 64-bit compressed size");
return ARCHIVE_FAILED;
}
zip_entry->compressed_size = t;
offset += 8;
datasize -= 8;
}
if (zip_entry->local_header_offset == 0xffffffff) {
uint64_t t = 0;
if (datasize < 8
|| (t = archive_le64dec(p + offset)) > INT64_MAX) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Malformed 64-bit local header offset");
return ARCHIVE_FAILED;
}
zip_entry->local_header_offset = t;
offset += 8;
datasize -= 8;
}
/* archive_le32dec(p + offset) gives disk
* on which file starts, but we don't handle
* multi-volume Zip files. */
break;
#ifdef DEBUG
case 0x0017:
{
/* Strong encryption field. */
if (archive_le16dec(p + offset) == 2) {
unsigned algId =
archive_le16dec(p + offset + 2);
unsigned bitLen =
archive_le16dec(p + offset + 4);
int flags =
archive_le16dec(p + offset + 6);
fprintf(stderr, "algId=0x%04x, bitLen=%u, "
"flgas=%d\n", algId, bitLen,flags);
}
break;
}
#endif
case 0x5455:
{
/* Extended time field "UT". */
int flags;
if (datasize == 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Incomplete extended time field");
return ARCHIVE_FAILED;
}
flags = p[offset];
offset++;
datasize--;
/* Flag bits indicate which dates are present. */
if (flags & 0x01)
{
#ifdef DEBUG
fprintf(stderr, "mtime: %lld -> %d\n",
(long long)zip_entry->mtime,
archive_le32dec(p + offset));
#endif
if (datasize < 4)
break;
zip_entry->mtime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
if (flags & 0x02)
{
if (datasize < 4)
break;
zip_entry->atime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
if (flags & 0x04)
{
if (datasize < 4)
break;
zip_entry->ctime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
break;
}
case 0x5855:
{
/* Info-ZIP Unix Extra Field (old version) "UX". */
if (datasize >= 8) {
zip_entry->atime = archive_le32dec(p + offset);
zip_entry->mtime =
archive_le32dec(p + offset + 4);
}
if (datasize >= 12) {
zip_entry->uid =
archive_le16dec(p + offset + 8);
zip_entry->gid =
archive_le16dec(p + offset + 10);
}
break;
}
case 0x6c78:
{
/* Experimental 'xl' field */
/*
* Introduced Dec 2013 to provide a way to
* include external file attributes (and other
* fields that ordinarily appear only in
* central directory) in local file header.
* This provides file type and permission
* information necessary to support full
* streaming extraction. Currently being
* discussed with other Zip developers
* ... subject to change.
*
* Format:
* The field starts with a bitmap that specifies
* which additional fields are included. The
* bitmap is variable length and can be extended in
* the future.
*
* n bytes - feature bitmap: first byte has low-order
* 7 bits. If high-order bit is set, a subsequent
* byte holds the next 7 bits, etc.
*
* if bitmap & 1, 2 byte "version made by"
* if bitmap & 2, 2 byte "internal file attributes"
* if bitmap & 4, 4 byte "external file attributes"
* if bitmap & 8, 2 byte comment length + n byte comment
*/
int bitmap, bitmap_last;
if (datasize < 1)
break;
bitmap_last = bitmap = 0xff & p[offset];
offset += 1;
datasize -= 1;
/* We only support first 7 bits of bitmap; skip rest. */
while ((bitmap_last & 0x80) != 0
&& datasize >= 1) {
bitmap_last = p[offset];
offset += 1;
datasize -= 1;
}
if (bitmap & 1) {
/* 2 byte "version made by" */
if (datasize < 2)
break;
zip_entry->system
= archive_le16dec(p + offset) >> 8;
offset += 2;
datasize -= 2;
}
if (bitmap & 2) {
/* 2 byte "internal file attributes" */
uint32_t internal_attributes;
if (datasize < 2)
break;
internal_attributes
= archive_le16dec(p + offset);
/* Not used by libarchive at present. */
(void)internal_attributes; /* UNUSED */
offset += 2;
datasize -= 2;
}
if (bitmap & 4) {
/* 4 byte "external file attributes" */
uint32_t external_attributes;
if (datasize < 4)
break;
external_attributes
= archive_le32dec(p + offset);
if (zip_entry->system == 3) {
zip_entry->mode
= external_attributes >> 16;
} else if (zip_entry->system == 0) {
if (0x10 == (external_attributes & 0x10)) {
zip_entry->mode = AE_IFDIR | 0775;
} else {
zip_entry->mode = AE_IFREG | 0664;
}
if (0x01 == (external_attributes & 0x01)) {
zip_entry->mode &= 0555;
}
} else {
zip_entry->mode = 0;
}
offset += 4;
datasize -= 4;
}
if (bitmap & 8) {
/* 2 byte comment length + comment */
uint32_t comment_length;
if (datasize < 2)
break;
comment_length
= archive_le16dec(p + offset);
offset += 2;
datasize -= 2;
if (datasize < comment_length)
break;
/* Comment is not supported by libarchive */
offset += comment_length;
datasize -= comment_length;
}
break;
}
case 0x7855:
/* Info-ZIP Unix Extra Field (type 2) "Ux". */
#ifdef DEBUG
fprintf(stderr, "uid %d gid %d\n",
archive_le16dec(p + offset),
archive_le16dec(p + offset + 2));
#endif
if (datasize >= 2)
zip_entry->uid = archive_le16dec(p + offset);
if (datasize >= 4)
zip_entry->gid =
archive_le16dec(p + offset + 2);
break;
case 0x7875:
{
/* Info-Zip Unix Extra Field (type 3) "ux". */
int uidsize = 0, gidsize = 0;
/* TODO: support arbitrary uidsize/gidsize. */
if (datasize >= 1 && p[offset] == 1) {/* version=1 */
if (datasize >= 4) {
/* get a uid size. */
uidsize = 0xff & (int)p[offset+1];
if (uidsize == 2)
zip_entry->uid =
archive_le16dec(
p + offset + 2);
else if (uidsize == 4 && datasize >= 6)
zip_entry->uid =
archive_le32dec(
p + offset + 2);
}
if (datasize >= (2 + uidsize + 3)) {
/* get a gid size. */
gidsize = 0xff & (int)p[offset+2+uidsize];
if (gidsize == 2)
zip_entry->gid =
archive_le16dec(
p+offset+2+uidsize+1);
else if (gidsize == 4 &&
datasize >= (2 + uidsize + 5))
zip_entry->gid =
archive_le32dec(
p+offset+2+uidsize+1);
}
}
break;
}
case 0x9901:
/* WinZip AES extra data field. */
if (datasize < 6) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Incomplete AES field");
return ARCHIVE_FAILED;
}
if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
/* Vendor version. */
zip_entry->aes_extra.vendor =
archive_le16dec(p + offset);
/* AES encryption strength. */
zip_entry->aes_extra.strength = p[offset + 4];
/* Actual compression method. */
zip_entry->aes_extra.compression =
p[offset + 5];
}
break;
default:
break;
}
offset += datasize;
}
if (offset != extra_length) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Malformed extra data: Consumed %d bytes of %d bytes",
(int)offset, (int)extra_length);
return ARCHIVE_FAILED;
}
return ARCHIVE_OK;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,812 |
pam-u2f | aab0c31a3bfed8912a271685d6ec909f61380155 | int get_devices_from_authfile(const char *authfile, const char *username,
unsigned max_devs, int verbose, FILE *debug_file,
device_t *devices, unsigned *n_devs) {
char *buf = NULL;
char *s_user, *s_token;
int retval = 0;
int fd = -1;
struct stat st;
struct passwd *pw = NULL, pw_s;
char buffer[BUFSIZE];
int gpu_ret;
FILE *opwfile = NULL;
unsigned i, j;
/* Ensure we never return uninitialized count. */
*n_devs = 0;
fd = open(authfile, O_RDONLY | O_CLOEXEC | O_NOCTTY);
if (fd < 0) {
if (verbose)
D(debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (fstat(fd, &st) < 0) {
if (verbose)
D(debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (!S_ISREG(st.st_mode)) {
if (verbose)
D(debug_file, "%s is not a regular file", authfile);
goto err;
}
if (st.st_size == 0) {
if (verbose)
D(debug_file, "File %s is empty", authfile);
goto err;
}
gpu_ret = getpwuid_r(st.st_uid, &pw_s, buffer, sizeof(buffer), &pw);
if (gpu_ret != 0 || pw == NULL) {
D(debug_file, "Unable to retrieve credentials for uid %u, (%s)", st.st_uid,
strerror(errno));
goto err;
}
if (strcmp(pw->pw_name, username) != 0 && strcmp(pw->pw_name, "root") != 0) {
if (strcmp(username, "root") != 0) {
D(debug_file, "The owner of the authentication file is neither %s nor root",
username);
} else {
D(debug_file, "The owner of the authentication file is not root");
}
goto err;
}
opwfile = fdopen(fd, "r");
if (opwfile == NULL) {
if (verbose)
D(debug_file, "fdopen: %s", strerror(errno));
goto err;
} else {
fd = -1; /* fd belongs to opwfile */
}
buf = malloc(sizeof(char) * (DEVSIZE * max_devs));
if (!buf) {
if (verbose)
D(debug_file, "Unable to allocate memory");
goto err;
}
retval = -2;
while (fgets(buf, (int)(DEVSIZE * (max_devs - 1)), opwfile)) {
char *saveptr = NULL;
size_t len = strlen(buf);
if (len > 0 && buf[len - 1] == '\n')
buf[len - 1] = '\0';
if (verbose)
D(debug_file, "Authorization line: %s", buf);
s_user = strtok_r(buf, ":", &saveptr);
if (s_user && strcmp(username, s_user) == 0) {
if (verbose)
D(debug_file, "Matched user: %s", s_user);
retval = -1; // We found at least one line for the user
// only keep last line for this user
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
i = 0;
while ((s_token = strtok_r(NULL, ",", &saveptr))) {
if ((*n_devs)++ > max_devs - 1) {
*n_devs = max_devs;
if (verbose)
D(debug_file, "Found more than %d devices, ignoring the remaining ones",
max_devs);
break;
}
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
if (verbose)
D(debug_file, "KeyHandle for device number %d: %s", i + 1, s_token);
devices[i].keyHandle = strdup(s_token);
if (!devices[i].keyHandle) {
if (verbose)
D(debug_file, "Unable to allocate memory for keyHandle number %d", i);
goto err;
}
s_token = strtok_r(NULL, ":", &saveptr);
if (!s_token) {
if (verbose)
D(debug_file, "Unable to retrieve publicKey number %d", i + 1);
goto err;
}
if (verbose)
D(debug_file, "publicKey for device number %d: %s", i + 1, s_token);
if (strlen(s_token) % 2 != 0) {
if (verbose)
D(debug_file, "Length of key number %d not even", i + 1);
goto err;
}
devices[i].key_len = strlen(s_token) / 2;
if (verbose)
D(debug_file, "Length of key number %d is %zu", i + 1, devices[i].key_len);
devices[i].publicKey =
malloc((sizeof(unsigned char) * devices[i].key_len));
if (!devices[i].publicKey) {
if (verbose)
D(debug_file, "Unable to allocate memory for publicKey number %d", i);
goto err;
}
for (j = 0; j < devices[i].key_len; j++) {
unsigned int x;
if (sscanf(&s_token[2 * j], "%2x", &x) != 1) {
if (verbose)
D(debug_file, "Invalid hex number in key");
goto err;
}
devices[i].publicKey[j] = (unsigned char)x;
}
i++;
}
}
}
if (verbose)
D(debug_file, "Found %d device(s) for user %s", *n_devs, username);
retval = 1;
goto out;
err:
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
out:
if (buf) {
free(buf);
buf = NULL;
}
if (opwfile)
fclose(opwfile);
if (fd != -1)
close(fd);
return retval;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,163 |
tensorflow | 15691e456c7dc9bd6be203b09765b063bf4a380c | inline void BinaryBroadcastFiveFold(const ArithmeticParams& unswitched_params,
const RuntimeShape& unswitched_input1_shape,
const T* unswitched_input1_data,
const RuntimeShape& unswitched_input2_shape,
const T* unswitched_input2_data,
const RuntimeShape& output_shape,
T* output_data, ElementwiseF elementwise_f,
ScalarBroadcastF scalar_broadcast_f) {
ArithmeticParams switched_params = unswitched_params;
switched_params.input1_offset = unswitched_params.input2_offset;
switched_params.input1_multiplier = unswitched_params.input2_multiplier;
switched_params.input1_shift = unswitched_params.input2_shift;
switched_params.input2_offset = unswitched_params.input1_offset;
switched_params.input2_multiplier = unswitched_params.input1_multiplier;
switched_params.input2_shift = unswitched_params.input1_shift;
const bool use_unswitched =
unswitched_params.broadcast_category ==
tflite::BroadcastableOpCategory::kFirstInputBroadcastsFast;
const ArithmeticParams& params =
use_unswitched ? unswitched_params : switched_params;
const T* input1_data =
use_unswitched ? unswitched_input1_data : unswitched_input2_data;
const T* input2_data =
use_unswitched ? unswitched_input2_data : unswitched_input1_data;
// Fivefold nested loops. The second input resets its position for each
// iteration of the second loop. The first input resets its position at the
// beginning of the fourth loop. The innermost loop is an elementwise add of
// sections of the arrays.
T* output_data_ptr = output_data;
const T* input1_data_ptr = input1_data;
const T* input2_data_reset = input2_data;
// In the fivefold pattern, y0, y2 and y4 are not broadcast, and so shared
// between input shapes. y3 for input 1 is always broadcast, and so the
// dimension there is 1, whereas optionally y1 might be broadcast for
// input 2. Put another way, input1.shape.FlatSize = y0 * y1 * y2 * y4,
// input2.shape.FlatSize = y0 * y2 * y3 * y4.
int y0 = params.broadcast_shape[0];
int y1 = params.broadcast_shape[1];
int y2 = params.broadcast_shape[2];
int y3 = params.broadcast_shape[3];
int y4 = params.broadcast_shape[4];
if (y4 > 1) {
// General fivefold pattern, with y4 > 1 so there is a non-broadcast inner
// dimension.
for (int i0 = 0; i0 < y0; ++i0) {
const T* input2_data_ptr = nullptr;
for (int i1 = 0; i1 < y1; ++i1) {
input2_data_ptr = input2_data_reset;
for (int i2 = 0; i2 < y2; ++i2) {
for (int i3 = 0; i3 < y3; ++i3) {
elementwise_f(y4, params, input1_data_ptr, input2_data_ptr,
output_data_ptr);
input2_data_ptr += y4;
output_data_ptr += y4;
}
// We have broadcast y4 of input1 data y3 times, and now move on.
input1_data_ptr += y4;
}
}
// We have broadcast y2*y3*y4 of input2 data y1 times, and now move on.
input2_data_reset = input2_data_ptr;
}
} else if (input1_data_ptr != nullptr) {
// Special case of y4 == 1, in which the innermost loop is a single
// element and can be combined with the next (y3) as an inner broadcast.
//
// Note that this handles the case of pure scalar broadcast when
// y0 == y1 == y2 == 1. With low overhead it handles cases such as scalar
// broadcast with batch (as y2 > 1).
//
// NOTE The process is the same as the above general case except
// simplified for y4 == 1 and the loop over y3 is contained within the
// AddScalarBroadcast function.
for (int i0 = 0; i0 < y0; ++i0) {
const T* input2_data_ptr = nullptr;
for (int i1 = 0; i1 < y1; ++i1) {
input2_data_ptr = input2_data_reset;
for (int i2 = 0; i2 < y2; ++i2) {
scalar_broadcast_f(y3, params, *input1_data_ptr, input2_data_ptr,
output_data_ptr);
input2_data_ptr += y3;
output_data_ptr += y3;
input1_data_ptr += 1;
}
}
input2_data_reset = input2_data_ptr;
}
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,731 |
ppp | 7658e8257183f062dc01f87969c140707c7e52cb | options_from_list(w, priv)
struct wordlist *w;
int priv;
{
char *argv[MAXARGS];
option_t *opt;
int i, n, ret = 0;
struct wordlist *w0;
privileged_option = priv;
option_source = "secrets file";
option_priority = OPRIO_SECFILE;
while (w != NULL) {
opt = find_option(w->word);
if (opt == NULL) {
option_error("In secrets file: unrecognized option '%s'",
w->word);
goto err;
}
n = n_arguments(opt);
w0 = w;
for (i = 0; i < n; ++i) {
w = w->next;
if (w == NULL) {
option_error(
"In secrets file: too few parameters for option '%s'",
w0->word);
goto err;
}
argv[i] = w->word;
}
if (!process_option(opt, w0->word, argv))
goto err;
w = w->next;
}
ret = 1;
err:
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,712 |
qemu | 940973ae0b45c9b6817bab8e4cf4df99a9ef83d7 | void ide_sector_write(IDEState *s)
{
int64_t sector_num;
int n;
s->status = READY_STAT | SEEK_STAT | BUSY_STAT;
sector_num = ide_get_sector(s);
#if defined(DEBUG_IDE)
printf("sector=%" PRId64 "\n", sector_num);
#endif
n = s->nsector;
if (n > s->req_nb_sectors) {
n = s->req_nb_sectors;
}
s->iov.iov_base = s->io_buffer;
s->iov.iov_len = n * BDRV_SECTOR_SIZE;
qemu_iovec_init_external(&s->qiov, &s->iov, 1);
bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
s->pio_aiocb = bdrv_aio_writev(s->bs, sector_num, &s->qiov, n,
ide_sector_write_cb, s);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,714 |
linux | dd504589577d8e8e70f51f997ad487a4cb6c026f | static void skcipher_free_async_sgls(struct skcipher_async_req *sreq)
{
struct skcipher_async_rsgl *rsgl, *tmp;
struct scatterlist *sgl;
struct scatterlist *sg;
int i, n;
list_for_each_entry_safe(rsgl, tmp, &sreq->list, list) {
af_alg_free_sg(&rsgl->sgl);
if (rsgl != &sreq->first_sgl)
kfree(rsgl);
}
sgl = sreq->tsg;
n = sg_nents(sgl);
for_each_sg(sgl, sg, n, i)
put_page(sg_page(sg));
kfree(sreq->tsg);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,254 |
samba | 745b99fc6b75db33cdb0a58df1a3f2a5063bc76e | static int ldb_wildcard_compare(struct ldb_context *ldb,
const struct ldb_parse_tree *tree,
const struct ldb_val value, bool *matched)
{
const struct ldb_schema_attribute *a;
struct ldb_val val;
struct ldb_val cnk;
struct ldb_val *chunk;
uint8_t *save_p = NULL;
unsigned int c = 0;
a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr);
if (!a) {
return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
}
if (tree->u.substring.chunks == NULL) {
*matched = false;
return LDB_SUCCESS;
}
if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) {
return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
}
save_p = val.data;
cnk.data = NULL;
if ( ! tree->u.substring.start_with_wildcard ) {
chunk = tree->u.substring.chunks[c];
if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch;
/* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */
if (cnk.length > val.length) {
goto mismatch;
}
/*
* Empty strings are returned as length 0. Ensure
* we can cope with this.
*/
if (cnk.length == 0) {
goto mismatch;
}
if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch;
val.length -= cnk.length;
val.data += cnk.length;
c++;
talloc_free(cnk.data);
cnk.data = NULL;
}
while (tree->u.substring.chunks[c]) {
uint8_t *p;
chunk = tree->u.substring.chunks[c];
if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch;
/*
* Empty strings are returned as length 0. Ensure
* we can cope with this.
*/
if (cnk.length == 0) {
goto mismatch;
}
/*
* Values might be binary blobs. Don't use string
* search, but memory search instead.
*/
p = memmem((const void *)val.data,val.length,
(const void *)cnk.data, cnk.length);
if (p == NULL) goto mismatch;
if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) {
uint8_t *g;
uint8_t *end = val.data + val.length;
do { /* greedy */
g = memmem(p + cnk.length,
end - (p + cnk.length),
(const uint8_t *)cnk.data,
cnk.length);
if (g) p = g;
} while(g);
}
val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length;
val.data = (uint8_t *)(p + cnk.length);
c++;
talloc_free(cnk.data);
cnk.data = NULL;
}
/* last chunk may not have reached end of string */
if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch;
talloc_free(save_p);
*matched = true;
return LDB_SUCCESS;
mismatch:
*matched = false;
talloc_free(save_p);
talloc_free(cnk.data);
return LDB_SUCCESS;
} | 1 | CVE-2019-3824 | 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. | 1,250 |
Android | 7fa3f552a6f34ed05c15e64ea30b8eed53f77a41 | bool SampleTable::isValid() const {
return mChunkOffsetOffset >= 0
&& mSampleToChunkOffset >= 0
&& mSampleSizeOffset >= 0
&& mHasTimeToSample;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,902 |
Android | acc192347665943ca674acf117e4f74a88436922 | FLAC__StreamDecoderTellStatus FLACParser::tellCallback(
FLAC__uint64 *absolute_byte_offset)
{
*absolute_byte_offset = mCurrentPos;
return FLAC__STREAM_DECODER_TELL_STATUS_OK;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,988 |
openjpeg | baf0c1ad4572daa89caa3b12985bdd93530f0dd7 | static void opj_applyLUT8u_8u32s_C1P3R(
OPJ_UINT8 const* pSrc, OPJ_INT32 srcStride,
OPJ_INT32* const* pDst, OPJ_INT32 const* pDstStride,
OPJ_UINT8 const* const* pLUT,
OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 y;
OPJ_INT32* pR = pDst[0];
OPJ_INT32* pG = pDst[1];
OPJ_INT32* pB = pDst[2];
OPJ_UINT8 const* pLUT_R = pLUT[0];
OPJ_UINT8 const* pLUT_G = pLUT[1];
OPJ_UINT8 const* pLUT_B = pLUT[2];
for (y = height; y != 0U; --y) {
OPJ_UINT32 x;
for (x = 0; x < width; x++) {
OPJ_UINT8 idx = pSrc[x];
pR[x] = (OPJ_INT32)pLUT_R[idx];
pG[x] = (OPJ_INT32)pLUT_G[idx];
pB[x] = (OPJ_INT32)pLUT_B[idx];
}
pSrc += srcStride;
pR += pDstStride[0];
pG += pDstStride[1];
pB += pDstStride[2];
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,972 |
Android | cc274e2abe8b2a6698a5c47d8aa4bb45f1f9538d | Cluster* Cluster::Create(Segment* pSegment, long idx, long long off)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment, idx, element_start);
assert(pCluster);
return pCluster;
}
| 1 | CVE-2016-2464 | 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,487 |
Chrome | d0947db40187f4708c58e64cbd6013faf9eddeed | xmlParseConditionalSections(xmlParserCtxtPtr ctxt) {
int id = ctxt->input->id;
SKIP(3);
SKIP_BLANKS;
if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) {
SKIP(7);
SKIP_BLANKS;
if (RAW != '[') {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
NEXT;
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Entering INCLUDE Conditional Section\n");
}
while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') ||
(NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
xmlParseConditionalSections(ctxt);
} else if (IS_BLANK_CH(CUR)) {
NEXT;
} else if (RAW == '%') {
xmlParsePEReference(ctxt);
} else
xmlParseMarkupDecl(ctxt);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
break;
}
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Leaving INCLUDE Conditional Section\n");
}
} else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) {
int state;
xmlParserInputState instate;
int depth = 0;
SKIP(6);
SKIP_BLANKS;
if (RAW != '[') {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
NEXT;
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Entering IGNORE Conditional Section\n");
}
/*
* Parse up to the end of the conditional section
* But disable SAX event generating DTD building in the meantime
*/
state = ctxt->disableSAX;
instate = ctxt->instate;
if (ctxt->recovery == 0) ctxt->disableSAX = 1;
ctxt->instate = XML_PARSER_IGNORE;
while (((depth >= 0) && (RAW != 0)) &&
(ctxt->instate != XML_PARSER_EOF)) {
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
depth++;
SKIP(3);
continue;
}
if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) {
if (--depth >= 0) SKIP(3);
continue;
}
NEXT;
continue;
}
ctxt->disableSAX = state;
ctxt->instate = instate;
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Leaving IGNORE Conditional Section\n");
}
} else {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL);
}
if (RAW == 0)
SHRINK;
if (RAW == 0) {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL);
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
SKIP(3);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,838 |
gd-libgd | 47eb44b2e90ca88a08dca9f9a1aa9041e9587f43 | GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP)
{
int i, j, ret;
unsigned char count;
if(flag) {
scd->curbit = 0;
scd->lastbit = 0;
scd->last_byte = 0;
scd->done = FALSE;
return 0;
}
if((scd->curbit + code_size) >= scd->lastbit) {
if(scd->done) {
if(scd->curbit >= scd->lastbit) {
/* Oh well */
}
return -1;
}
scd->buf[0] = scd->buf[scd->last_byte - 2];
scd->buf[1] = scd->buf[scd->last_byte - 1];
if((count = GetDataBlock(fd, &scd->buf[2], ZeroDataBlockP)) <= 0) {
scd->done = TRUE;
}
scd->last_byte = 2 + count;
scd->curbit = (scd->curbit - scd->lastbit) + 16;
scd->lastbit = (2 + count) * 8;
}
ret = 0;
for (i = scd->curbit, j = 0; j < code_size; ++i, ++j) {
if (i < CSD_BUF_SIZE * 8) {
ret |= ((scd->buf[i / 8] & (1 << (i % 8))) != 0) << j;
} else {
ret = -1;
break;
}
}
scd->curbit += code_size;
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,287 |
linux | 7ed47b7d142ec99ad6880bbbec51e9f12b3af74c | static void __exit ghash_mod_exit(void)
{
crypto_unregister_shash(&ghash_alg);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,764 |
exim | d740d2111f189760593a303124ff6b9b1f83453d | do_local_deliveries(void)
{
open_db dbblock;
open_db *dbm_file = NULL;
time_t now = time(NULL);
/* Loop until we have exhausted the supply of local deliveries */
while (addr_local)
{
struct timeval delivery_start;
struct timeval deliver_time;
address_item *addr2, *addr3, *nextaddr;
int logflags = LOG_MAIN;
int logchar = dont_deliver? '*' : '=';
transport_instance *tp;
uschar * serialize_key = NULL;
/* Pick the first undelivered address off the chain */
address_item *addr = addr_local;
addr_local = addr->next;
addr->next = NULL;
DEBUG(D_deliver|D_transport)
debug_printf("--------> %s <--------\n", addr->address);
/* An internal disaster if there is no transport. Should not occur! */
if (!(tp = addr->transport))
{
logflags |= LOG_PANIC;
disable_logging = FALSE; /* Jic */
addr->message = addr->router
? string_sprintf("No transport set by %s router", addr->router->name)
: string_sprintf("No transport set by system filter");
post_process_one(addr, DEFER, logflags, EXIM_DTYPE_TRANSPORT, 0);
continue;
}
/* Check that this base address hasn't previously been delivered to this
transport. The check is necessary at this point to handle homonymic addresses
correctly in cases where the pattern of redirection changes between delivery
attempts. Non-homonymic previous delivery is detected earlier, at routing
time. */
if (previously_transported(addr, FALSE)) continue;
/* There are weird cases where logging is disabled */
disable_logging = tp->disable_logging;
/* Check for batched addresses and possible amalgamation. Skip all the work
if either batch_max <= 1 or there aren't any other addresses for local
delivery. */
if (tp->batch_max > 1 && addr_local)
{
int batch_count = 1;
BOOL uses_dom = readconf_depends((driver_instance *)tp, US"domain");
BOOL uses_lp = ( testflag(addr, af_pfr)
&& (testflag(addr, af_file) || addr->local_part[0] == '|')
)
|| readconf_depends((driver_instance *)tp, US"local_part");
uschar *batch_id = NULL;
address_item **anchor = &addr_local;
address_item *last = addr;
address_item *next;
/* Expand the batch_id string for comparison with other addresses.
Expansion failure suppresses batching. */
if (tp->batch_id)
{
deliver_set_expansions(addr);
batch_id = expand_string(tp->batch_id);
deliver_set_expansions(NULL);
if (!batch_id)
{
log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand batch_id option "
"in %s transport (%s): %s", tp->name, addr->address,
expand_string_message);
batch_count = tp->batch_max;
}
}
/* Until we reach the batch_max limit, pick off addresses which have the
same characteristics. These are:
same transport
not previously delivered (see comment about 50 lines above)
same local part if the transport's configuration contains $local_part
or if this is a file or pipe delivery from a redirection
same domain if the transport's configuration contains $domain
same errors address
same additional headers
same headers to be removed
same uid/gid for running the transport
same first host if a host list is set
*/
while ((next = *anchor) && batch_count < tp->batch_max)
{
BOOL ok =
tp == next->transport
&& !previously_transported(next, TRUE)
&& testflag(addr, af_pfr) == testflag(next, af_pfr)
&& testflag(addr, af_file) == testflag(next, af_file)
&& (!uses_lp || Ustrcmp(next->local_part, addr->local_part) == 0)
&& (!uses_dom || Ustrcmp(next->domain, addr->domain) == 0)
&& same_strings(next->prop.errors_address, addr->prop.errors_address)
&& same_headers(next->prop.extra_headers, addr->prop.extra_headers)
&& same_strings(next->prop.remove_headers, addr->prop.remove_headers)
&& same_ugid(tp, addr, next)
&& ( !addr->host_list && !next->host_list
|| addr->host_list
&& next->host_list
&& Ustrcmp(addr->host_list->name, next->host_list->name) == 0
);
/* If the transport has a batch_id setting, batch_id will be non-NULL
from the expansion outside the loop. Expand for this address and compare.
Expansion failure makes this address ineligible for batching. */
if (ok && batch_id)
{
uschar *bid;
address_item *save_nextnext = next->next;
next->next = NULL; /* Expansion for a single address */
deliver_set_expansions(next);
next->next = save_nextnext;
bid = expand_string(tp->batch_id);
deliver_set_expansions(NULL);
if (!bid)
{
log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand batch_id option "
"in %s transport (%s): %s", tp->name, next->address,
expand_string_message);
ok = FALSE;
}
else ok = (Ustrcmp(batch_id, bid) == 0);
}
/* Take address into batch if OK. */
if (ok)
{
*anchor = next->next; /* Include the address */
next->next = NULL;
last->next = next;
last = next;
batch_count++;
}
else anchor = &next->next; /* Skip the address */
}
}
/* We now have one or more addresses that can be delivered in a batch. Check
whether the transport is prepared to accept a message of this size. If not,
fail them all forthwith. If the expansion fails, or does not yield an
integer, defer delivery. */
if (tp->message_size_limit)
{
int rc = check_message_size(tp, addr);
if (rc != OK)
{
replicate_status(addr);
while (addr)
{
addr2 = addr->next;
post_process_one(addr, rc, logflags, EXIM_DTYPE_TRANSPORT, 0);
addr = addr2;
}
continue; /* With next batch of addresses */
}
}
/* If we are not running the queue, or if forcing, all deliveries will be
attempted. Otherwise, we must respect the retry times for each address. Even
when not doing this, we need to set up the retry key string, and determine
whether a retry record exists, because after a successful delivery, a delete
retry item must be set up. Keep the retry database open only for the duration
of these checks, rather than for all local deliveries, because some local
deliveries (e.g. to pipes) can take a substantial time. */
if (!(dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE)))
{
DEBUG(D_deliver|D_retry|D_hints_lookup)
debug_printf("no retry data available\n");
}
addr2 = addr;
addr3 = NULL;
while (addr2)
{
BOOL ok = TRUE; /* to deliver this address */
uschar *retry_key;
/* Set up the retry key to include the domain or not, and change its
leading character from "R" to "T". Must make a copy before doing this,
because the old key may be pointed to from a "delete" retry item after
a routing delay. */
retry_key = string_copy(
tp->retry_use_local_part ? addr2->address_retry_key :
addr2->domain_retry_key);
*retry_key = 'T';
/* Inspect the retry data. If there is no hints file, delivery happens. */
if (dbm_file)
{
dbdata_retry *retry_record = dbfn_read(dbm_file, retry_key);
/* If there is no retry record, delivery happens. If there is,
remember it exists so it can be deleted after a successful delivery. */
if (retry_record)
{
setflag(addr2, af_lt_retry_exists);
/* A retry record exists for this address. If queue running and not
forcing, inspect its contents. If the record is too old, or if its
retry time has come, or if it has passed its cutoff time, delivery
will go ahead. */
DEBUG(D_retry)
{
debug_printf("retry record exists: age=%s ",
readconf_printtime(now - retry_record->time_stamp));
debug_printf("(max %s)\n", readconf_printtime(retry_data_expire));
debug_printf(" time to retry = %s expired = %d\n",
readconf_printtime(retry_record->next_try - now),
retry_record->expired);
}
if (queue_running && !deliver_force)
{
ok = (now - retry_record->time_stamp > retry_data_expire)
|| (now >= retry_record->next_try)
|| retry_record->expired;
/* If we haven't reached the retry time, there is one more check
to do, which is for the ultimate address timeout. */
if (!ok)
ok = retry_ultimate_address_timeout(retry_key, addr2->domain,
retry_record, now);
}
}
else DEBUG(D_retry) debug_printf("no retry record exists\n");
}
/* This address is to be delivered. Leave it on the chain. */
if (ok)
{
addr3 = addr2;
addr2 = addr2->next;
}
/* This address is to be deferred. Take it out of the chain, and
post-process it as complete. Must take it out of the chain first,
because post processing puts it on another chain. */
else
{
address_item *this = addr2;
this->message = US"Retry time not yet reached";
this->basic_errno = ERRNO_LRETRY;
addr2 = addr3 ? (addr3->next = addr2->next)
: (addr = addr2->next);
post_process_one(this, DEFER, logflags, EXIM_DTYPE_TRANSPORT, 0);
}
}
if (dbm_file) dbfn_close(dbm_file);
/* If there are no addresses left on the chain, they all deferred. Loop
for the next set of addresses. */
if (!addr) continue;
/* If the transport is limited for parallellism, enforce that here.
We use a hints DB entry, incremented here and decremented after
the transport (and any shadow transport) completes. */
if (tpt_parallel_check(tp, addr, &serialize_key))
{
if (expand_string_message)
{
logflags |= LOG_PANIC;
do
{
addr = addr->next;
post_process_one(addr, DEFER, logflags, EXIM_DTYPE_TRANSPORT, 0);
} while ((addr = addr2));
}
continue; /* Loop for the next set of addresses. */
}
/* So, finally, we do have some addresses that can be passed to the
transport. Before doing so, set up variables that are relevant to a
single delivery. */
deliver_set_expansions(addr);
gettimeofday(&delivery_start, NULL);
deliver_local(addr, FALSE);
timesince(&deliver_time, &delivery_start);
/* If a shadow transport (which must perforce be another local transport), is
defined, and its condition is met, we must pass the message to the shadow
too, but only those addresses that succeeded. We do this by making a new
chain of addresses - also to keep the original chain uncontaminated. We must
use a chain rather than doing it one by one, because the shadow transport may
batch.
NOTE: if the condition fails because of a lookup defer, there is nothing we
can do! */
if ( tp->shadow
&& ( !tp->shadow_condition
|| expand_check_condition(tp->shadow_condition, tp->name, US"transport")
) )
{
transport_instance *stp;
address_item *shadow_addr = NULL;
address_item **last = &shadow_addr;
for (stp = transports; stp; stp = stp->next)
if (Ustrcmp(stp->name, tp->shadow) == 0) break;
if (!stp)
log_write(0, LOG_MAIN|LOG_PANIC, "shadow transport \"%s\" not found ",
tp->shadow);
/* Pick off the addresses that have succeeded, and make clones. Put into
the shadow_message field a pointer to the shadow_message field of the real
address. */
else for (addr2 = addr; addr2; addr2 = addr2->next)
if (addr2->transport_return == OK)
{
addr3 = store_get(sizeof(address_item));
*addr3 = *addr2;
addr3->next = NULL;
addr3->shadow_message = US &addr2->shadow_message;
addr3->transport = stp;
addr3->transport_return = DEFER;
addr3->return_filename = NULL;
addr3->return_file = -1;
*last = addr3;
last = &addr3->next;
}
/* If we found any addresses to shadow, run the delivery, and stick any
message back into the shadow_message field in the original. */
if (shadow_addr)
{
int save_count = transport_count;
DEBUG(D_deliver|D_transport)
debug_printf(">>>>>>>>>>>>>>>> Shadow delivery >>>>>>>>>>>>>>>>\n");
deliver_local(shadow_addr, TRUE);
for(; shadow_addr; shadow_addr = shadow_addr->next)
{
int sresult = shadow_addr->transport_return;
*(uschar **)shadow_addr->shadow_message =
sresult == OK
? string_sprintf(" ST=%s", stp->name)
: string_sprintf(" ST=%s (%s%s%s)", stp->name,
shadow_addr->basic_errno <= 0
? US""
: US strerror(shadow_addr->basic_errno),
shadow_addr->basic_errno <= 0 || !shadow_addr->message
? US""
: US": ",
shadow_addr->message
? shadow_addr->message
: shadow_addr->basic_errno <= 0
? US"unknown error"
: US"");
DEBUG(D_deliver|D_transport)
debug_printf("%s shadow transport returned %s for %s\n",
stp->name,
sresult == OK ? "OK" :
sresult == DEFER ? "DEFER" :
sresult == FAIL ? "FAIL" :
sresult == PANIC ? "PANIC" : "?",
shadow_addr->address);
}
DEBUG(D_deliver|D_transport)
debug_printf(">>>>>>>>>>>>>>>> End shadow delivery >>>>>>>>>>>>>>>>\n");
transport_count = save_count; /* Restore original transport count */
}
}
/* Cancel the expansions that were set up for the delivery. */
deliver_set_expansions(NULL);
/* If the transport was parallelism-limited, decrement the hints DB record. */
if (serialize_key) enq_end(serialize_key);
/* Now we can process the results of the real transport. We must take each
address off the chain first, because post_process_one() puts it on another
chain. */
for (addr2 = addr; addr2; addr2 = nextaddr)
{
int result = addr2->transport_return;
nextaddr = addr2->next;
DEBUG(D_deliver|D_transport)
debug_printf("%s transport returned %s for %s\n",
tp->name,
result == OK ? "OK" :
result == DEFER ? "DEFER" :
result == FAIL ? "FAIL" :
result == PANIC ? "PANIC" : "?",
addr2->address);
/* If there is a retry_record, or if delivery is deferred, build a retry
item for setting a new retry time or deleting the old retry record from
the database. These items are handled all together after all addresses
have been handled (so the database is open just for a short time for
updating). */
if (result == DEFER || testflag(addr2, af_lt_retry_exists))
{
int flags = result == DEFER ? 0 : rf_delete;
uschar *retry_key = string_copy(tp->retry_use_local_part
? addr2->address_retry_key : addr2->domain_retry_key);
*retry_key = 'T';
retry_add_item(addr2, retry_key, flags);
}
/* Done with this address */
if (result == OK)
{
addr2->more_errno = deliver_time.tv_sec;
addr2->delivery_usec = deliver_time.tv_usec;
}
post_process_one(addr2, result, logflags, EXIM_DTYPE_TRANSPORT, logchar);
/* If a pipe delivery generated text to be sent back, the result may be
changed to FAIL, and we must copy this for subsequent addresses in the
batch. */
if (addr2->transport_return != result)
{
for (addr3 = nextaddr; addr3; addr3 = addr3->next)
{
addr3->transport_return = addr2->transport_return;
addr3->basic_errno = addr2->basic_errno;
addr3->message = addr2->message;
}
result = addr2->transport_return;
}
/* Whether or not the result was changed to FAIL, we need to copy the
return_file value from the first address into all the addresses of the
batch, so they are all listed in the error message. */
addr2->return_file = addr->return_file;
/* Change log character for recording successful deliveries. */
if (result == OK) logchar = '-';
}
} /* Loop back for next batch of addresses */
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,829 |
thrift | cfaadcc4adcfde2a8232c62ec89870b73ef40df1 | static uint64_t fromWire64(uint64_t x) {return ntohll(x);} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,385 |
linux | f2e323ec96077642d397bb1c355def536d489d16 | static int ttusbdecfe_dvbt_read_status(struct dvb_frontend *fe,
fe_status_t *status)
{
struct ttusbdecfe_state* state = fe->demodulator_priv;
u8 b[] = { 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 };
u8 result[4];
int len, ret;
*status=0;
ret=state->config->send_command(fe, 0x73, sizeof(b), b, &len, result);
if(ret)
return ret;
if(len != 4) {
printk(KERN_ERR "%s: unexpected reply\n", __func__);
return -EIO;
}
switch(result[3]) {
case 1: /* not tuned yet */
case 2: /* no signal/no lock*/
break;
case 3: /* signal found and locked*/
*status = FE_HAS_SIGNAL | FE_HAS_VITERBI |
FE_HAS_SYNC | FE_HAS_CARRIER | FE_HAS_LOCK;
break;
case 4:
*status = FE_TIMEDOUT;
break;
default:
pr_info("%s: returned unknown value: %d\n",
__func__, result[3]);
return -EIO;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,089 |
lighttpd1.4 | b03b86f47b0d5a553137f081fadc482b4af1372d | connection_get_state (request_state_t state)
{
switch (state) {
case CON_STATE_CONNECT: return "connect";
case CON_STATE_READ: return "read";
case CON_STATE_READ_POST: return "readpost";
case CON_STATE_WRITE: return "write";
case CON_STATE_CLOSE: return "close";
case CON_STATE_ERROR: return "error";
case CON_STATE_HANDLE_REQUEST: return "handle-req";
case CON_STATE_REQUEST_START: return "req-start";
case CON_STATE_REQUEST_END: return "req-end";
case CON_STATE_RESPONSE_START: return "resp-start";
case CON_STATE_RESPONSE_END: return "resp-end";
default: return "(unknown)";
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,824 |
xserver | 144849ea27230962227e62a943b399e2ab304787 | SProcXkbGetKbdByName(ClientPtr client)
{
REQUEST(xkbGetKbdByNameReq);
swaps(&stuff->length);
REQUEST_AT_LEAST_SIZE(xkbGetKbdByNameReq);
swaps(&stuff->deviceSpec);
swaps(&stuff->want);
swaps(&stuff->need);
return ProcXkbGetKbdByName(client);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,658 |
linux | 3b0541791453fbe7f42867e310e0c9eb6295364d | static int sas_ex_manuf_info(struct domain_device *dev)
{
u8 *mi_req;
u8 *mi_resp;
int res;
mi_req = alloc_smp_req(MI_REQ_SIZE);
if (!mi_req)
return -ENOMEM;
mi_resp = alloc_smp_resp(MI_RESP_SIZE);
if (!mi_resp) {
kfree(mi_req);
return -ENOMEM;
}
mi_req[1] = SMP_REPORT_MANUF_INFO;
res = smp_execute_task(dev, mi_req, MI_REQ_SIZE, mi_resp,MI_RESP_SIZE);
if (res) {
pr_notice("MI: ex %016llx failed:0x%x\n",
SAS_ADDR(dev->sas_addr), res);
goto out;
} else if (mi_resp[2] != SMP_RESP_FUNC_ACC) {
pr_debug("MI ex %016llx returned SMP result:0x%x\n",
SAS_ADDR(dev->sas_addr), mi_resp[2]);
goto out;
}
ex_assign_manuf_info(dev, mi_resp);
out:
kfree(mi_req);
kfree(mi_resp);
return res;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,068 |
Android | 22f824feac43d5758f9a70b77f2aca840ba62c3b | virtual void notifyResolution(
uint32_t width, uint32_t height) {
Parcel data, reply;
data.writeInterfaceToken(ICrypto::getInterfaceDescriptor());
data.writeInt32(width);
data.writeInt32(height);
remote()->transact(NOTIFY_RESOLUTION, data, &reply);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,446 |
Chrome | deaa07bec5d105ffc546d37eba3da4cba341fc03 | void ObserverOnLogoAvailable(LogoObserver* observer,
bool from_cache,
LogoCallbackReason type,
const base::Optional<Logo>& logo) {
switch (type) {
case LogoCallbackReason::DISABLED:
case LogoCallbackReason::CANCELED:
case LogoCallbackReason::FAILED:
break;
case LogoCallbackReason::REVALIDATED:
break;
case LogoCallbackReason::DETERMINED:
observer->OnLogoAvailable(logo ? &logo.value() : nullptr, from_cache);
break;
}
if (!from_cache) {
observer->OnObserverRemoved();
}
}
| 1 | CVE-2015-1290 | 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,721 |
tnef | 8dccf79857ceeb7a6d3e42c1e762e7b865d5344d | parse_file (FILE* input_file, char* directory,
char *body_filename, char *body_pref,
int flags)
{
uint32 d;
uint16 key;
Attr *attr = NULL;
File *file = NULL;
int rtf_size = 0, html_size = 0;
MessageBody body;
memset (&body, '\0', sizeof (MessageBody));
/* store the program options in our file global variables */
g_flags = flags;
/* check that this is in fact a TNEF file */
d = geti32(input_file);
if (d != TNEF_SIGNATURE)
{
fprintf (stdout, "Seems not to be a TNEF file\n");
return 1;
}
/* Get the key */
key = geti16(input_file);
debug_print ("TNEF Key: %hx\n", key);
/* The rest of the file is a series of 'messages' and 'attachments' */
while ( data_left( input_file ) )
{
attr = read_object( input_file );
if ( attr == NULL ) break;
/* This signals the beginning of a file */
if (attr->name == attATTACHRENDDATA)
{
if (file)
{
file_write (file, directory);
file_free (file);
}
else
{
file = CHECKED_XCALLOC (File, 1);
}
}
/* Add the data to our lists. */
switch (attr->lvl_type)
{
case LVL_MESSAGE:
if (attr->name == attBODY)
{
body.text_body = get_text_data (attr);
}
else if (attr->name == attMAPIPROPS)
{
MAPI_Attr **mapi_attrs
= mapi_attr_read (attr->len, attr->buf);
if (mapi_attrs)
{
int i;
for (i = 0; mapi_attrs[i]; i++)
{
MAPI_Attr *a = mapi_attrs[i];
if (a->name == MAPI_BODY_HTML)
{
body.html_bodies = get_html_data (a);
html_size = a->num_values;
}
else if (a->name == MAPI_RTF_COMPRESSED)
{
body.rtf_bodies = get_rtf_data (a);
rtf_size = a->num_values;
}
}
/* cannot save attributes to file, since they
* are not attachment attributes */
/* file_add_mapi_attrs (file, mapi_attrs); */
mapi_attr_free_list (mapi_attrs);
XFREE (mapi_attrs);
}
}
break;
case LVL_ATTACHMENT:
file_add_attr (file, attr);
break;
default:
fprintf (stderr, "Invalid lvl type on attribute: %d\n",
attr->lvl_type);
return 1;
break;
}
attr_free (attr);
XFREE (attr);
}
if (file)
{
file_write (file, directory);
file_free (file);
XFREE (file);
}
/* Write the message body */
if (flags & SAVEBODY)
{
int i = 0;
int all_flag = 0;
if (strcmp (body_pref, "all") == 0)
{
all_flag = 1;
body_pref = "rht";
}
for (; i < 3; i++)
{
File **files
= get_body_files (body_filename, body_pref[i], &body);
if (files)
{
int j = 0;
for (; files[j]; j++)
{
file_write(files[j], directory);
file_free (files[j]);
XFREE(files[j]);
}
XFREE(files);
if (!all_flag) break;
}
}
}
if (body.text_body)
{
free_bodies(body.text_body, 1);
XFREE(body.text_body);
}
if (rtf_size > 0)
{
free_bodies(body.rtf_bodies, rtf_size);
XFREE(body.rtf_bodies);
}
if (html_size > 0)
{
free_bodies(body.html_bodies, html_size);
XFREE(body.html_bodies);
}
return 0;
}
| 1 | CVE-2017-6310 | 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. | 4,444 |
openssl | 9cb177301fdab492e4cfef376b28339afe3ef663 | static LDOUBLE pow_10(int in_exp)
{
LDOUBLE result = 1;
while (in_exp) {
result *= 10;
in_exp--;
}
return result;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,196 |
ImageMagick | f6e9d0d9955e85bdd7540b251cd50d598dacc5e6 | static void *AcquireBZIPMemory(void *context,int items,int size)
{
(void) context;
return((void *) AcquireQuantumMemory((size_t) items,(size_t) size));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,584 |
Chrome | f335421145bb7f82c60fb9d61babcd6ce2e4b21e | bool Extension::LoadManagedModeSites(
const DictionaryValue* content_pack_value,
string16* error) {
if (!content_pack_value->HasKey(keys::kContentPackSites))
return true;
FilePath::StringType site_list_str;
if (!content_pack_value->GetString(keys::kContentPackSites, &site_list_str)) {
*error = ASCIIToUTF16(errors::kInvalidContentPackSites);
return false;
}
content_pack_site_list_ = FilePath(site_list_str);
return true;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,747 |
Chrome | 62154472bd2c43e1790dd1bd8a527c1db9118d88 | void WebBluetoothServiceImpl::RemoteServerGetPrimaryServicesImpl(
const blink::WebBluetoothDeviceId& device_id,
blink::mojom::WebBluetoothGATTQueryQuantity quantity,
const base::Optional<BluetoothUUID>& services_uuid,
RemoteServerGetPrimaryServicesCallback callback,
device::BluetoothDevice* device) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!device->IsGattConnected()) {
RecordGetPrimaryServicesOutcome(
quantity, UMAGetPrimaryServiceOutcome::DEVICE_DISCONNECTED);
std::move(callback).Run(blink::mojom::WebBluetoothResult::NO_SERVICES_FOUND,
base::nullopt /* services */);
return;
}
DCHECK(device->IsGattServicesDiscoveryComplete());
std::vector<device::BluetoothRemoteGattService*> services =
services_uuid ? device->GetPrimaryServicesByUUID(services_uuid.value())
: device->GetPrimaryServices();
std::vector<blink::mojom::WebBluetoothRemoteGATTServicePtr> response_services;
for (device::BluetoothRemoteGattService* service : services) {
if (!allowed_devices().IsAllowedToAccessService(device_id,
service->GetUUID())) {
continue;
}
std::string service_instance_id = service->GetIdentifier();
const std::string& device_address = device->GetAddress();
auto insert_result = service_id_to_device_address_.insert(
make_pair(service_instance_id, device_address));
if (!insert_result.second)
DCHECK_EQ(insert_result.first->second, device_address);
blink::mojom::WebBluetoothRemoteGATTServicePtr service_ptr =
blink::mojom::WebBluetoothRemoteGATTService::New();
service_ptr->instance_id = service_instance_id;
service_ptr->uuid = service->GetUUID();
response_services.push_back(std::move(service_ptr));
if (quantity == blink::mojom::WebBluetoothGATTQueryQuantity::SINGLE) {
break;
}
}
if (!response_services.empty()) {
DVLOG(1) << "Services found in device.";
RecordGetPrimaryServicesOutcome(quantity,
UMAGetPrimaryServiceOutcome::SUCCESS);
std::move(callback).Run(blink::mojom::WebBluetoothResult::SUCCESS,
std::move(response_services));
return;
}
DVLOG(1) << "Services not found in device.";
RecordGetPrimaryServicesOutcome(
quantity, services_uuid ? UMAGetPrimaryServiceOutcome::NOT_FOUND
: UMAGetPrimaryServiceOutcome::NO_SERVICES);
std::move(callback).Run(
services_uuid ? blink::mojom::WebBluetoothResult::SERVICE_NOT_FOUND
: blink::mojom::WebBluetoothResult::NO_SERVICES_FOUND,
base::nullopt /* services */);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,332 |
drogon | 3c785326c63a34aa1799a639ae185bc9453cb447 | int HttpFileImpl::save() const
{
return save(HttpAppFrameworkImpl::instance().getUploadPath());
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,954 |
skiboot | 5be38b672c1410e2f10acd3ad2eecfdc81d5daf7 | static char *char_to_wchar(const char *key, const size_t keylen)
{
int i;
char *str;
str = zalloc(keylen * 2);
if (!str)
return NULL;
for (i = 0; i < keylen*2; key++) {
str[i++] = *key;
str[i++] = '\0';
}
return str;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,857 |
linux | 0ddcff49b672239dda94d70d0fcf50317a9f4b51 | static int mac80211_hwsim_add_chanctx(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *ctx)
{
hwsim_set_chanctx_magic(ctx);
wiphy_dbg(hw->wiphy,
"add channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n",
ctx->def.chan->center_freq, ctx->def.width,
ctx->def.center_freq1, ctx->def.center_freq2);
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,436 |
linux | dab6cf55f81a6e16b8147aed9a843e1691dcd318 | static int s390_regs_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int rc = 0;
if (target == current)
save_access_regs(target->thread.acrs);
if (kbuf) {
const unsigned long *k = kbuf;
while (count > 0 && !rc) {
rc = __poke_user(target, pos, *k++);
count -= sizeof(*k);
pos += sizeof(*k);
}
} else {
const unsigned long __user *u = ubuf;
while (count > 0 && !rc) {
unsigned long word;
rc = __get_user(word, u++);
if (rc)
break;
rc = __poke_user(target, pos, word);
count -= sizeof(*u);
pos += sizeof(*u);
}
}
if (rc == 0 && target == current)
restore_access_regs(target->thread.acrs);
return rc;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,665 |
Chrome | a81c185f34b34ef8410239506825b185b332c00b | void GaiaCookieManagerService::OnListAccountsFailure(
const GoogleServiceAuthError& error) {
VLOG(1) << "ListAccounts failed";
DCHECK(requests_.front().request_type() ==
GaiaCookieRequestType::LIST_ACCOUNTS);
if (++fetcher_retries_ < kMaxFetcherRetries && error.IsTransientError()) {
fetcher_backoff_.InformOfRequest(false);
UMA_HISTOGRAM_ENUMERATION("Signin.ListAccountsRetry",
error.state(), GoogleServiceAuthError::NUM_STATES);
fetcher_timer_.Start(
FROM_HERE, fetcher_backoff_.GetTimeUntilRelease(),
base::Bind(&SigninClient::DelayNetworkCall,
base::Unretained(signin_client_),
base::Bind(
&GaiaCookieManagerService::StartFetchingListAccounts,
base::Unretained(this))));
return;
}
UMA_HISTOGRAM_ENUMERATION("Signin.ListAccountsFailure",
error.state(), GoogleServiceAuthError::NUM_STATES);
for (auto& observer : observer_list_) {
observer.OnGaiaAccountsInCookieUpdated(listed_accounts_,
signed_out_accounts_, error);
}
HandleNextRequest();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,884 |
Chrome | ed5c0b5ff5cec5a12235b868d0f3ba7e0c0f2a24 | void OnGetSystemSalt(const GetSystemSaltCallback& callback,
dbus::Response* response) {
if (!response) {
callback.Run(DBUS_METHOD_CALL_FAILURE, std::vector<uint8>());
return;
}
dbus::MessageReader reader(response);
const uint8* bytes = NULL;
size_t length = 0;
if (!reader.PopArrayOfBytes(&bytes, &length)) {
callback.Run(DBUS_METHOD_CALL_FAILURE, std::vector<uint8>());
return;
}
callback.Run(DBUS_METHOD_CALL_SUCCESS,
std::vector<uint8>(bytes, bytes + length));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,721 |
collectd | d16c24542b2f96a194d43a73c2e5778822b9cb47 | static int csnmp_strvbcopy(char *dst, /* {{{ */
const struct variable_list *vb, size_t dst_size) {
char *src;
size_t num_chars;
if (vb->type == ASN_OCTET_STR)
src = (char *)vb->val.string;
else if (vb->type == ASN_BIT_STR)
src = (char *)vb->val.bitstring;
else if (vb->type == ASN_IPADDRESS) {
return ssnprintf(dst, dst_size,
"%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8 "",
(uint8_t)vb->val.string[0], (uint8_t)vb->val.string[1],
(uint8_t)vb->val.string[2], (uint8_t)vb->val.string[3]);
} else {
dst[0] = 0;
return (EINVAL);
}
num_chars = dst_size - 1;
if (num_chars > vb->val_len)
num_chars = vb->val_len;
for (size_t i = 0; i < num_chars; i++) {
/* Check for control characters. */
if ((unsigned char)src[i] < 32)
return (csnmp_strvbcopy_hexstring(dst, vb, dst_size));
dst[i] = src[i];
}
dst[num_chars] = 0;
dst[dst_size - 1] = 0;
if (dst_size <= vb->val_len)
return ENOMEM;
return 0;
} /* }}} int csnmp_strvbcopy */
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,901 |
netdata | 92327c9ec211bd1616315abcb255861b130b97ca | inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) {
debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
int ret = 400;
BUFFER *dimensions = NULL;
buffer_flush(w->response.data);
char *google_version = "0.6",
*google_reqId = "0",
*google_sig = "0",
*google_out = "json",
*responseHandler = NULL,
*outFileName = NULL;
time_t last_timestamp_in_data = 0, google_timestamp = 0;
char *chart = NULL
, *before_str = NULL
, *after_str = NULL
, *group_time_str = NULL
, *points_str = NULL;
int group = RRDR_GROUPING_AVERAGE;
uint32_t format = DATASOURCE_JSON;
uint32_t options = 0x00000000;
while(url) {
char *value = mystrsep(&url, "?&");
if(!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
// name and value are now the parameters
// they are not null and not empty
if(!strcmp(name, "chart")) chart = value;
else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
if(!dimensions) dimensions = buffer_create(100);
buffer_strcat(dimensions, "|");
buffer_strcat(dimensions, value);
}
else if(!strcmp(name, "after")) after_str = value;
else if(!strcmp(name, "before")) before_str = value;
else if(!strcmp(name, "points")) points_str = value;
else if(!strcmp(name, "gtime")) group_time_str = value;
else if(!strcmp(name, "group")) {
group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE);
}
else if(!strcmp(name, "format")) {
format = web_client_api_request_v1_data_format(value);
}
else if(!strcmp(name, "options")) {
options |= web_client_api_request_v1_data_options(value);
}
else if(!strcmp(name, "callback")) {
responseHandler = value;
}
else if(!strcmp(name, "filename")) {
outFileName = value;
}
else if(!strcmp(name, "tqx")) {
// parse Google Visualization API options
// https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
char *tqx_name, *tqx_value;
while(value) {
tqx_value = mystrsep(&value, ";");
if(!tqx_value || !*tqx_value) continue;
tqx_name = mystrsep(&tqx_value, ":");
if(!tqx_name || !*tqx_name) continue;
if(!tqx_value || !*tqx_value) continue;
if(!strcmp(tqx_name, "version"))
google_version = tqx_value;
else if(!strcmp(tqx_name, "reqId"))
google_reqId = tqx_value;
else if(!strcmp(tqx_name, "sig")) {
google_sig = tqx_value;
google_timestamp = strtoul(google_sig, NULL, 0);
}
else if(!strcmp(tqx_name, "out")) {
google_out = tqx_value;
format = web_client_api_request_v1_data_google_format(google_out);
}
else if(!strcmp(tqx_name, "responseHandler"))
responseHandler = tqx_value;
else if(!strcmp(tqx_name, "outFileName"))
outFileName = tqx_value;
}
}
}
if(!chart || !*chart) {
buffer_sprintf(w->response.data, "No chart id is given at the request.");
goto cleanup;
}
RRDSET *st = rrdset_find(host, chart);
if(!st) st = rrdset_find_byname(host, chart);
if(!st) {
buffer_strcat(w->response.data, "Chart is not found: ");
buffer_strcat_htmlescape(w->response.data, chart);
ret = 404;
goto cleanup;
}
st->last_accessed_time = now_realtime_sec();
long long before = (before_str && *before_str)?str2l(before_str):0;
long long after = (after_str && *after_str) ?str2l(after_str):0;
int points = (points_str && *points_str)?str2i(points_str):0;
long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0;
debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'"
, w->id
, chart
, (dimensions)?buffer_tostring(dimensions):""
, after
, before
, points
, group
, format
, options
);
if(outFileName && *outFileName) {
buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
}
if(format == DATASOURCE_DATATABLE_JSONP) {
if(responseHandler == NULL)
responseHandler = "google.visualization.Query.setResponse";
debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
}
else if(format == DATASOURCE_JSONP) {
if(responseHandler == NULL)
responseHandler = "callback";
buffer_strcat(w->response.data, responseHandler);
buffer_strcat(w->response.data, "(");
}
ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time
, options, &last_timestamp_in_data);
if(format == DATASOURCE_DATATABLE_JSONP) {
if(google_timestamp < last_timestamp_in_data)
buffer_strcat(w->response.data, "});");
else {
// the client already has the latest data
buffer_flush(w->response.data);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
responseHandler, google_version, google_reqId);
}
}
else if(format == DATASOURCE_JSONP)
buffer_strcat(w->response.data, ");");
cleanup:
buffer_free(dimensions);
return ret;
} | 1 | CVE-2018-18839 | 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. | 3,978 |
krb5 | 8ee70ec63931d1e38567905387ab9b1d45734d81 | find_alternate_tgs(krb5_kdc_req *request, krb5_db_entry **server_ptr)
{
krb5_error_code retval;
krb5_principal *plist = NULL, *pl2, tmpprinc;
krb5_data tmp;
krb5_db_entry *server = NULL;
*server_ptr = NULL;
/*
* Call to krb5_princ_component is normally not safe but is so
* here only because find_alternate_tgs() is only called from
* somewhere that has already checked the number of components in
* the principal.
*/
if ((retval = krb5_walk_realm_tree(kdc_context,
krb5_princ_realm(kdc_context, request->server),
krb5_princ_component(kdc_context, request->server, 1),
&plist, KRB5_REALM_BRANCH_CHAR)))
return retval;
/* move to the end */
for (pl2 = plist; *pl2; pl2++);
/* the first entry in this array is for krbtgt/local@local, so we
ignore it */
while (--pl2 > plist) {
tmp = *krb5_princ_realm(kdc_context, *pl2);
krb5_princ_set_realm(kdc_context, *pl2,
krb5_princ_realm(kdc_context, tgs_server));
retval = krb5_db_get_principal(kdc_context, *pl2, 0, &server);
krb5_princ_set_realm(kdc_context, *pl2, &tmp);
if (retval == KRB5_KDB_NOENTRY)
continue;
else if (retval)
goto cleanup;
/* Found it. */
tmp = *krb5_princ_realm(kdc_context, *pl2);
krb5_princ_set_realm(kdc_context, *pl2,
krb5_princ_realm(kdc_context, tgs_server));
retval = krb5_copy_principal(kdc_context, *pl2, &tmpprinc);
if (retval)
goto cleanup;
krb5_princ_set_realm(kdc_context, *pl2, &tmp);
krb5_free_principal(kdc_context, request->server);
request->server = tmpprinc;
log_tgs_alt_tgt(request->server);
*server_ptr = server;
server = NULL;
goto cleanup;
}
retval = KRB5_KDB_NOENTRY;
cleanup:
krb5_free_realm_tree(kdc_context, plist);
krb5_db_free_principal(kdc_context, server);
return retval;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,902 |
Chrome | d59a4441697f6253e7dc3f7ae5caad6e5fd2c778 | ImageBitmap::ImageBitmap(ImageData* data,
Optional<IntRect> cropRect,
const ImageBitmapOptions& options) {
IntRect dataSrcRect = IntRect(IntPoint(), data->size());
ParsedOptions parsedOptions =
parseOptions(options, cropRect, data->bitmapSourceSize());
if (dstBufferSizeHasOverflow(parsedOptions))
return;
IntRect srcRect = cropRect ? intersection(parsedOptions.cropRect, dataSrcRect)
: dataSrcRect;
if (!parsedOptions.premultiplyAlpha) {
unsigned char* srcAddr = data->data()->data();
SkImageInfo info = SkImageInfo::Make(
parsedOptions.cropRect.width(), parsedOptions.cropRect.height(),
kN32_SkColorType, kUnpremul_SkAlphaType);
size_t bytesPerPixel = static_cast<size_t>(info.bytesPerPixel());
size_t srcPixelBytesPerRow = bytesPerPixel * data->size().width();
size_t dstPixelBytesPerRow = bytesPerPixel * parsedOptions.cropRect.width();
sk_sp<SkImage> skImage;
if (parsedOptions.cropRect == IntRect(IntPoint(), data->size())) {
swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow,
parsedOptions.flipY);
skImage =
SkImage::MakeRasterCopy(SkPixmap(info, srcAddr, dstPixelBytesPerRow));
swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow,
parsedOptions.flipY);
} else {
RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(
static_cast<size_t>(parsedOptions.cropRect.height()) *
parsedOptions.cropRect.width(),
bytesPerPixel);
if (!dstBuffer)
return;
RefPtr<Uint8Array> copiedDataBuffer =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
if (!srcRect.isEmpty()) {
IntPoint srcPoint = IntPoint(
(parsedOptions.cropRect.x() > 0) ? parsedOptions.cropRect.x() : 0,
(parsedOptions.cropRect.y() > 0) ? parsedOptions.cropRect.y() : 0);
IntPoint dstPoint = IntPoint(
(parsedOptions.cropRect.x() >= 0) ? 0 : -parsedOptions.cropRect.x(),
(parsedOptions.cropRect.y() >= 0) ? 0
: -parsedOptions.cropRect.y());
int copyHeight = data->size().height() - srcPoint.y();
if (parsedOptions.cropRect.height() < copyHeight)
copyHeight = parsedOptions.cropRect.height();
int copyWidth = data->size().width() - srcPoint.x();
if (parsedOptions.cropRect.width() < copyWidth)
copyWidth = parsedOptions.cropRect.width();
for (int i = 0; i < copyHeight; i++) {
size_t srcStartCopyPosition =
(i + srcPoint.y()) * srcPixelBytesPerRow +
srcPoint.x() * bytesPerPixel;
size_t srcEndCopyPosition =
srcStartCopyPosition + copyWidth * bytesPerPixel;
size_t dstStartCopyPosition;
if (parsedOptions.flipY)
dstStartCopyPosition =
(parsedOptions.cropRect.height() - 1 - dstPoint.y() - i) *
dstPixelBytesPerRow +
dstPoint.x() * bytesPerPixel;
else
dstStartCopyPosition = (dstPoint.y() + i) * dstPixelBytesPerRow +
dstPoint.x() * bytesPerPixel;
for (size_t j = 0; j < srcEndCopyPosition - srcStartCopyPosition;
j++) {
if (kN32_SkColorType == kBGRA_8888_SkColorType) {
if (j % 4 == 0)
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j + 2];
else if (j % 4 == 2)
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j - 2];
else
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j];
} else {
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j];
}
}
}
}
skImage = newSkImageFromRaster(info, std::move(copiedDataBuffer),
dstPixelBytesPerRow);
}
if (!skImage)
return;
if (parsedOptions.shouldScaleInput)
m_image = StaticBitmapImage::create(scaleSkImage(
skImage, parsedOptions.resizeWidth, parsedOptions.resizeHeight,
parsedOptions.resizeQuality));
else
m_image = StaticBitmapImage::create(skImage);
if (!m_image)
return;
m_image->setPremultiplied(parsedOptions.premultiplyAlpha);
return;
}
std::unique_ptr<ImageBuffer> buffer = ImageBuffer::create(
parsedOptions.cropRect.size(), NonOpaque, DoNotInitializeImagePixels);
if (!buffer)
return;
if (srcRect.isEmpty()) {
m_image = StaticBitmapImage::create(buffer->newSkImageSnapshot(
PreferNoAcceleration, SnapshotReasonUnknown));
return;
}
IntPoint dstPoint = IntPoint(std::min(0, -parsedOptions.cropRect.x()),
std::min(0, -parsedOptions.cropRect.y()));
if (parsedOptions.cropRect.x() < 0)
dstPoint.setX(-parsedOptions.cropRect.x());
if (parsedOptions.cropRect.y() < 0)
dstPoint.setY(-parsedOptions.cropRect.y());
buffer->putByteArray(Unmultiplied, data->data()->data(), data->size(),
srcRect, dstPoint);
sk_sp<SkImage> skImage =
buffer->newSkImageSnapshot(PreferNoAcceleration, SnapshotReasonUnknown);
if (parsedOptions.flipY)
skImage = flipSkImageVertically(skImage.get(), PremultiplyAlpha);
if (!skImage)
return;
if (parsedOptions.shouldScaleInput) {
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(
parsedOptions.resizeWidth, parsedOptions.resizeHeight);
if (!surface)
return;
SkPaint paint;
paint.setFilterQuality(parsedOptions.resizeQuality);
SkRect dstDrawRect =
SkRect::MakeWH(parsedOptions.resizeWidth, parsedOptions.resizeHeight);
surface->getCanvas()->drawImageRect(skImage, dstDrawRect, &paint);
skImage = surface->makeImageSnapshot();
}
m_image = StaticBitmapImage::create(std::move(skImage));
}
| 1 | CVE-2016-5209 | 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). | 7,197 |
Chrome | 1a828911013ff501b87aacc5b555e470b31f2909 | void Clipboard::ReadAsciiText(Clipboard::Buffer buffer,
std::string* result) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return;
result->clear();
gchar* text = gtk_clipboard_wait_for_text(clipboard);
if (text == NULL)
return;
result->assign(text);
g_free(text);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,550 |
php-src | fb58e69a84f4fde603a630d2c9df2fa3be16d846 | static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC)
{
const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C);
assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding));
return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,754 |
libmspack | 8759da8db6ec9e866cb8eb143313f397f925bb4f | static int read_spaninfo(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
off_t *length_ptr)
{
struct mspack_system *sys = self->system;
unsigned char *data;
/* find SpanInfo file */
int err = find_sys_file(self, sec, &sec->spaninfo, spaninfo_name);
if (err) return MSPACK_ERR_DATAFORMAT;
/* check it's large enough */
if (sec->spaninfo->length != 8) {
D(("SpanInfo file is wrong size"))
return MSPACK_ERR_DATAFORMAT;
}
/* read the SpanInfo file */
if (!(data = read_sys_file(self, sec->spaninfo))) {
D(("can't read SpanInfo file"))
return self->error;
}
/* get the uncompressed length of the LZX stream */
err = read_off64(length_ptr, data, sys, self->d->infh);
sys->free(data);
if (err) return MSPACK_ERR_DATAFORMAT;
if (*length_ptr <= 0) {
D(("output length is invalid"))
return MSPACK_ERR_DATAFORMAT;
}
return MSPACK_ERR_OK;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,218 |
linux | 2638fd0f92d4397884fd991d8f4925cb3f081901 | tcpmss_tg4(struct sk_buff *skb, const struct xt_action_param *par)
{
struct iphdr *iph = ip_hdr(skb);
__be16 newlen;
int ret;
ret = tcpmss_mangle_packet(skb, par,
PF_INET,
iph->ihl * 4,
sizeof(*iph) + sizeof(struct tcphdr));
if (ret < 0)
return NF_DROP;
if (ret > 0) {
iph = ip_hdr(skb);
newlen = htons(ntohs(iph->tot_len) + ret);
csum_replace2(&iph->check, iph->tot_len, newlen);
iph->tot_len = newlen;
}
return XT_CONTINUE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,708 |
linux-2.6 | b3563c4fbff906991a1b4ef4609f99cca2a0de6a | void __rta_fill(struct sk_buff *skb, int attrtype, int attrlen, const void *data)
{
struct rtattr *rta;
int size = RTA_LENGTH(attrlen);
rta = (struct rtattr*)skb_put(skb, RTA_ALIGN(size));
rta->rta_type = attrtype;
rta->rta_len = size;
memcpy(RTA_DATA(rta), data, attrlen);
} | 1 | CVE-2005-4881 | 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. | 1,704 |
savannah | 8d22746c9e5af80ff4304aef440986403a5072e2 | psh_hint_table_init( PSH_Hint_Table table,
PS_Hint_Table hints,
PS_Mask_Table hint_masks,
PS_Mask_Table counter_masks,
FT_Memory memory )
{
FT_UInt count;
FT_Error error;
FT_UNUSED( counter_masks );
count = hints->num_hints;
/* allocate our tables */
if ( FT_NEW_ARRAY( table->sort, 2 * count ) ||
FT_NEW_ARRAY( table->hints, count ) ||
FT_NEW_ARRAY( table->zones, 2 * count + 1 ) )
goto Exit;
table->max_hints = count;
table->sort_global = table->sort + count;
table->num_hints = 0;
table->num_zones = 0;
table->zone = 0;
/* initialize the `table->hints' array */
{
PSH_Hint write = table->hints;
PS_Hint read = hints->hints;
for ( ; count > 0; count--, write++, read++ )
{
write->org_pos = read->pos;
write->org_len = read->len;
write->flags = read->flags;
}
}
/* we now need to determine the initial `parent' stems; first */
/* activate the hints that are given by the initial hint masks */
if ( hint_masks )
{
PS_Mask mask = hint_masks->masks;
count = hint_masks->num_masks;
table->hint_masks = hint_masks;
for ( ; count > 0; count--, mask++ )
psh_hint_table_record_mask( table, mask );
}
/* finally, do a linear parse in case some hints were left alone */
if ( table->num_hints != table->max_hints )
{
FT_UInt idx;
FT_TRACE0(( "psh_hint_table_init: missing/incorrect hint masks\n" ));
count = table->max_hints;
for ( idx = 0; idx < count; idx++ )
psh_hint_table_record( table, idx );
}
Exit:
return error;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,751 |
Chrome | 5f8671e7667b8b133bd3664100012a3906e92d65 | void Wait() {
run_loop_.reset(new base::RunLoop());
run_loop_->Run();
run_loop_.reset();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,078 |
md4c | 4fc808d8fe8d8904f8525bb4231d854f45e23a19 | md_analyze_line(MD_CTX* ctx, OFF beg, OFF* p_end,
const MD_LINE_ANALYSIS* pivot_line, MD_LINE_ANALYSIS* line)
{
unsigned total_indent = 0;
int n_parents = 0;
int n_brothers = 0;
int n_children = 0;
MD_CONTAINER container = { 0 };
int prev_line_has_list_loosening_effect = ctx->last_line_has_list_loosening_effect;
OFF off = beg;
OFF hr_killer = 0;
int ret = 0;
line->indent = md_line_indentation(ctx, total_indent, off, &off);
total_indent += line->indent;
line->beg = off;
/* Given the indentation and block quote marks '>', determine how many of
* the current containers are our parents. */
while(n_parents < ctx->n_containers) {
MD_CONTAINER* c = &ctx->containers[n_parents];
if(c->ch == _T('>') && line->indent < ctx->code_indent_offset &&
off < ctx->size && CH(off) == _T('>'))
{
/* Block quote mark. */
off++;
total_indent++;
line->indent = md_line_indentation(ctx, total_indent, off, &off);
total_indent += line->indent;
/* The optional 1st space after '>' is part of the block quote mark. */
if(line->indent > 0)
line->indent--;
line->beg = off;
} else if(c->ch != _T('>') && line->indent >= c->contents_indent) {
/* List. */
line->indent -= c->contents_indent;
} else {
break;
}
n_parents++;
}
if(off >= ctx->size || ISNEWLINE(off)) {
/* Blank line does not need any real indentation to be nested inside
* a list. */
if(n_brothers + n_children == 0) {
while(n_parents < ctx->n_containers && ctx->containers[n_parents].ch != _T('>'))
n_parents++;
}
}
while(TRUE) {
/* Check whether we are fenced code continuation. */
if(pivot_line->type == MD_LINE_FENCEDCODE) {
line->beg = off;
/* We are another MD_LINE_FENCEDCODE unless we are closing fence
* which we transform into MD_LINE_BLANK. */
if(line->indent < ctx->code_indent_offset) {
if(md_is_closing_code_fence(ctx, CH(pivot_line->beg), off, &off)) {
line->type = MD_LINE_BLANK;
ctx->last_line_has_list_loosening_effect = FALSE;
break;
}
}
/* Change indentation accordingly to the initial code fence. */
if(n_parents == ctx->n_containers) {
if(line->indent > pivot_line->indent)
line->indent -= pivot_line->indent;
else
line->indent = 0;
line->type = MD_LINE_FENCEDCODE;
break;
}
}
/* Check whether we are HTML block continuation. */
if(pivot_line->type == MD_LINE_HTML && ctx->html_block_type > 0) {
if(n_parents < ctx->n_containers) {
/* HTML block is implicitly ended if the enclosing container
* block ends. */
ctx->html_block_type = 0;
} else {
int html_block_type;
html_block_type = md_is_html_block_end_condition(ctx, off, &off);
if(html_block_type > 0) {
MD_ASSERT(html_block_type == ctx->html_block_type);
/* Make sure this is the last line of the block. */
ctx->html_block_type = 0;
/* Some end conditions serve as blank lines at the same time. */
if(html_block_type == 6 || html_block_type == 7) {
line->type = MD_LINE_BLANK;
line->indent = 0;
break;
}
}
line->type = MD_LINE_HTML;
n_parents = ctx->n_containers;
break;
}
}
/* Check for blank line. */
if(off >= ctx->size || ISNEWLINE(off)) {
if(pivot_line->type == MD_LINE_INDENTEDCODE && n_parents == ctx->n_containers) {
line->type = MD_LINE_INDENTEDCODE;
if(line->indent > ctx->code_indent_offset)
line->indent -= ctx->code_indent_offset;
else
line->indent = 0;
ctx->last_line_has_list_loosening_effect = FALSE;
} else {
line->type = MD_LINE_BLANK;
ctx->last_line_has_list_loosening_effect = (n_parents > 0 &&
n_brothers + n_children == 0 &&
ctx->containers[n_parents-1].ch != _T('>'));
#if 1
/* See https://github.com/mity/md4c/issues/6
*
* This ugly checking tests we are in (yet empty) list item but
* not its very first line (i.e. not the line with the list
* item mark).
*
* If we are such a blank line, then any following non-blank
* line which would be part of the list item actually has to
* end the list because according to the specification, "a list
* item can begin with at most one blank line."
*/
if(n_parents > 0 && ctx->containers[n_parents-1].ch != _T('>') &&
n_brothers + n_children == 0 && ctx->current_block == NULL &&
ctx->n_block_bytes > (int) sizeof(MD_BLOCK))
{
MD_BLOCK* top_block = (MD_BLOCK*) ((char*)ctx->block_bytes + ctx->n_block_bytes - sizeof(MD_BLOCK));
if(top_block->type == MD_BLOCK_LI)
ctx->last_list_item_starts_with_two_blank_lines = TRUE;
}
#endif
}
break;
} else {
#if 1
/* This is the 2nd half of the hack. If the flag is set (i.e. there
* was a 2nd blank line at the beginning of the list item) and if
* we would otherwise still belong to the list item, we enforce
* the end of the list. */
ctx->last_line_has_list_loosening_effect = FALSE;
if(ctx->last_list_item_starts_with_two_blank_lines) {
if(n_parents > 0 && ctx->containers[n_parents-1].ch != _T('>') &&
n_brothers + n_children == 0 && ctx->current_block == NULL &&
ctx->n_block_bytes > (int) sizeof(MD_BLOCK))
{
MD_BLOCK* top_block = (MD_BLOCK*) ((char*)ctx->block_bytes + ctx->n_block_bytes - sizeof(MD_BLOCK));
if(top_block->type == MD_BLOCK_LI)
n_parents--;
}
ctx->last_list_item_starts_with_two_blank_lines = FALSE;
}
#endif
}
/* Check whether we are Setext underline. */
if(line->indent < ctx->code_indent_offset && pivot_line->type == MD_LINE_TEXT
&& (CH(off) == _T('=') || CH(off) == _T('-'))
&& (n_parents == ctx->n_containers))
{
unsigned level;
if(md_is_setext_underline(ctx, off, &off, &level)) {
line->type = MD_LINE_SETEXTUNDERLINE;
line->data = level;
break;
}
}
/* Check for thematic break line. */
if(line->indent < ctx->code_indent_offset && ISANYOF(off, _T("-_*")) && off >= hr_killer) {
if(md_is_hr_line(ctx, off, &off, &hr_killer)) {
line->type = MD_LINE_HR;
break;
}
}
/* Check for "brother" container. I.e. whether we are another list item
* in already started list. */
if(n_parents < ctx->n_containers && n_brothers + n_children == 0) {
OFF tmp;
if(md_is_container_mark(ctx, line->indent, off, &tmp, &container) &&
md_is_container_compatible(&ctx->containers[n_parents], &container))
{
pivot_line = &md_dummy_blank_line;
off = tmp;
total_indent += container.contents_indent - container.mark_indent;
line->indent = md_line_indentation(ctx, total_indent, off, &off);
total_indent += line->indent;
line->beg = off;
/* Some of the following whitespace actually still belongs to the mark. */
if(off >= ctx->size || ISNEWLINE(off)) {
container.contents_indent++;
} else if(line->indent <= ctx->code_indent_offset) {
container.contents_indent += line->indent;
line->indent = 0;
} else {
container.contents_indent += 1;
line->indent--;
}
ctx->containers[n_parents].mark_indent = container.mark_indent;
ctx->containers[n_parents].contents_indent = container.contents_indent;
n_brothers++;
continue;
}
}
/* Check for indented code.
* Note indented code block cannot interrupt a paragraph. */
if(line->indent >= ctx->code_indent_offset &&
(pivot_line->type == MD_LINE_BLANK || pivot_line->type == MD_LINE_INDENTEDCODE))
{
line->type = MD_LINE_INDENTEDCODE;
MD_ASSERT(line->indent >= ctx->code_indent_offset);
line->indent -= ctx->code_indent_offset;
line->data = 0;
break;
}
/* Check for start of a new container block. */
if(line->indent < ctx->code_indent_offset &&
md_is_container_mark(ctx, line->indent, off, &off, &container))
{
if(pivot_line->type == MD_LINE_TEXT && n_parents == ctx->n_containers &&
(off >= ctx->size || ISNEWLINE(off)) && container.ch != _T('>'))
{
/* Noop. List mark followed by a blank line cannot interrupt a paragraph. */
} else if(pivot_line->type == MD_LINE_TEXT && n_parents == ctx->n_containers &&
(container.ch == _T('.') || container.ch == _T(')')) && container.start != 1)
{
/* Noop. Ordered list cannot interrupt a paragraph unless the start index is 1. */
} else {
total_indent += container.contents_indent - container.mark_indent;
line->indent = md_line_indentation(ctx, total_indent, off, &off);
total_indent += line->indent;
line->beg = off;
line->data = container.ch;
/* Some of the following whitespace actually still belongs to the mark. */
if(off >= ctx->size || ISNEWLINE(off)) {
container.contents_indent++;
} else if(line->indent <= ctx->code_indent_offset) {
container.contents_indent += line->indent;
line->indent = 0;
} else {
container.contents_indent += 1;
line->indent--;
}
if(n_brothers + n_children == 0)
pivot_line = &md_dummy_blank_line;
if(n_children == 0)
MD_CHECK(md_leave_child_containers(ctx, n_parents + n_brothers));
n_children++;
MD_CHECK(md_push_container(ctx, &container));
continue;
}
}
/* Check whether we are table continuation. */
if(pivot_line->type == MD_LINE_TABLE && n_parents == ctx->n_containers) {
line->type = MD_LINE_TABLE;
break;
}
/* Check for ATX header. */
if(line->indent < ctx->code_indent_offset && CH(off) == _T('#')) {
unsigned level;
if(md_is_atxheader_line(ctx, off, &line->beg, &off, &level)) {
line->type = MD_LINE_ATXHEADER;
line->data = level;
break;
}
}
/* Check whether we are starting code fence. */
if(CH(off) == _T('`') || CH(off) == _T('~')) {
if(md_is_opening_code_fence(ctx, off, &off)) {
line->type = MD_LINE_FENCEDCODE;
line->data = 1;
break;
}
}
/* Check for start of raw HTML block. */
if(CH(off) == _T('<') && !(ctx->parser.flags & MD_FLAG_NOHTMLBLOCKS))
{
ctx->html_block_type = md_is_html_block_start_condition(ctx, off);
/* HTML block type 7 cannot interrupt paragraph. */
if(ctx->html_block_type == 7 && pivot_line->type == MD_LINE_TEXT)
ctx->html_block_type = 0;
if(ctx->html_block_type > 0) {
/* The line itself also may immediately close the block. */
if(md_is_html_block_end_condition(ctx, off, &off) == ctx->html_block_type) {
/* Make sure this is the last line of the block. */
ctx->html_block_type = 0;
}
line->type = MD_LINE_HTML;
break;
}
}
/* Check for table underline. */
if((ctx->parser.flags & MD_FLAG_TABLES) && pivot_line->type == MD_LINE_TEXT &&
(CH(off) == _T('|') || CH(off) == _T('-') || CH(off) == _T(':')) &&
n_parents == ctx->n_containers)
{
unsigned col_count;
if(ctx->current_block != NULL && ctx->current_block->n_lines == 1 &&
md_is_table_underline(ctx, off, &off, &col_count))
{
line->data = col_count;
line->type = MD_LINE_TABLEUNDERLINE;
break;
}
}
/* By default, we are normal text line. */
line->type = MD_LINE_TEXT;
if(pivot_line->type == MD_LINE_TEXT && n_brothers + n_children == 0) {
/* Lazy continuation. */
n_parents = ctx->n_containers;
}
/* Check for task mark. */
if((ctx->parser.flags & MD_FLAG_TASKLISTS) && n_brothers + n_children > 0 &&
ISANYOF_(ctx->containers[ctx->n_containers-1].ch, _T("-+*.)")))
{
OFF tmp = off;
while(tmp < ctx->size && tmp < off + 3 && ISBLANK(tmp))
tmp++;
if(tmp + 2 < ctx->size && CH(tmp) == _T('[') &&
ISANYOF(tmp+1, _T("xX ")) && CH(tmp+2) == _T(']') &&
(tmp + 3 == ctx->size || ISBLANK(tmp+3) || ISNEWLINE(tmp+3)))
{
MD_CONTAINER* task_container = (n_children > 0 ? &ctx->containers[ctx->n_containers-1] : &container);
task_container->is_task = TRUE;
task_container->task_mark_off = tmp + 1;
off = tmp + 3;
while(ISWHITESPACE(off))
off++;
line->beg = off;
}
}
break;
}
/* Scan for end of the line.
*
* Note this is quite a bottleneck of the parsing as we here iterate almost
* over compete document.
*/
#if defined __linux__ && !defined MD4C_USE_UTF16
/* Recent glibc versions have superbly optimized strcspn(), even using
* vectorization if available. */
if(ctx->doc_ends_with_newline && off < ctx->size) {
while(TRUE) {
off += (OFF) strcspn(STR(off), "\r\n");
/* strcspn() can stop on zero terminator; but that can appear
* anywhere in the Markfown input... */
if(CH(off) == _T('\0'))
off++;
else
break;
}
} else
#endif
{
/* Optimization: Use some loop unrolling. */
while(off + 3 < ctx->size && !ISNEWLINE(off+0) && !ISNEWLINE(off+1)
&& !ISNEWLINE(off+2) && !ISNEWLINE(off+3))
off += 4;
while(off < ctx->size && !ISNEWLINE(off))
off++;
}
/* Set end of the line. */
line->end = off;
/* But for ATX header, we should exclude the optional trailing mark. */
if(line->type == MD_LINE_ATXHEADER) {
OFF tmp = line->end;
while(tmp > line->beg && CH(tmp-1) == _T(' '))
tmp--;
while(tmp > line->beg && CH(tmp-1) == _T('#'))
tmp--;
if(tmp == line->beg || CH(tmp-1) == _T(' ') || (ctx->parser.flags & MD_FLAG_PERMISSIVEATXHEADERS))
line->end = tmp;
}
/* Trim trailing spaces. */
if(line->type != MD_LINE_INDENTEDCODE && line->type != MD_LINE_FENCEDCODE) {
while(line->end > line->beg && CH(line->end-1) == _T(' '))
line->end--;
}
/* Eat also the new line. */
if(off < ctx->size && CH(off) == _T('\r'))
off++;
if(off < ctx->size && CH(off) == _T('\n'))
off++;
*p_end = off;
/* If we belong to a list after seeing a blank line, the list is loose. */
if(prev_line_has_list_loosening_effect && line->type != MD_LINE_BLANK && n_parents + n_brothers > 0) {
MD_CONTAINER* c = &ctx->containers[n_parents + n_brothers - 1];
if(c->ch != _T('>')) {
MD_BLOCK* block = (MD_BLOCK*) (((char*)ctx->block_bytes) + c->block_byte_off);
block->flags |= MD_BLOCK_LOOSE_LIST;
}
}
/* Leave any containers we are not part of anymore. */
if(n_children == 0 && n_parents + n_brothers < ctx->n_containers)
MD_CHECK(md_leave_child_containers(ctx, n_parents + n_brothers));
/* Enter any container we found a mark for. */
if(n_brothers > 0) {
MD_ASSERT(n_brothers == 1);
MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI,
ctx->containers[n_parents].task_mark_off,
(ctx->containers[n_parents].is_task ? CH(ctx->containers[n_parents].task_mark_off) : 0),
MD_BLOCK_CONTAINER_CLOSER));
MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI,
container.task_mark_off,
(container.is_task ? CH(container.task_mark_off) : 0),
MD_BLOCK_CONTAINER_OPENER));
ctx->containers[n_parents].is_task = container.is_task;
ctx->containers[n_parents].task_mark_off = container.task_mark_off;
}
if(n_children > 0)
MD_CHECK(md_enter_child_containers(ctx, n_children));
abort:
return ret;
} | 1 | CVE-2021-30027 | 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. | 564 |
htcondor | 8f9b304c4f6c0a98dafa61b2c0e4beb3b70e4c84 | SchedulerObject::suspend(std::string key, std::string &/*reason*/, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
scheduler.enqueueActOnJobMyself(id,JA_SUSPEND_JOBS,true);
return true;
}
| 1 | CVE-2012-4462 | 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. | 569 |
linux | 8141c7f3e7aee618312fa1c15109e1219de784a7 | static int unshare_sighand(unsigned long unshare_flags, struct sighand_struct **new_sighp)
{
struct sighand_struct *sigh = current->sighand;
if ((unshare_flags & CLONE_SIGHAND) && atomic_read(&sigh->count) > 1)
return -EINVAL;
else
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,444 |
bpf | 4b81ccebaeee885ab1aa1438133f2991e3a2b6ea | static void bpf_ringbuf_commit(void *sample, u64 flags, bool discard)
{
unsigned long rec_pos, cons_pos;
struct bpf_ringbuf_hdr *hdr;
struct bpf_ringbuf *rb;
u32 new_len;
hdr = sample - BPF_RINGBUF_HDR_SZ;
rb = bpf_ringbuf_restore_from_rec(hdr);
new_len = hdr->len ^ BPF_RINGBUF_BUSY_BIT;
if (discard)
new_len |= BPF_RINGBUF_DISCARD_BIT;
/* update record header with correct final size prefix */
xchg(&hdr->len, new_len);
/* if consumer caught up and is waiting for our record, notify about
* new data availability
*/
rec_pos = (void *)hdr - (void *)rb->data;
cons_pos = smp_load_acquire(&rb->consumer_pos) & rb->mask;
if (flags & BPF_RB_FORCE_WAKEUP)
irq_work_queue(&rb->work);
else if (cons_pos == rec_pos && !(flags & BPF_RB_NO_WAKEUP))
irq_work_queue(&rb->work);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,482 |
linux-stable | 8dfbcc4351a0b6d2f2d77f367552f48ffefafe18 | static void dump_firm_type_and_int_freq(unsigned int type, u16 int_freq)
{
if (type & BASE)
printk("BASE ");
if (type & INIT1)
printk("INIT1 ");
if (type & F8MHZ)
printk("F8MHZ ");
if (type & MTS)
printk("MTS ");
if (type & D2620)
printk("D2620 ");
if (type & D2633)
printk("D2633 ");
if (type & DTV6)
printk("DTV6 ");
if (type & QAM)
printk("QAM ");
if (type & DTV7)
printk("DTV7 ");
if (type & DTV78)
printk("DTV78 ");
if (type & DTV8)
printk("DTV8 ");
if (type & FM)
printk("FM ");
if (type & INPUT1)
printk("INPUT1 ");
if (type & LCD)
printk("LCD ");
if (type & NOGD)
printk("NOGD ");
if (type & MONO)
printk("MONO ");
if (type & ATSC)
printk("ATSC ");
if (type & IF)
printk("IF ");
if (type & LG60)
printk("LG60 ");
if (type & ATI638)
printk("ATI638 ");
if (type & OREN538)
printk("OREN538 ");
if (type & OREN36)
printk("OREN36 ");
if (type & TOYOTA388)
printk("TOYOTA388 ");
if (type & TOYOTA794)
printk("TOYOTA794 ");
if (type & DIBCOM52)
printk("DIBCOM52 ");
if (type & ZARLINK456)
printk("ZARLINK456 ");
if (type & CHINA)
printk("CHINA ");
if (type & F6MHZ)
printk("F6MHZ ");
if (type & INPUT2)
printk("INPUT2 ");
if (type & SCODE)
printk("SCODE ");
if (type & HAS_IF)
printk("HAS_IF_%d ", int_freq);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,541 |
libtiff | 787c0ee906430b772f33ca50b97b8b5ca070faec | DECLAREreadFunc(readSeparateTilesIntoBuffer)
{
int status = 1;
uint32 imagew = TIFFRasterScanlineSize(in);
uint32 tilew = TIFFTileRowSize(in);
int iskew = imagew - tilew*spp;
tsize_t tilesize = TIFFTileSize(in);
tdata_t tilebuf;
uint8* bufp = (uint8*) buf;
uint32 tw, tl;
uint32 row;
uint16 bps = 0, bytes_per_sample;
tilebuf = _TIFFmalloc(tilesize);
if (tilebuf == 0)
return 0;
_TIFFmemset(tilebuf, 0, tilesize);
(void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
(void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
(void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
if( bps == 0 )
{
TIFFError(TIFFFileName(in), "Error, cannot read BitsPerSample");
status = 0;
goto done;
}
assert( bps % 8 == 0 );
bytes_per_sample = bps/8;
for (row = 0; row < imagelength; row += tl) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth; col += tw) {
tsample_t s;
for (s = 0; s < spp; s++) {
if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read tile at %lu %lu, "
"sample %lu",
(unsigned long) col,
(unsigned long) row,
(unsigned long) s);
status = 0;
goto done;
}
/*
* Tile is clipped horizontally. Calculate
* visible portion and skewing factors.
*/
if (colb + tilew*spp > imagew) {
uint32 width = imagew - colb;
int oskew = tilew*spp - width;
cpSeparateBufToContigBuf(
bufp+colb+s*bytes_per_sample,
tilebuf, nrow,
width/(spp*bytes_per_sample),
oskew + iskew,
oskew/spp, spp,
bytes_per_sample);
} else
cpSeparateBufToContigBuf(
bufp+colb+s*bytes_per_sample,
tilebuf, nrow, tw,
iskew, 0, spp,
bytes_per_sample);
}
colb += tilew*spp;
}
bufp += imagew * nrow;
}
done:
_TIFFfree(tilebuf);
return status;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,646 |
linux | 45f6fad84cc305103b28d73482b344d7f5b76f39 | int inet6_sk_rebuild_header(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct dst_entry *dst;
dst = __sk_dst_check(sk, np->dst_cookie);
if (!dst) {
struct inet_sock *inet = inet_sk(sk);
struct in6_addr *final_p, final;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = sk->sk_protocol;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = np->saddr;
fl6.flowlabel = np->flow_label;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = inet->inet_dport;
fl6.fl6_sport = inet->inet_sport;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
final_p = fl6_update_dst(&fl6, np->opt, &final);
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
sk->sk_route_caps = 0;
sk->sk_err_soft = -PTR_ERR(dst);
return PTR_ERR(dst);
}
__ip6_dst_store(sk, dst, NULL, NULL);
}
return 0;
}
| 1 | CVE-2016-3841 | 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. | 8,473 |
mutt | 4a2becbdb4422aaffe3ce314991b9d670b7adf17 | ADDRESS *rfc822_cpy_adr (ADDRESS *addr, int prune)
{
ADDRESS *top = NULL, *last = NULL;
for (; addr; addr = addr->next)
{
if (prune && addr->group && (!addr->next || !addr->next->mailbox))
{
/* ignore this element of the list */
}
else if (last)
{
last->next = rfc822_cpy_adr_real (addr);
last = last->next;
}
else
top = last = rfc822_cpy_adr_real (addr);
}
return top;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,332 |
gnupg | 4bde12206c5bf199dc6e12a74af8da4558ba41bf | get_user_id (u32 * keyid, size_t * rn)
{
user_id_db_t r;
char *p;
int pass = 0;
/* Try it two times; second pass reads from key resources. */
do
{
for (r = user_id_db; r; r = r->next)
{
keyid_list_t a;
for (a = r->keyids; a; a = a->next)
{
if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
{
p = xmalloc (r->len);
memcpy (p, r->name, r->len);
*rn = r->len;
return p;
}
}
}
}
while (++pass < 2 && !get_pubkey (NULL, keyid));
p = xstrdup (user_id_not_found_utf8 ());
*rn = strlen (p);
return p;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,379 |
nanopb | e2f0ccf939d9f82931d085acb6df8e9a182a4261 | bool pb_decode_double_as_float(pb_istream_t *stream, float *dest)
{
uint_least8_t sign;
int exponent;
uint32_t mantissa;
uint64_t value;
union { float f; uint32_t i; } out;
if (!pb_decode_fixed64(stream, &value))
return false;
/* Decompose input value */
sign = (uint_least8_t)((value >> 63) & 1);
exponent = (int)((value >> 52) & 0x7FF) - 1023;
mantissa = (value >> 28) & 0xFFFFFF; /* Highest 24 bits */
/* Figure if value is in range representable by floats. */
if (exponent == 1024)
{
/* Special value */
exponent = 128;
mantissa >>= 1;
}
else
{
if (exponent > 127)
{
/* Too large, convert to infinity */
exponent = 128;
mantissa = 0;
}
else if (exponent < -150)
{
/* Too small, convert to zero */
exponent = -127;
mantissa = 0;
}
else if (exponent < -126)
{
/* Denormalized */
mantissa |= 0x1000000;
mantissa >>= (-126 - exponent);
exponent = -127;
}
/* Round off mantissa */
mantissa = (mantissa + 1) >> 1;
/* Check if mantissa went over 2.0 */
if (mantissa & 0x800000)
{
exponent += 1;
mantissa &= 0x7FFFFF;
mantissa >>= 1;
}
}
/* Combine fields */
out.i = mantissa;
out.i |= (uint32_t)(exponent + 127) << 23;
out.i |= (uint32_t)sign << 31;
*dest = out.f;
return true;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,909 |
FreeRDP | 445a5a42c500ceb80f8fa7f2c11f3682538033f3 | POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s)
{
POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE));
if (!pointer_position)
goto fail;
if (Stream_GetRemainingLength(s) < 4)
goto fail;
Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */
Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */
return pointer_position;
fail:
free_pointer_position_update(update->context, pointer_position);
return NULL;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,058 |
tensorflow | 6972f9dfe325636b3db4e0bc517ee22a159365c0 | explicit FusedBatchNormGradOpV3(OpKernelConstruction* context)
: FusedBatchNormGradOpBase<Device, T, U>(context) {} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,962 |
linux-2.6 | f151cd2c54ddc7714e2f740681350476cda03a28 | parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat,
unsigned char *data, struct list_head *auth_tok_list,
struct ecryptfs_auth_tok **new_auth_tok,
size_t *packet_size, size_t max_packet_size)
{
size_t body_size;
struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
size_t length_size;
int rc = 0;
(*packet_size) = 0;
(*new_auth_tok) = NULL;
/**
*This format is inspired by OpenPGP; see RFC 2440
* packet tag 3
*
* Tag 3 identifier (1 byte)
* Max Tag 3 packet size (max 3 bytes)
* Version (1 byte)
* Cipher code (1 byte)
* S2K specifier (1 byte)
* Hash identifier (1 byte)
* Salt (ECRYPTFS_SALT_SIZE)
* Hash iterations (1 byte)
* Encrypted key (arbitrary)
*
* (ECRYPTFS_SALT_SIZE + 7) minimum packet size
*/
if (max_packet_size < (ECRYPTFS_SALT_SIZE + 7)) {
printk(KERN_ERR "Max packet size too large\n");
rc = -EINVAL;
goto out;
}
if (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) {
printk(KERN_ERR "First byte != 0x%.2x; invalid packet\n",
ECRYPTFS_TAG_3_PACKET_TYPE);
rc = -EINVAL;
goto out;
}
/* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
* at end of function upon failure */
auth_tok_list_item =
kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL);
if (!auth_tok_list_item) {
printk(KERN_ERR "Unable to allocate memory\n");
rc = -ENOMEM;
goto out;
}
(*new_auth_tok) = &auth_tok_list_item->auth_tok;
rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
&length_size);
if (rc) {
printk(KERN_WARNING "Error parsing packet length; rc = [%d]\n",
rc);
goto out_free;
}
if (unlikely(body_size < (ECRYPTFS_SALT_SIZE + 5))) {
printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
rc = -EINVAL;
goto out_free;
}
(*packet_size) += length_size;
if (unlikely((*packet_size) + body_size > max_packet_size)) {
printk(KERN_ERR "Packet size exceeds max\n");
rc = -EINVAL;
goto out_free;
}
(*new_auth_tok)->session_key.encrypted_key_size =
(body_size - (ECRYPTFS_SALT_SIZE + 5));
if (unlikely(data[(*packet_size)++] != 0x04)) {
printk(KERN_WARNING "Unknown version number [%d]\n",
data[(*packet_size) - 1]);
rc = -EINVAL;
goto out_free;
}
ecryptfs_cipher_code_to_string(crypt_stat->cipher,
(u16)data[(*packet_size)]);
/* A little extra work to differentiate among the AES key
* sizes; see RFC2440 */
switch(data[(*packet_size)++]) {
case RFC2440_CIPHER_AES_192:
crypt_stat->key_size = 24;
break;
default:
crypt_stat->key_size =
(*new_auth_tok)->session_key.encrypted_key_size;
}
ecryptfs_init_crypt_ctx(crypt_stat);
if (unlikely(data[(*packet_size)++] != 0x03)) {
printk(KERN_WARNING "Only S2K ID 3 is currently supported\n");
rc = -ENOSYS;
goto out_free;
}
/* TODO: finish the hash mapping */
switch (data[(*packet_size)++]) {
case 0x01: /* See RFC2440 for these numbers and their mappings */
/* Choose MD5 */
memcpy((*new_auth_tok)->token.password.salt,
&data[(*packet_size)], ECRYPTFS_SALT_SIZE);
(*packet_size) += ECRYPTFS_SALT_SIZE;
/* This conversion was taken straight from RFC2440 */
(*new_auth_tok)->token.password.hash_iterations =
((u32) 16 + (data[(*packet_size)] & 15))
<< ((data[(*packet_size)] >> 4) + 6);
(*packet_size)++;
/* Friendly reminder:
* (*new_auth_tok)->session_key.encrypted_key_size =
* (body_size - (ECRYPTFS_SALT_SIZE + 5)); */
memcpy((*new_auth_tok)->session_key.encrypted_key,
&data[(*packet_size)],
(*new_auth_tok)->session_key.encrypted_key_size);
(*packet_size) +=
(*new_auth_tok)->session_key.encrypted_key_size;
(*new_auth_tok)->session_key.flags &=
~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
(*new_auth_tok)->session_key.flags |=
ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
(*new_auth_tok)->token.password.hash_algo = 0x01; /* MD5 */
break;
default:
ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: "
"[%d]\n", data[(*packet_size) - 1]);
rc = -ENOSYS;
goto out_free;
}
(*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;
/* TODO: Parametarize; we might actually want userspace to
* decrypt the session key. */
(*new_auth_tok)->session_key.flags &=
~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
(*new_auth_tok)->session_key.flags &=
~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
list_add(&auth_tok_list_item->list, auth_tok_list);
goto out;
out_free:
(*new_auth_tok) = NULL;
memset(auth_tok_list_item, 0,
sizeof(struct ecryptfs_auth_tok_list_item));
kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
auth_tok_list_item);
out:
if (rc)
(*packet_size) = 0;
return rc;
} | 1 | CVE-2009-2407 | 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). | 540 |
linux | 9060cb719e61b685ec0102574e10337fa5f445ea | int af_alg_release(struct socket *sock)
{
if (sock->sk)
sock_put(sock->sk);
return 0;
} | 1 | CVE-2019-8912 | 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. | 5,543 |
pcre2 | 03654e751e7f0700693526b67dfcadda6b42c9d0 | static int get_recurse_data_length(compiler_common *common, PCRE2_SPTR cc, PCRE2_SPTR ccend,
BOOL *needs_control_head, BOOL *has_quit, BOOL *has_accept)
{
int length = 1;
int size, offset;
PCRE2_SPTR alternative;
BOOL quit_found = FALSE;
BOOL accept_found = FALSE;
BOOL setsom_found = FALSE;
BOOL setmark_found = FALSE;
BOOL control_head_found = FALSE;
memset(common->recurse_bitset, 0, common->recurse_bitset_size);
#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD
SLJIT_ASSERT(common->control_head_ptr != 0);
control_head_found = TRUE;
#endif
/* Calculate the sum of the private machine words. */
while (cc < ccend)
{
size = 0;
switch(*cc)
{
case OP_SET_SOM:
SLJIT_ASSERT(common->has_set_som);
setsom_found = TRUE;
cc += 1;
break;
case OP_RECURSE:
if (common->has_set_som)
setsom_found = TRUE;
if (common->mark_ptr != 0)
setmark_found = TRUE;
if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))
length++;
cc += 1 + LINK_SIZE;
break;
case OP_KET:
offset = PRIVATE_DATA(cc);
if (offset != 0)
{
if (recurse_check_bit(common, offset))
length++;
SLJIT_ASSERT(PRIVATE_DATA(cc + 1) != 0);
cc += PRIVATE_DATA(cc + 1);
}
cc += 1 + LINK_SIZE;
break;
case OP_ASSERT:
case OP_ASSERT_NOT:
case OP_ASSERTBACK:
case OP_ASSERTBACK_NOT:
case OP_ASSERT_NA:
case OP_ASSERTBACK_NA:
case OP_ONCE:
case OP_SCRIPT_RUN:
case OP_BRAPOS:
case OP_SBRA:
case OP_SBRAPOS:
case OP_SCOND:
SLJIT_ASSERT(PRIVATE_DATA(cc) != 0);
if (recurse_check_bit(common, PRIVATE_DATA(cc)))
length++;
cc += 1 + LINK_SIZE;
break;
case OP_CBRA:
case OP_SCBRA:
offset = GET2(cc, 1 + LINK_SIZE);
if (recurse_check_bit(common, OVECTOR(offset << 1)))
{
SLJIT_ASSERT(recurse_check_bit(common, OVECTOR((offset << 1) + 1)));
length += 2;
}
if (common->optimized_cbracket[offset] == 0 && recurse_check_bit(common, OVECTOR_PRIV(offset)))
length++;
if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))
length++;
cc += 1 + LINK_SIZE + IMM2_SIZE;
break;
case OP_CBRAPOS:
case OP_SCBRAPOS:
offset = GET2(cc, 1 + LINK_SIZE);
if (recurse_check_bit(common, OVECTOR(offset << 1)))
{
SLJIT_ASSERT(recurse_check_bit(common, OVECTOR((offset << 1) + 1)));
length += 2;
}
if (recurse_check_bit(common, OVECTOR_PRIV(offset)))
length++;
if (recurse_check_bit(common, PRIVATE_DATA(cc)))
length++;
if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))
length++;
cc += 1 + LINK_SIZE + IMM2_SIZE;
break;
case OP_COND:
/* Might be a hidden SCOND. */
alternative = cc + GET(cc, 1);
if ((*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) && recurse_check_bit(common, PRIVATE_DATA(cc)))
length++;
cc += 1 + LINK_SIZE;
break;
CASE_ITERATOR_PRIVATE_DATA_1
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
length++;
cc += 2;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_PRIVATE_DATA_2A
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
{
SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));
length += 2;
}
cc += 2;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_PRIVATE_DATA_2B
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
{
SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));
length += 2;
}
cc += 2 + IMM2_SIZE;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_1
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
length++;
cc += 1;
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_2A
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
{
SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));
length += 2;
}
cc += 1;
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_2B
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
{
SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));
length += 2;
}
cc += 1 + IMM2_SIZE;
break;
case OP_CLASS:
case OP_NCLASS:
#if defined SUPPORT_UNICODE || PCRE2_CODE_UNIT_WIDTH != 8
case OP_XCLASS:
size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(PCRE2_UCHAR);
#else
size = 1 + 32 / (int)sizeof(PCRE2_UCHAR);
#endif
offset = PRIVATE_DATA(cc);
if (offset != 0 && recurse_check_bit(common, offset))
length += get_class_iterator_size(cc + size);
cc += size;
break;
case OP_MARK:
case OP_COMMIT_ARG:
case OP_PRUNE_ARG:
case OP_THEN_ARG:
SLJIT_ASSERT(common->mark_ptr != 0);
if (!setmark_found)
setmark_found = TRUE;
if (common->control_head_ptr != 0)
control_head_found = TRUE;
if (*cc != OP_MARK)
quit_found = TRUE;
cc += 1 + 2 + cc[1];
break;
case OP_PRUNE:
case OP_SKIP:
case OP_COMMIT:
quit_found = TRUE;
cc++;
break;
case OP_SKIP_ARG:
quit_found = TRUE;
cc += 1 + 2 + cc[1];
break;
case OP_THEN:
SLJIT_ASSERT(common->control_head_ptr != 0);
quit_found = TRUE;
control_head_found = TRUE;
cc++;
break;
case OP_ACCEPT:
case OP_ASSERT_ACCEPT:
accept_found = TRUE;
cc++;
break;
default:
cc = next_opcode(common, cc);
SLJIT_ASSERT(cc != NULL);
break;
}
}
SLJIT_ASSERT(cc == ccend);
if (control_head_found)
length++;
if (quit_found)
{
if (setsom_found)
length++;
if (setmark_found)
length++;
}
*needs_control_head = control_head_found;
*has_quit = quit_found;
*has_accept = accept_found;
return length;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,710 |
libjpeg-turbo | 82923eb93a2eacf4a593e00e3e672bbb86a8a3a0 | read_non_rle_pixel (tga_source_ptr sinfo)
/* Read one Targa pixel from the input file; no RLE expansion */
{
register FILE *infile = sinfo->pub.input_file;
register int i;
for (i = 0; i < sinfo->pixel_size; i++) {
sinfo->tga_pixel[i] = (U_CHAR) getc(infile);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,688 |
linux | a6138db815df5ee542d848318e5dae681590fccd | static int do_remount(struct path *path, int flags, int mnt_flags,
void *data)
{
int err;
struct super_block *sb = path->mnt->mnt_sb;
struct mount *mnt = real_mount(path->mnt);
if (!check_mnt(mnt))
return -EINVAL;
if (path->dentry != path->mnt->mnt_root)
return -EINVAL;
err = security_sb_remount(sb, data);
if (err)
return err;
down_write(&sb->s_umount);
if (flags & MS_BIND)
err = change_mount_flags(path->mnt, flags);
else if (!capable(CAP_SYS_ADMIN))
err = -EPERM;
else
err = do_remount_sb(sb, flags, data, 0);
if (!err) {
lock_mount_hash();
mnt_flags |= mnt->mnt.mnt_flags & MNT_PROPAGATION_MASK;
mnt->mnt.mnt_flags = mnt_flags;
touch_mnt_namespace(mnt->mnt_ns);
unlock_mount_hash();
}
up_write(&sb->s_umount);
return err;
}
| 1 | CVE-2014-5206 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 4,804 |
linux | ef87dbe7614341c2e7bfe8d32fcb7028cc97442c | static int raw_cmd_copyin(int cmd, void __user *param,
struct floppy_raw_cmd **rcmd)
{
struct floppy_raw_cmd *ptr;
int ret;
int i;
*rcmd = NULL;
loop:
ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);
if (!ptr)
return -ENOMEM;
*rcmd = ptr;
ret = copy_from_user(ptr, param, sizeof(*ptr));
if (ret)
return -EFAULT;
ptr->next = NULL;
ptr->buffer_length = 0;
param += sizeof(struct floppy_raw_cmd);
if (ptr->cmd_count > 33)
/* the command may now also take up the space
* initially intended for the reply & the
* reply count. Needed for long 82078 commands
* such as RESTORE, which takes ... 17 command
* bytes. Murphy's law #137: When you reserve
* 16 bytes for a structure, you'll one day
* discover that you really need 17...
*/
return -EINVAL;
for (i = 0; i < 16; i++)
ptr->reply[i] = 0;
ptr->resultcode = 0;
ptr->kernel_data = NULL;
if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
if (ptr->length <= 0)
return -EINVAL;
ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);
fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);
if (!ptr->kernel_data)
return -ENOMEM;
ptr->buffer_length = ptr->length;
}
if (ptr->flags & FD_RAW_WRITE) {
ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);
if (ret)
return ret;
}
if (ptr->flags & FD_RAW_MORE) {
rcmd = &(ptr->next);
ptr->rate &= 0x43;
goto loop;
}
return 0;
}
| 1 | CVE-2014-1737 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 222 |
acpica | 37f2c716f2c6ab14c3ba557a539c3ee3224931b5 | AcpiNsEvaluate (
ACPI_EVALUATE_INFO *Info)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsEvaluate);
if (!Info)
{
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
if (!Info->Node)
{
/*
* Get the actual namespace node for the target object if we
* need to. Handles these cases:
*
* 1) Null node, valid pathname from root (absolute path)
* 2) Node and valid pathname (path relative to Node)
* 3) Node, Null pathname
*/
Status = AcpiNsGetNode (Info->PrefixNode, Info->RelativePathname,
ACPI_NS_NO_UPSEARCH, &Info->Node);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
}
/*
* For a method alias, we must grab the actual method node so that
* proper scoping context will be established before execution.
*/
if (AcpiNsGetType (Info->Node) == ACPI_TYPE_LOCAL_METHOD_ALIAS)
{
Info->Node = ACPI_CAST_PTR (
ACPI_NAMESPACE_NODE, Info->Node->Object);
}
/* Complete the info block initialization */
Info->ReturnObject = NULL;
Info->NodeFlags = Info->Node->Flags;
Info->ObjDesc = AcpiNsGetAttachedObject (Info->Node);
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "%s [%p] Value %p\n",
Info->RelativePathname, Info->Node,
AcpiNsGetAttachedObject (Info->Node)));
/* Get info if we have a predefined name (_HID, etc.) */
Info->Predefined = AcpiUtMatchPredefinedMethod (Info->Node->Name.Ascii);
/* Get the full pathname to the object, for use in warning messages */
Info->FullPathname = AcpiNsGetNormalizedPathname (Info->Node, TRUE);
if (!Info->FullPathname)
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
/* Count the number of arguments being passed in */
Info->ParamCount = 0;
if (Info->Parameters)
{
while (Info->Parameters[Info->ParamCount])
{
Info->ParamCount++;
}
/* Warn on impossible argument count */
if (Info->ParamCount > ACPI_METHOD_NUM_ARGS)
{
ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS,
"Excess arguments (%u) - using only %u",
Info->ParamCount, ACPI_METHOD_NUM_ARGS));
Info->ParamCount = ACPI_METHOD_NUM_ARGS;
}
}
/*
* For predefined names: Check that the declared argument count
* matches the ACPI spec -- otherwise this is a BIOS error.
*/
AcpiNsCheckAcpiCompliance (Info->FullPathname, Info->Node,
Info->Predefined);
/*
* For all names: Check that the incoming argument count for
* this method/object matches the actual ASL/AML definition.
*/
AcpiNsCheckArgumentCount (Info->FullPathname, Info->Node,
Info->ParamCount, Info->Predefined);
/* For predefined names: Typecheck all incoming arguments */
AcpiNsCheckArgumentTypes (Info);
/*
* Three major evaluation cases:
*
* 1) Object types that cannot be evaluated by definition
* 2) The object is a control method -- execute it
* 3) The object is not a method -- just return it's current value
*/
switch (AcpiNsGetType (Info->Node))
{
case ACPI_TYPE_DEVICE:
case ACPI_TYPE_EVENT:
case ACPI_TYPE_MUTEX:
case ACPI_TYPE_REGION:
case ACPI_TYPE_THERMAL:
case ACPI_TYPE_LOCAL_SCOPE:
/*
* 1) Disallow evaluation of certain object types. For these,
* object evaluation is undefined and not supported.
*/
ACPI_ERROR ((AE_INFO,
"%s: Evaluation of object type [%s] is not supported",
Info->FullPathname,
AcpiUtGetTypeName (Info->Node->Type)));
Status = AE_TYPE;
goto Cleanup;
case ACPI_TYPE_METHOD:
/*
* 2) Object is a control method - execute it
*/
/* Verify that there is a method object associated with this node */
if (!Info->ObjDesc)
{
ACPI_ERROR ((AE_INFO, "%s: Method has no attached sub-object",
Info->FullPathname));
Status = AE_NULL_OBJECT;
goto Cleanup;
}
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,
"**** Execute method [%s] at AML address %p length %X\n",
Info->FullPathname,
Info->ObjDesc->Method.AmlStart + 1,
Info->ObjDesc->Method.AmlLength - 1));
/*
* Any namespace deletion must acquire both the namespace and
* interpreter locks to ensure that no thread is using the portion of
* the namespace that is being deleted.
*
* Execute the method via the interpreter. The interpreter is locked
* here before calling into the AML parser
*/
AcpiExEnterInterpreter ();
Status = AcpiPsExecuteMethod (Info);
AcpiExExitInterpreter ();
break;
default:
/*
* 3) All other non-method objects -- get the current object value
*/
/*
* Some objects require additional resolution steps (e.g., the Node
* may be a field that must be read, etc.) -- we can't just grab
* the object out of the node.
*
* Use ResolveNodeToValue() to get the associated value.
*
* NOTE: we can get away with passing in NULL for a walk state because
* the Node is guaranteed to not be a reference to either a method
* local or a method argument (because this interface is never called
* from a running method.)
*
* Even though we do not directly invoke the interpreter for object
* resolution, we must lock it because we could access an OpRegion.
* The OpRegion access code assumes that the interpreter is locked.
*/
AcpiExEnterInterpreter ();
/* TBD: ResolveNodeToValue has a strange interface, fix */
Info->ReturnObject = ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Info->Node);
Status = AcpiExResolveNodeToValue (ACPI_CAST_INDIRECT_PTR (
ACPI_NAMESPACE_NODE, &Info->ReturnObject), NULL);
AcpiExExitInterpreter ();
if (ACPI_FAILURE (Status))
{
Info->ReturnObject = NULL;
goto Cleanup;
}
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Returned object %p [%s]\n",
Info->ReturnObject,
AcpiUtGetObjectTypeName (Info->ReturnObject)));
Status = AE_CTRL_RETURN_VALUE; /* Always has a "return value" */
break;
}
/*
* For predefined names, check the return value against the ACPI
* specification. Some incorrect return value types are repaired.
*/
(void) AcpiNsCheckReturnValue (Info->Node, Info, Info->ParamCount,
Status, &Info->ReturnObject);
/* Check if there is a return value that must be dealt with */
if (Status == AE_CTRL_RETURN_VALUE)
{
/* If caller does not want the return value, delete it */
if (Info->Flags & ACPI_IGNORE_RETURN_VALUE)
{
AcpiUtRemoveReference (Info->ReturnObject);
Info->ReturnObject = NULL;
}
/* Map AE_CTRL_RETURN_VALUE to AE_OK, we are done with it */
Status = AE_OK;
}
else if (ACPI_FAILURE(Status))
{
/* If ReturnObject exists, delete it */
if (Info->ReturnObject)
{
AcpiUtRemoveReference (Info->ReturnObject);
Info->ReturnObject = NULL;
}
}
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES,
"*** Completed evaluation of object %s ***\n",
Info->RelativePathname));
Cleanup:
/*
* Namespace was unlocked by the handling AcpiNs* function, so we
* just free the pathname and return
*/
ACPI_FREE (Info->FullPathname);
Info->FullPathname = NULL;
return_ACPI_STATUS (Status);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,229 |
vino | 9c8b9f81205203db6c31068babbfb8a734acacdb | rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len)
{
rfbClientPtr cl;
rfbServerCutTextMsg sct;
rfbClientIteratorPtr iterator;
iterator = rfbGetClientIterator(rfbScreen);
while ((cl = rfbClientIteratorNext(iterator)) != NULL) {
sct.type = rfbServerCutText;
sct.length = Swap32IfLE(len);
if (WriteExact(cl, (char *)&sct,
sz_rfbServerCutTextMsg) < 0) {
rfbLogPerror("rfbSendServerCutText: write");
rfbCloseClient(cl);
continue;
}
if (WriteExact(cl, str, len) < 0) {
rfbLogPerror("rfbSendServerCutText: write");
rfbCloseClient(cl);
}
}
rfbReleaseClientIterator(iterator);
} | 1 | CVE-2012-4429 | 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. | 7,753 |
php-src | b4e4788c4461449b4587e19ef1f474ce938e4980 | static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel TSRMLS_DC)
{
size_t idex;
void *vptr;
image_info_value *info_value;
image_info_data *info_data;
image_info_data *list;
if (length < 0) {
return;
}
list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0);
image_info->info_list[section_index].list = list;
info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count];
memset(info_data, 0, sizeof(image_info_data));
info_data->tag = tag;
info_data->format = format;
info_data->length = length;
info_data->name = estrdup(name);
info_value = &info_data->value;
switch (format) {
case TAG_FMT_STRING:
if (value) {
length = php_strnlen(value, length);
info_value->s = estrndup(value, length);
info_data->length = length;
} else {
info_data->length = 0;
info_value->s = estrdup("");
}
break;
default:
/* Standard says more types possible but skip them...
* but allow users to handle data if they know how to
* So not return but use type UNDEFINED
* return;
*/
info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */
case TAG_FMT_SBYTE:
case TAG_FMT_BYTE:
/* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */
if (!length)
break;
case TAG_FMT_UNDEFINED:
if (value) {
if (tag == TAG_MAKER_NOTE) {
length = MIN(length, strlen(value));
}
/* do not recompute length here */
info_value->s = estrndup(value, length);
info_data->length = length;
} else {
info_data->length = 0;
info_value->s = estrdup("");
}
break;
case TAG_FMT_USHORT:
case TAG_FMT_ULONG:
case TAG_FMT_URATIONAL:
case TAG_FMT_SSHORT:
case TAG_FMT_SLONG:
case TAG_FMT_SRATIONAL:
case TAG_FMT_SINGLE:
case TAG_FMT_DOUBLE:
if (length==0) {
break;
} else
if (length>1) {
info_value->list = safe_emalloc(length, sizeof(image_info_value), 0);
} else {
info_value = &info_data->value;
}
for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) {
if (length>1) {
info_value = &info_data->value.list[idex];
}
switch (format) {
case TAG_FMT_USHORT:
info_value->u = php_ifd_get16u(vptr, motorola_intel);
break;
case TAG_FMT_ULONG:
info_value->u = php_ifd_get32u(vptr, motorola_intel);
break;
case TAG_FMT_URATIONAL:
info_value->ur.num = php_ifd_get32u(vptr, motorola_intel);
info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);
break;
case TAG_FMT_SSHORT:
info_value->i = php_ifd_get16s(vptr, motorola_intel);
break;
case TAG_FMT_SLONG:
info_value->i = php_ifd_get32s(vptr, motorola_intel);
break;
case TAG_FMT_SRATIONAL:
info_value->sr.num = php_ifd_get32u(vptr, motorola_intel);
info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);
break;
case TAG_FMT_SINGLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type single");
#endif
info_value->f = *(float *)value;
case TAG_FMT_DOUBLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type double");
#endif
info_value->d = *(double *)value;
break;
}
}
}
image_info->sections_found |= 1<<section_index;
image_info->info_list[section_index].count++;
} | 1 | CVE-2018-10549 | 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,583 |
linux | c2349758acf1874e4c2b93fe41d072336f1a31d0 | void rds_ib_exit(void)
{
rds_info_deregister_func(RDS_INFO_IB_CONNECTIONS, rds_ib_ic_info);
rds_ib_unregister_client();
rds_ib_destroy_nodev_conns();
rds_ib_sysctl_exit();
rds_ib_recv_exit();
rds_trans_unregister(&rds_ib_transport);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,941 |
linux | b3baa0fbd02a1a9d493d8cb92ae4a4491b9e9d13 | void __skb_get_hash(struct sk_buff *skb)
{
struct flow_keys keys;
u32 hash;
__flow_hash_secret_init();
hash = ___skb_get_hash(skb, &keys, hashrnd);
if (!hash)
return;
if (keys.ports.ports)
skb->l4_hash = 1;
skb->sw_hash = 1;
skb->hash = hash;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,162 |
linux | 54d83fc74aa9ec72794373cb47432c5f7fb1a309 | static inline bool unconditional(const struct ip6t_ip6 *ipv6)
{
static const struct ip6t_ip6 uncond;
return memcmp(ipv6, &uncond, sizeof(uncond)) == 0;
}
| 1 | CVE-2016-3134 | 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,075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.