code
stringlengths
12
2.05k
label
int64
0
1
programming_language
stringclasses
9 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
103
description
stringlengths
36
1.23k
url
stringlengths
36
48
label_name
stringclasses
2 values
inline void StringData::setSize(int len) { assertx(!isImmutable() && !hasMultipleRefs()); assertx(len >= 0 && len <= capacity()); mutableData()[len] = 0; m_lenAndHash = len; assertx(m_hash == 0); assertx(checkSane()); }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
void RemoteFsDevice::serviceRemoved(const QString &name) { if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) { sub=tr("Not Available"); updateStatus(); } }
0
C++
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
TfLiteStatus NonMaxSuppressionMultiClass(TfLiteContext* context, TfLiteNode* node, OpData* op_data) { // Get the input tensors const TfLiteTensor* input_box_encodings = GetInput(context, node, kInputTensorBoxEncodings); const TfLiteTensor* input_class_predictions = GetInput(context, node, kInputTensorClassPredictions); const int num_boxes = input_box_encodings->dims->data[1]; const int num_classes = op_data->num_classes; TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[0], kBatchSize); TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[1], num_boxes); const int num_classes_with_background = input_class_predictions->dims->data[2]; TF_LITE_ENSURE(context, (num_classes_with_background - num_classes <= 1)); TF_LITE_ENSURE(context, (num_classes_with_background >= num_classes)); const TfLiteTensor* scores; switch (input_class_predictions->type) { case kTfLiteUInt8: { TfLiteTensor* temporary_scores = &context->tensors[op_data->scores_index]; DequantizeClassPredictions(input_class_predictions, num_boxes, num_classes_with_background, temporary_scores); scores = temporary_scores; } break; case kTfLiteFloat32: scores = input_class_predictions; break; default: // Unsupported type. return kTfLiteError; } if (op_data->use_regular_non_max_suppression) TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassRegularHelper( context, node, op_data, GetTensorData<float>(scores))); else TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassFastHelper( context, node, op_data, GetTensorData<float>(scores))); return kTfLiteOk; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = input->dims->data[0]; output_size->data[1] = input->dims->data[1]; output_size->data[2] = input->dims->data[2]; output_size->data[3] = input->dims->data[3]; return context->ResizeTensor(context, output, output_size); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
void pb_controller::play_file(const std::string& file) { std::string cmdline; std::string player = cfg->get_configvalue("player"); if (player == "") return; cmdline.append(player); cmdline.append(" '"); cmdline.append(utils::replace_all(file,"'", "%27")); cmdline.append("'"); stfl::reset(); utils::run_interactively(cmdline, "pb_controller::play_file"); }
1
C++
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); if (!is_supported_type(input->type)) { TF_LITE_UNSUPPORTED_TYPE(context, input->type, op_name); } return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
bool AdminRequestHandler::handleDumpStaticStringsRequest(folly::File& file) { auto const& list = lookupDefinedStaticStrings(); for (auto item : list) { auto const line = formatStaticString(item); folly::writeFull(file.fd(), line.data(), line.size()); if (RuntimeOption::EvalPerfDataMap) { auto const len = std::min<size_t>(item->size(), 255); std::string str(item->data(), len); // Only print the first line (up to 255 characters). Since we want '\0' in // the list of characters to avoid, we need to use the version of // `find_first_of()' with explicit length. auto cutOffPos = str.find_first_of("\r\n", 0, 3); if (cutOffPos != std::string::npos) str.erase(cutOffPos); Debug::DebugInfo::recordDataMap(item->mutableData(), item->mutableData() + item->size(), "Str-" + str); } } return true; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
TfLiteStatus EluPrepare(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); OpData* data = reinterpret_cast<OpData*>(node->user_data); // Use LUT to handle quantized elu path. if (input->type == kTfLiteInt8) { PopulateLookupTable<int8_t>(data, input, output, [](float value) { return value < 0.0 ? std::exp(value) - 1.0f : value; }); } return GenericPrepare(context, node); }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
void jas_matrix_asl(jas_matrix_t *matrix, int n) { jas_matind_t i; jas_matind_t j; jas_seqent_t *rowstart; jas_matind_t rowstep; jas_seqent_t *data; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { //*data <<= n; *data = jas_seqent_asl(*data, n); } } } }
1
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
static optional<Principal> parse_principal(CephContext* cct, TokenID t, string&& s) { // Wildcard! if ((t == TokenID::AWS) && (s == "*")) { return Principal::wildcard(); // Do nothing for now. } else if (t == TokenID::CanonicalUser) { // AWS ARNs } else if (t == TokenID::AWS) { auto a = ARN::parse(s); if (!a) { if (std::none_of(s.begin(), s.end(), [](const char& c) { return (c == ':') || (c == '/'); })) { // Since tenants are simply prefixes, there's no really good // way to see if one exists or not. So we return the thing and // let them try to match against it. return Principal::tenant(std::move(s)); } } if (a->resource == "root") { return Principal::tenant(std::move(a->account)); } static const char rx_str[] = "([^/]*)/(.*)"; static const regex rx(rx_str, sizeof(rx_str) - 1, ECMAScript | optimize); smatch match; if (regex_match(a->resource, match, rx)) { ceph_assert(match.size() == 3); if (match[1] == "user") { return Principal::user(std::move(a->account), match[2]); } if (match[1] == "role") { return Principal::role(std::move(a->account), match[2]); } } } ldout(cct, 0) << "Supplied principal is discarded: " << s << dendl; return boost::none; }
0
C++
CWE-617
Reachable Assertion
The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.
https://cwe.mitre.org/data/definitions/617.html
vulnerable
TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: MaxEvalFloat<kernel_type>(context, node, params, data, input, output); break; case kTfLiteUInt8: MaxEvalQuantizedUInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt8: MaxEvalQuantizedInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt16: MaxEvalQuantizedInt16<kernel_type>(context, node, params, data, input, output); break; default: TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray { return channelEncode(target, message); }; #ifdef HAVE_QCA2 putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc, network()->cipher(bufferInfo.bufferName())); #else putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc); #endif emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); }
1
C++
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
https://cwe.mitre.org/data/definitions/399.html
safe
bool WideToCharMap(const wchar *Src,char *Dest,size_t DestSize,bool &Success) { // String with inconvertible characters mapped to private use Unicode area // must have the mark code somewhere. if (wcschr(Src,(wchar)MappedStringMark)==NULL) return false; Success=true; uint SrcPos=0,DestPos=0; while (Src[SrcPos]!=0 && DestPos<DestSize-MB_CUR_MAX) { if (uint(Src[SrcPos])==MappedStringMark) { SrcPos++; continue; } // For security reasons do not restore low ASCII codes, so mapping cannot // be used to hide control codes like path separators. if (uint(Src[SrcPos])>=MapAreaStart+0x80 && uint(Src[SrcPos])<MapAreaStart+0x100) Dest[DestPos++]=char(uint(Src[SrcPos++])-MapAreaStart); else { mbstate_t ps; memset(&ps,0,sizeof(ps)); if (wcrtomb(Dest+DestPos,Src[SrcPos],&ps)==-1) { Dest[DestPos]='_'; Success=false; } SrcPos++; memset(&ps,0,sizeof(ps)); int Length=mbrlen(Dest+DestPos,MB_CUR_MAX,&ps); DestPos+=Max(Length,1); } } Dest[Min(DestPos,DestSize-1)]=0; return true; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
void writeStats(Array& /*ret*/) override { fprintf(stderr, "writeStats start\n"); // RetSame: the return value is the same instance every time // HasThis: call has a this argument // AllSame: all returns were the same data even though args are different // MemberCount: number of different arg sets (including this) fprintf(stderr, "Count Function MinSerLen MaxSerLen RetSame HasThis " "AllSame MemberCount\n"); for (auto& me : m_memos) { if (me.second.m_ignore) continue; if (me.second.m_count == 1) continue; int min_ser_len = 999999999; int max_ser_len = 0; int count = 0; int member_count = 0; bool all_same = true; if (me.second.m_has_this) { bool any_multiple = false; auto& fr = me.second.m_member_memos.begin()->second.m_return_value; member_count = me.second.m_member_memos.size(); for (auto& mme : me.second.m_member_memos) { if (mme.second.m_return_value != fr) all_same = false; count += mme.second.m_count; auto ser_len = mme.second.m_return_value.length(); min_ser_len = std::min(min_ser_len, ser_len); max_ser_len = std::max(max_ser_len, ser_len); if (mme.second.m_count > 1) any_multiple = true; } if (!any_multiple && !all_same) continue; } else { min_ser_len = max_ser_len = me.second.m_return_value.length(); count = me.second.m_count; all_same = me.second.m_ret_tv_same; } fprintf(stderr, "%d %s %d %d %s %s %s %d\n", count, me.first.data(), min_ser_len, max_ser_len, me.second.m_ret_tv_same ? " true" : "false", me.second.m_has_this ? " true" : "false", all_same ? " true" : "false", member_count ); } fprintf(stderr, "writeStats end\n"); }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
static INLINE SIZE_T ntlm_av_pair_get_len(const NTLM_AV_PAIR* pAvPair) { UINT16 AvLen; Data_Read_UINT16(&pAvPair->AvLen, AvLen); return AvLen; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const TfLiteTensor* seq_lengths; TF_LITE_ENSURE_OK( context, GetInputSafe(context, node, kSeqLengthsTensor, &seq_lengths)); TF_LITE_ENSURE_EQ(context, NumDimensions(seq_lengths), 1); if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 && input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 && input->type != kTfLiteInt64) { context->ReportError(context, "Type '%s' is not supported by reverse_sequence.", TfLiteTypeGetName(input->type)); return kTfLiteError; } if (seq_lengths->type != kTfLiteInt32 && seq_lengths->type != kTfLiteInt64) { context->ReportError( context, "Seq_lengths type '%s' is not supported by reverse_sequence.", TfLiteTypeGetName(seq_lengths->type)); return kTfLiteError; } TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims); TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type); return context->ResizeTensor(context, output, output_shape); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
req::ptr<XMLDocumentData> doc() const { return m_node ? m_node->doc() : nullptr; }
1
C++
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
bool ConstantFolding::SimplifyReshape(const GraphProperties& properties, bool use_shape_info, NodeDef* node) { if (!use_shape_info || node->attr().count("T") == 0 || !IsSimplifiableReshape(*node, properties).ok()) { return false; } DataType output_type = node->attr().at("T").type(); node->set_op("Identity"); EraseRegularNodeAttributes(node); (*node->mutable_attr())["T"].set_type(output_type); *node->mutable_input(1) = AsControlDependency(node->input(1)); return true; }
1
C++
CWE-617
Reachable Assertion
The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.
https://cwe.mitre.org/data/definitions/617.html
safe
mptctl_replace_fw (unsigned long arg) { struct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg; struct mpt_ioctl_replace_fw karg; MPT_ADAPTER *ioc; int iocnum; int newFwSize; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_replace_fw - " "Unable to read in mpt_ioctl_replace_fw struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_replace_fw() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_replace_fw called.\n", ioc->name)); /* If caching FW, Free the old FW image */ if (ioc->cached_fw == NULL) return 0; mpt_free_fw_memory(ioc); /* Allocate memory for the new FW image */ newFwSize = ALIGN(karg.newImageSize, 4); mpt_alloc_fw_memory(ioc, newFwSize); if (ioc->cached_fw == NULL) return -ENOMEM; /* Copy the data from user memory to kernel space */ if (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_replace_fw - " "Unable to read in mpt_ioctl_replace_fw image " "@ %p\n", ioc->name, __FILE__, __LINE__, uarg); mpt_free_fw_memory(ioc); return -EFAULT; } /* Update IOCFactsReply */ ioc->facts.FWImageSize = newFwSize; return 0; }
0
C++
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
vulnerable
TightDecoder::FilterGradient24(const rdr::U8 *inbuf, const PixelFormat& pf, PIXEL_T* outbuf, int stride, const Rect& r) { int x, y, c; rdr::U8 prevRow[TIGHT_MAX_WIDTH*3]; rdr::U8 thisRow[TIGHT_MAX_WIDTH*3]; rdr::U8 pix[3]; int est[3]; memset(prevRow, 0, sizeof(prevRow)); // Set up shortcut variables int rectHeight = r.height(); int rectWidth = r.width(); for (y = 0; y < rectHeight; y++) { /* First pixel in a row */ for (c = 0; c < 3; c++) { pix[c] = inbuf[y*rectWidth*3+c] + prevRow[c]; thisRow[c] = pix[c]; } pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride], pix, 1); /* Remaining pixels of a row */ for (x = 1; x < rectWidth; x++) { for (c = 0; c < 3; c++) { est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c]; if (est[c] > 0xff) { est[c] = 0xff; } else if (est[c] < 0) { est[c] = 0; } pix[c] = inbuf[(y*rectWidth+x)*3+c] + est[c]; thisRow[x*3+c] = pix[c]; } pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride+x], pix, 1); } memcpy(prevRow, thisRow, sizeof(prevRow)); } }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
TfLiteStatus GreaterEval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); bool requires_broadcast = !HaveSameShapes(input1, input2); switch (input1->type) { case kTfLiteFloat32: Comparison<float, reference_ops::GreaterFn>(input1, input2, output, requires_broadcast); break; case kTfLiteInt32: Comparison<int32_t, reference_ops::GreaterFn>(input1, input2, output, requires_broadcast); break; case kTfLiteInt64: Comparison<int64_t, reference_ops::GreaterFn>(input1, input2, output, requires_broadcast); break; case kTfLiteUInt8: ComparisonQuantized<uint8_t, reference_ops::GreaterFn>( input1, input2, output, requires_broadcast); break; case kTfLiteInt8: ComparisonQuantized<int8_t, reference_ops::GreaterFn>( input1, input2, output, requires_broadcast); break; default: context->ReportError(context, "Does not support type %d, requires float|int|uint8", input1->type); return kTfLiteError; } return kTfLiteOk; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
void Compute(OpKernelContext* context) override { const Tensor& prefix = context->input(0); const Tensor& tensor_names = context->input(1); const Tensor& shape_and_slices = context->input(2); OP_REQUIRES(context, tensor_names.NumElements() == dtypes_.size(), errors::InvalidArgument("Got ", tensor_names.NumElements(), " tensor names, but ", dtypes_.size(), " expected dtypes.")); ValidateInputs(false /* not save op */, context, prefix, tensor_names, shape_and_slices); if (!context->status().ok()) return; const string& prefix_string = prefix.scalar<tstring>()(); // Intention: we plan to use the RestoreV2 op as a backward-compatible // reader as we upgrade to the V2 format. This allows transparent upgrade. // We here attempt to read a V1 checkpoint, if "prefix_string" does not // refer to a V2 checkpoint. Env* env = Env::Default(); std::vector<string> paths; if (!env->GetMatchingPaths(MetaFilename(prefix_string), &paths).ok() || paths.empty()) { // Cannot find V2's metadata file, so "prefix_string" does not point to a // V2 checkpoint. Invokes the V1 read path instead. for (size_t i = 0; i < tensor_names.NumElements(); ++i) { RestoreTensor(context, &checkpoint::OpenTableTensorSliceReader, /* preferred_shard */ -1, /* restore_slice */ true, /* restore_index */ i); if (!context->status().ok()) { return; } } return; } // If found, invokes the V2 reader. OP_REQUIRES_OK(context, RestoreTensorsV2(context, prefix, tensor_names, shape_and_slices, dtypes_)); }
1
C++
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
safe
TypedValue HHVM_FUNCTION(substr_compare, const String& main_str, const String& str, int offset, int length /* = INT_MAX */, bool case_insensitivity /* = false */) { int s1_len = main_str.size(); int s2_len = str.size(); if (length <= 0) { raise_warning("The length must be greater than zero"); return make_tv<KindOfBoolean>(false); } if (offset < 0) { offset = s1_len + offset; if (offset < 0) offset = 0; } if (offset >= s1_len) { raise_warning("The start position cannot exceed initial string length"); return make_tv<KindOfBoolean>(false); } int cmp_len = s1_len - offset; if (cmp_len < s2_len) cmp_len = s2_len; if (cmp_len > length) cmp_len = length; const char *s1 = main_str.data(); if (case_insensitivity) { return tvReturn(bstrcasecmp(s1 + offset, cmp_len, str.data(), cmp_len)); } return tvReturn(string_ncmp(s1 + offset, str.data(), cmp_len)); }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
Status TensorSliceReader::GetTensor( const string& name, std::unique_ptr<tensorflow::Tensor>* out_tensor) const { DataType type; TensorShape shape; TensorSlice slice; { mutex_lock l(mu_); const TensorSliceSet* tss = gtl::FindPtrOrNull(tensors_, name); if (tss == nullptr) { return errors::NotFound(name, " not found in checkpoint file"); } if (tss->Slices().size() > 1) { // TODO(sherrym): Support multi-slice checkpoints. return errors::Unimplemented("Sliced checkpoints are not supported"); } type = tss->type(); shape = tss->shape(); slice = tss->Slices().begin()->second.slice; } std::unique_ptr<tensorflow::Tensor> t(new tensorflow::Tensor(type, shape)); bool success = false; #define READER_COPY(dt) \ case dt: \ success = CopySliceData(name, slice, \ t->flat<EnumToDataType<dt>::Type>().data()); \ break; switch (type) { READER_COPY(DT_FLOAT); READER_COPY(DT_DOUBLE); READER_COPY(DT_INT32); READER_COPY(DT_UINT8); READER_COPY(DT_INT16); READER_COPY(DT_INT8); READER_COPY(DT_INT64); READER_COPY(DT_STRING); default: return errors::Unimplemented("Data type not supported"); } #undef READER_COPY if (!success) { return errors::NotFound(name, " not found in checkpoint file"); } std::swap(*out_tensor, t); return Status::OK(); }
0
C++
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
vulnerable
void writeStats(Array& /*ret*/) override { fprintf(stderr, "writeStats start\n"); // RetSame: the return value is the same instance every time // HasThis: call has a this argument // AllSame: all returns were the same data even though args are different // MemberCount: number of different arg sets (including this) fprintf(stderr, "Count Function MinSerLen MaxSerLen RetSame HasThis " "AllSame MemberCount\n"); for (auto& me : m_memos) { if (me.second.m_ignore) continue; if (me.second.m_count == 1) continue; int min_ser_len = 999999999; int max_ser_len = 0; int count = 0; int member_count = 0; bool all_same = true; if (me.second.m_has_this) { bool any_multiple = false; auto& fr = me.second.m_member_memos.begin()->second.m_return_value; member_count = me.second.m_member_memos.size(); for (auto& mme : me.second.m_member_memos) { if (mme.second.m_return_value != fr) all_same = false; count += mme.second.m_count; auto ser_len = mme.second.m_return_value.length(); min_ser_len = std::min<int64_t>(min_ser_len, ser_len); max_ser_len = std::max<int64_t>(max_ser_len, ser_len); if (mme.second.m_count > 1) any_multiple = true; } if (!any_multiple && !all_same) continue; } else { min_ser_len = max_ser_len = me.second.m_return_value.length(); count = me.second.m_count; all_same = me.second.m_ret_tv_same; } fprintf(stderr, "%d %s %d %d %s %s %s %d\n", count, me.first.data(), min_ser_len, max_ser_len, me.second.m_ret_tv_same ? " true" : "false", me.second.m_has_this ? " true" : "false", all_same ? " true" : "false", member_count ); } fprintf(stderr, "writeStats end\n"); }
1
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
inline int check(int itemSize, int nItems=1) { if (ptr + itemSize * nItems > end) { if (ptr + itemSize > end) return overrun(itemSize, nItems); nItems = (end - ptr) / itemSize; } return nItems; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
Http::Response AbstractWebApplication::processRequest(const Http::Request &request, const Http::Environment &env) { session_ = 0; request_ = request; env_ = env; clear(); // clear response sessionInitialize(); if (!sessionActive() && !isAuthNeeded()) sessionStart(); if (isBanned()) { status(403, "Forbidden"); print(QObject::tr("Your IP address has been banned after too many failed authentication attempts."), Http::CONTENT_TYPE_TXT); } else { processRequest(); } return response(); }
0
C++
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.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
gdImagePtr gdImageCreateTrueColor (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof(unsigned char *), sy)) { return NULL; } if (overflow2(sizeof(int) + sizeof(unsigned char), sx * sy)) { return NULL; } // Check for OOM before doing a potentially large allocation. auto allocsz = sizeof(gdImage) + (sizeof(int *) + sizeof(unsigned char *)) * sy + (sizeof(int) + sizeof(unsigned char)) * sx * sy; if (UNLIKELY(precheckOOM(allocsz))) { // Don't throw here because GD might need to do its own cleanup. return NULL; } im = (gdImage *) gdMalloc(sizeof(gdImage)); memset(im, 0, sizeof(gdImage)); im->tpixels = (int **) gdMalloc(sizeof(int *) * sy); im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy); im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; i < sy; i++) { im->tpixels[i] = (int *) gdCalloc(sx, sizeof(int)); im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char)); } im->sx = sx; im->sy = sy; im->transparent = (-1); im->interlace = 0; im->trueColor = 1; /* 2.0.2: alpha blending is now on by default, and saving of alpha is * off by default. This allows font antialiasing to work as expected * on the first try in JPEGs -- quite important -- and also allows * for smaller PNGs when saving of alpha channel is not really * desired, which it usually isn't! */ im->saveAlphaFlag = 0; im->alphaBlendingFlag = 1; im->thick = 1; im->AA = 0; im->AA_polygon = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; }
1
C++
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TfLiteTensor* hits; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 1, &hits)); const TfLiteTensor* lookup; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &lookup)); const TfLiteTensor* key; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &key)); const TfLiteTensor* value; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &value)); const int num_rows = SizeOfDimension(value, 0); const int row_bytes = value->bytes / num_rows; void* pointer = nullptr; DynamicBuffer buf; for (int i = 0; i < SizeOfDimension(lookup, 0); i++) { int idx = -1; pointer = bsearch(&(lookup->data.i32[i]), key->data.i32, num_rows, sizeof(int32_t), greater); if (pointer != nullptr) { idx = (reinterpret_cast<char*>(pointer) - (key->data.raw)) / sizeof(int32_t); } if (idx >= num_rows || idx < 0) { if (output->type == kTfLiteString) { buf.AddString(nullptr, 0); } else { memset(output->data.raw + i * row_bytes, 0, row_bytes); } hits->data.uint8[i] = 0; } else { if (output->type == kTfLiteString) { buf.AddString(GetString(value, idx)); } else { memcpy(output->data.raw + i * row_bytes, value->data.raw + idx * row_bytes, row_bytes); } hits->data.uint8[i] = 1; } } if (output->type == kTfLiteString) { buf.WriteToTensorAsVector(output); } return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
bool IsOpened() {return hFile!=FILE_BAD_HANDLE;};
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
QPDF::resolve(int objid, int generation) { // Check object cache before checking xref table. This allows us // to insert things into the object cache that don't actually // exist in the file. QPDFObjGen og(objid, generation); if (this->resolving.count(og)) { // This can happen if an object references itself directly or // indirectly in some key that has to be resolved during // object parsing, such as stream length. QTC::TC("qpdf", "QPDF recursion loop in resolve"); warn(QPDFExc(qpdf_e_damaged_pdf, this->file->getName(), "", this->file->getLastOffset(), "loop detected resolving object " + QUtil::int_to_string(objid) + " " + QUtil::int_to_string(generation))); return new QPDF_Null; } ResolveRecorder rr(this, og); if (! this->obj_cache.count(og)) { if (! this->xref_table.count(og)) { // PDF spec says unknown objects resolve to the null object. return new QPDF_Null; } QPDFXRefEntry const& entry = this->xref_table[og]; switch (entry.getType()) { case 1: { qpdf_offset_t offset = entry.getOffset(); // Object stored in cache by readObjectAtOffset int aobjid; int ageneration; QPDFObjectHandle oh = readObjectAtOffset(true, offset, "", objid, generation, aobjid, ageneration); } break; case 2: resolveObjectsInStream(entry.getObjStreamNumber()); break; default: throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(), "", 0, "object " + QUtil::int_to_string(objid) + "/" + QUtil::int_to_string(generation) + " has unexpected xref entry type"); } } return this->obj_cache[og].object; }
1
C++
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
https://cwe.mitre.org/data/definitions/399.html
safe
Jsi_Value *jsi_ValueObjKeyAssign(Jsi_Interp *interp, Jsi_Value *target, Jsi_Value *keyval, Jsi_Value *value, int flag) { int arrayindex = -1; if (keyval->vt == JSI_VT_NUMBER && Jsi_NumberIsInteger(keyval->d.num) && keyval->d.num >= 0) { arrayindex = (int)keyval->d.num; } /* TODO: array["1"] also extern the length of array */ if (arrayindex >= 0 && arrayindex < MAX_ARRAY_LIST && target->vt == JSI_VT_OBJECT && target->d.obj->arr) { return jsi_ObjArraySetDup(interp, target->d.obj, value, arrayindex); } const char *kstr = Jsi_ValueToString(interp, keyval, NULL); #if (defined(JSI_HAS___PROTO__) && JSI_HAS___PROTO__==2) if (Jsi_Strcmp(kstr, "__proto__")==0) { Jsi_Obj *obj = target->d.obj; obj->__proto__ = Jsi_ValueDup(interp, value); //obj->clearProto = 1; return obj->__proto__; } #endif Jsi_Value *v = Jsi_ValueNew1(interp); if (value) Jsi_ValueCopy(interp, v, value); jsi_ValueObjSet(interp, target, kstr, v, flag, (Jsi_ValueIsStringKey(interp, keyval)? JSI_OM_ISSTRKEY:0)); Jsi_DecrRefCount(interp, v); return v; }
0
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) { ut32 i = 0; RBinJavaAnnotation *annotation = NULL; RBinJavaElementValuePair *evps = NULL; ut64 offset = 0; annotation = R_NEW0 (RBinJavaAnnotation); if (!annotation) { return NULL; } // (ut16) read and set annotation_value.type_idx; annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; // (ut16) read and set annotation_value.num_element_value_pairs; annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; annotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free); // read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs for (i = 0; i < annotation->num_element_value_pairs; i++) { if (offset > sz) { break; } evps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset); if (evps) { offset += evps->size; r_list_append (annotation->element_value_pairs, (void *) evps); } } annotation->size = offset; return annotation; }
0
C++
CWE-788
Access of Memory Location After End of Buffer
The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer.
https://cwe.mitre.org/data/definitions/788.html
vulnerable
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteLocalResponseNormParams*>(node->builtin_data); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); if (output->type == kTfLiteFloat32) { #define TF_LITE_LOCAL_RESPONSE_NORM(type) \ tflite::LocalResponseNormalizationParams op_params; \ op_params.range = params->radius; \ op_params.bias = params->bias; \ op_params.alpha = params->alpha; \ op_params.beta = params->beta; \ type::LocalResponseNormalization( \ op_params, GetTensorShape(input), GetTensorData<float>(input), \ GetTensorShape(output), GetTensorData<float>(output)) if (kernel_type == kReference) { TF_LITE_LOCAL_RESPONSE_NORM(reference_ops); } if (kernel_type == kGenericOptimized) { TF_LITE_LOCAL_RESPONSE_NORM(optimized_ops); } #undef TF_LITE_LOCAL_RESPONSE_NORM } else { context->ReportError(context, "Output type is %d, requires float.", output->type); return kTfLiteError; } return kTfLiteOk; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); // There are two ways in which the 'output' can be made dynamic: it could be // a string tensor, or its shape cannot be calculated during Prepare(). In // either case, we now have all the information to calculate its shape. if (IsDynamicTensor(output)) { TF_LITE_ENSURE_OK(context, ResizeOutput(context, node)); } // Note that string tensors are always "dynamic" in the sense that their size // is not known until we have all the content. This applies even when their // shape is known ahead of time. As a result, a string tensor is never given // any memory by ResizeOutput(), and we need to do it manually here. Since // reshape doesn't change the data, the output tensor needs exactly as many // bytes as the input tensor. if (output->type == kTfLiteString) { auto bytes_required = input->bytes; TfLiteTensorRealloc(bytes_required, output); output->bytes = bytes_required; } memcpy(output->data.raw, input->data.raw, input->bytes); return kTfLiteOk; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
void Bezier(double x1,double y1,double x2,double y2,double x3,double y3) { sprintf(outputbuffer,"\n %12.3f %12.3f %12.3f %12.3f %12.3f %12.3f c",x1,y1,x2,y2,x3,y3); sendClean(outputbuffer); }
1
C++
NVD-CWE-noinfo
null
null
null
safe
bool read(ReadonlyBytes buffer) { auto fields_size = sizeof(EndOfCentralDirectory) - sizeof(u8*); if (buffer.size() < fields_size) return false; if (memcmp(buffer.data(), end_of_central_directory_signature, sizeof(end_of_central_directory_signature)) != 0) return false; memcpy(reinterpret_cast<void*>(&disk_number), buffer.data() + sizeof(end_of_central_directory_signature), fields_size); comment = buffer.data() + sizeof(end_of_central_directory_signature) + fields_size; return true; }
0
C++
CWE-120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.
https://cwe.mitre.org/data/definitions/120.html
vulnerable
TfLiteStatus PrepareMeanOrSum(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_OK(context, PrepareSimple(context, node)); OpData* data = reinterpret_cast<OpData*>(node->user_data); // reduce_mean requires a buffer to store intermediate sum result. OpContext op_context(context, node); if (op_context.input->type == kTfLiteInt8 || op_context.input->type == kTfLiteUInt8 || op_context.input->type == kTfLiteInt16) { const double real_multiplier = static_cast<double>(op_context.input->params.scale) / static_cast<double>(op_context.output->params.scale); int exponent; QuantizeMultiplier(real_multiplier, &data->multiplier, &exponent); data->shift = exponent; } TfLiteTensor* temp_sum; TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/2, &temp_sum)); if (!IsConstantTensor(op_context.axis)) { SetTensorToDynamic(temp_sum); return kTfLiteOk; } temp_sum->allocation_type = kTfLiteArenaRw; return ResizeTempSum(context, &op_context, temp_sum); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
Jsi_RC Jsi_ValueInsertArray(Jsi_Interp *interp, Jsi_Value *target, int key, Jsi_Value *val, int flags) { if (target->vt != JSI_VT_OBJECT) { if (interp->strict) Jsi_LogWarn("Target is not object"); return JSI_ERROR; } Jsi_Obj *obj = target->d.obj; if (obj->isarrlist) { if (key >= 0 && key < interp->maxArrayList) { Jsi_ObjArraySet(interp, obj, val, key); return JSI_OK; } return JSI_ERROR; } char unibuf[JSI_MAX_NUMBER_STRING]; Jsi_NumberItoA10(key, unibuf, sizeof(unibuf)); Jsi_ObjInsert(interp, obj, unibuf, val, flags); return JSI_OK; }
0
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") { int errStatus = 0; vector<char> errMsg(BUF_LEN, 0); uint32_t encLen; string key = SAMPLE_AES_KEY; vector <uint8_t> encrypted_key(BUF_LEN, 0); PRINT_SRC_LINE auto status = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &encLen); REQUIRE(status == 0); REQUIRE(errStatus == 0); vector<char> decr_key(BUF_LEN, 0); PRINT_SRC_LINE status = trustedDecryptKeyAES(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data()); REQUIRE(status == 0); REQUIRE(errStatus == 0); REQUIRE(key.compare(decr_key.data()) == 0); }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
explicit ThreadPoolHandleOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("display_name", &display_name_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("num_threads", &num_threads_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("max_intra_op_parallelism", &max_intra_op_parallelism_)); OP_REQUIRES( ctx, num_threads_ > 0, errors::InvalidArgument("`num_threads` must be greater than zero.")); }
0
C++
CWE-770
Allocation of Resources Without Limits or Throttling
The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TF_LITE_ENSURE_TYPES_EQ(context, GetInput(context, node, 0)->type, kTfLiteString); TF_LITE_ENSURE_TYPES_EQ(context, GetOutput(context, node, 0)->type, kTfLiteString); return kTfLiteOk; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
TfLiteStatus L2Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: L2EvalFloat<kernel_type>(context, node, params, data, input, output); break; case kTfLiteUInt8: // We don't have a quantized implementation, so just fall through to the // 'default' case. default: context->ReportError(context, "Type %d not currently supported.", input->type); return kTfLiteError; } return kTfLiteOk; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
static const EVP_MD *tpm_algorithm_to_openssl_digest(TPMI_ALG_HASH algorithm) { switch(algorithm) { case TPM_ALG_SHA1: return EVP_sha1(); case ALG_SHA256_VALUE: return EVP_sha256(); case TPM_ALG_SHA384: return EVP_sha384(); case TPM_ALG_SHA512: return EVP_sha512(); default: return NULL; } /* no return, not possible */ }
1
C++
CWE-522
Insufficiently Protected Credentials
The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval.
https://cwe.mitre.org/data/definitions/522.html
safe
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y&255]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y&255]); } } }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); output->type = input->type; return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const Tensor& filter = context->input(1); const Tensor& out_backprop = context->input(2); // Determine relevant sizes from input and filters. int stride_rows = 0, stride_cols = 0; int rate_rows = 0, rate_cols = 0; int64 pad_top = 0, pad_left = 0; int64 out_rows = 0, out_cols = 0; ParseSizes(context, strides_, rates_, padding_, &stride_rows, &stride_cols, &rate_rows, &rate_cols, &pad_top, &pad_left, &out_rows, &out_cols); if (!context->status().ok()) return; // Verify that the incoming gradient tensor has the expected size // [ batch, out_rows, out_cols, depth ] const int batch = input.dim_size(0); const int depth = input.dim_size(3); OP_REQUIRES(context, batch == out_backprop.dim_size(0) && out_rows == out_backprop.dim_size(1) && out_cols == out_backprop.dim_size(2) && depth == out_backprop.dim_size(3), errors::InvalidArgument("out_backprop has incompatible size.")); // The computed filter_backprop has the same dimensions as the filter: // [ batch, input_rows, input_cols, depth ] Tensor* filter_backprop = nullptr; OP_REQUIRES_OK( context, context->allocate_output(0, filter.shape(), &filter_backprop)); // If there is nothing to compute, return. if (filter.shape().num_elements() == 0) { return; } functor::DilationBackpropFilter<Device, T>()( context->eigen_device<Device>(), input.tensor<T, 4>(), filter.tensor<T, 3>(), out_backprop.tensor<T, 4>(), stride_rows, stride_cols, rate_rows, rate_cols, pad_top, pad_left, filter_backprop->tensor<T, 3>()); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
void operator = (const IniSection &s) { if (&s == this) { return; } IniBase::operator = (s); ip = s.ip; end_comment = s.end_comment; rewrite_by = s.rewrite_by; container = s.container; reindex (); }
0
C++
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.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
FdInStream::FdInStream(int fd_, int timeoutms_, int bufSize_, bool closeWhenDone_) : fd(fd_), closeWhenDone(closeWhenDone_), timeoutms(timeoutms_), blockCallback(0), timing(false), timeWaitedIn100us(5), timedKbits(0), bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0) { ptr = end = start = new U8[bufSize]; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
TfLiteStatus SimpleStatefulOp::Invoke(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast<OpData*>(node->user_data); *data->invoke_count += 1; const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const uint8_t* input_data = GetTensorData<uint8_t>(input); int size = NumElements(input->dims); uint8_t* sorting_buffer = reinterpret_cast<uint8_t*>( context->GetScratchBuffer(context, data->sorting_buffer)); // Copy inputs data to the sorting buffer. We don't want to mutate the input // tensor as it might be used by a another node. for (int i = 0; i < size; i++) { sorting_buffer[i] = input_data[i]; } // In place insertion sort on `sorting_buffer`. for (int i = 1; i < size; i++) { for (int j = i; j > 0 && sorting_buffer[j] < sorting_buffer[j - 1]; j--) { std::swap(sorting_buffer[j], sorting_buffer[j - 1]); } } TfLiteTensor* median; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kMedianTensor, &median)); uint8_t* median_data = GetTensorData<uint8_t>(median); TfLiteTensor* invoke_count; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kInvokeCount, &invoke_count)); int32_t* invoke_count_data = GetTensorData<int32_t>(invoke_count); median_data[0] = sorting_buffer[size / 2]; invoke_count_data[0] = *data->invoke_count; return kTfLiteOk; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
bool canContinue() override { return true; }
0
C++
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
vulnerable
void Compute(OpKernelContext* context) override { auto min_input_tensor = context->input(1); auto max_input_tensor = context->input(2); OP_REQUIRES( context, min_input_tensor.NumElements() == 1, errors::InvalidArgument( "min_input must be a scalar float value, got tensor with shape ", min_input_tensor.shape())); OP_REQUIRES( context, max_input_tensor.NumElements() == 1, errors::InvalidArgument( "max_input must be a scalar float value, got tensor with shape ", max_input_tensor.shape())); const float min_input = context->input(1).flat<float>()(0); const float max_input = context->input(2).flat<float>()(0); MaxPoolingOp<Device, T>::Compute(context); Tensor* output_min = nullptr; OP_REQUIRES_OK(context, context->allocate_output(1, {}, &output_min)); output_min->flat<float>()(0) = min_input; Tensor* output_max = nullptr; OP_REQUIRES_OK(context, context->allocate_output(2, {}, &output_max)); output_max->flat<float>()(0) = max_input; }
1
C++
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
safe
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast<OpData*>(node->user_data); const TfLiteTensor* input1; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor1, &input1)); const TfLiteTensor* input2; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor2, &input2)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); switch (input1->type) { case kTfLiteInt32: { return EvalImpl<int32_t>(context, data->requires_broadcast, input1, input2, output); } case kTfLiteFloat32: { return EvalImpl<float>(context, data->requires_broadcast, input1, input2, output); } default: { context->ReportError(context, "Type '%s' is not supported by floor_div.", TfLiteTypeGetName(input1->type)); return kTfLiteError; } } }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
void EvalAddN(TfLiteContext* context, TfLiteNode* node) { // TODO(haoliang): Initialize all_inputs only once during init. VectorOfTensors<T> all_inputs(*context, *node->inputs); // Safe to use unchecked since caller checks that tensor is valid TfLiteTensor* output = GetOutput(context, node, kOutputTensor); int num_inputs = NumInputs(node); // Safe to use unchecked since caller checks that tensor is valid const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); reference_ops::AddN<T>(GetTensorShape(input1), num_inputs, all_inputs.data(), GetTensorData<T>(output)); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
void FormatConverter<T>::InitSparseToDenseConverter( std::vector<int> shape, std::vector<int> traversal_order, std::vector<TfLiteDimensionType> format, std::vector<int> dense_size, std::vector<std::vector<int>> segments, std::vector<std::vector<int>> indices, std::vector<int> block_map) { dense_shape_ = std::move(shape); traversal_order_ = std::move(traversal_order); block_map_ = std::move(block_map); format_ = std::move(format); dense_size_ = 1; for (int i = 0; i < dense_shape_.size(); i++) { dense_size_ *= dense_shape_[i]; } dim_metadata_.resize(2 * format_.size()); for (int i = 0; i < format_.size(); i++) { if (format_[i] == kTfLiteDimDense) { dim_metadata_[2 * i] = {dense_size[i]}; } else { dim_metadata_[2 * i] = std::move(segments[i]); dim_metadata_[2 * i + 1] = std::move(indices[i]); } } int original_rank = dense_shape_.size(); int block_dim = 0; blocked_shape_.resize(original_rank); block_size_.resize(block_map_.size()); for (int i = 0; i < original_rank; i++) { if (block_dim < block_map_.size() && block_map_[block_dim] == i) { int orig_dim = traversal_order_[original_rank + block_dim]; block_size_[block_dim] = dense_size[orig_dim]; blocked_shape_[i] = dense_shape_[i] / dense_size[orig_dim]; block_dim++; } else { blocked_shape_[i] = dense_shape_[i]; } } }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
absl::Status IsSupported(const TfLiteContext* context, const TfLiteNode* tflite_node, const TfLiteRegistration* registration) final { if (mirror_pad_) { const TfLiteMirrorPaddingParams* tf_options; RETURN_IF_ERROR(RetrieveBuiltinData(tflite_node, &tf_options)); if (tf_options->mode != TfLiteMirrorPaddingMode::kTfLiteMirrorPaddingReflect) { return absl::InvalidArgumentError( "Only Reflective padding is supported for Mirror Pad operation."); } } RETURN_IF_ERROR(CheckMaxSupportedOpVersion(registration, 2)); RETURN_IF_ERROR(CheckInputsOutputs(context, tflite_node, /*runtime_inputs=*/1, /*outputs=*/1)); RETURN_IF_ERROR(CheckTensorIsAvailable(context, tflite_node, 1)); auto pad_tensor = tflite::GetInput(context, tflite_node, 1); if (pad_tensor->dims->size != 2) { return absl::InvalidArgumentError(absl::StrCat( "Invalid paddings tensor dimension: expected 2 dim, got ", pad_tensor->dims->size, " dim")); } bool supported = pad_tensor->dims->data[0] == 3 || pad_tensor->dims->data[0] == 4; if (!supported || pad_tensor->dims->data[1] != 2) { return absl::InvalidArgumentError(absl::StrCat( "Invalid paddings tensor shape: expected 4x2 or 3x2, got ", pad_tensor->dims->data[0], "x", pad_tensor->dims->data[1])); } return absl::OkStatus(); }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
TfLiteStatus EvalHashtableImport(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input_resource_id_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputResourceIdTensor, &input_resource_id_tensor)); const int resource_id = input_resource_id_tensor->data.i32[0]; const TfLiteTensor* key_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kKeyTensor, &key_tensor)); const TfLiteTensor* value_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kValueTensor, &value_tensor)); Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_); auto& resources = subgraph->resources(); auto* lookup = resource::GetHashtableResource(&resources, resource_id); TF_LITE_ENSURE(context, lookup != nullptr); TF_LITE_ENSURE_STATUS( lookup->CheckKeyAndValueTypes(context, key_tensor, value_tensor)); // The hashtable resource will only be initialized once, attempting to // initialize it multiple times will be a no-op. auto result = lookup->Import(context, key_tensor, value_tensor); return result; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); if (input->type != kTfLiteFloat32) { TF_LITE_UNSUPPORTED_TYPE(context, input->type, "Ceil"); } optimized_ops::Ceil(GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); return kTfLiteOk; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
void CommandData::ProcessCommand() { #ifndef SFX_MODULE const wchar *SingleCharCommands=L"FUADPXETK"; if (Command[0]!=0 && Command[1]!=0 && wcschr(SingleCharCommands,Command[0])!=NULL || *ArcName==0) OutHelp(*Command==0 ? RARX_SUCCESS:RARX_USERERROR); // Return 'success' for 'rar' without parameters. const wchar *ArcExt=GetExt(ArcName); #ifdef _UNIX if (ArcExt==NULL && (!FileExist(ArcName) || IsDir(GetFileAttr(ArcName)))) wcsncatz(ArcName,L".rar",ASIZE(ArcName)); #else if (ArcExt==NULL) wcsncatz(ArcName,L".rar",ASIZE(ArcName)); #endif // Treat arcname.part1 as arcname.part1.rar. if (ArcExt!=NULL && wcsnicomp(ArcExt,L".part",5)==0 && IsDigit(ArcExt[5]) && !FileExist(ArcName)) { wchar Name[NM]; wcsncpyz(Name,ArcName,ASIZE(Name)); wcsncatz(Name,L".rar",ASIZE(Name)); if (FileExist(Name)) wcsncpyz(ArcName,Name,ASIZE(ArcName)); } if (wcschr(L"AFUMD",*Command)==NULL) { if (GenerateArcName) GenerateArchiveName(ArcName,ASIZE(ArcName),GenerateMask,false); StringList ArcMasks; ArcMasks.AddString(ArcName); ScanTree Scan(&ArcMasks,Recurse,SaveSymLinks,SCAN_SKIPDIRS); FindData FindData; while (Scan.GetNext(&FindData)==SCAN_SUCCESS) AddArcName(FindData.Name); } else AddArcName(ArcName); #endif switch(Command[0]) { case 'P': case 'X': case 'E': case 'T': case 'I': { CmdExtract Extract(this); Extract.DoExtract(); } break; #ifndef SILENT case 'V': case 'L': ListArchive(this); break; default: OutHelp(RARX_USERERROR); #endif } if (!BareOutput) mprintf(L"\n"); }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
R_API RBinJavaVerificationObj *r_bin_java_read_from_buffer_verification_info_new(ut8 *buffer, ut64 sz, ut64 buf_offset) { if (sz < 8) { return NULL; } ut64 offset = 0; RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj); if (!se) { return NULL; } se->file_offset = buf_offset; se->tag = buffer[offset]; offset += 1; if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) { se->info.obj_val_cp_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; } else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) { se->info.uninit_offset = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; } if (R_BIN_JAVA_STACKMAP_UNINIT < se->tag) { r_bin_java_verification_info_free (se); return NULL; } se->size = offset; return se; }
1
C++
CWE-805
Buffer Access with Incorrect Length Value
The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer.
https://cwe.mitre.org/data/definitions/805.html
safe
TfLiteStatus GetOutputSafe(const TfLiteContext* context, const TfLiteNode* node, int index, TfLiteTensor** tensor) { int tensor_index; TF_LITE_ENSURE_OK( context, ValidateTensorIndexingSafe(context, index, node->outputs->size, node->outputs->data, &tensor_index)); *tensor = GetTensorAtIndex(context, tensor_index); return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
int FileInStream::overrun(int itemSize, int nItems, bool wait) { if (itemSize > (int)sizeof(b)) throw Exception("FileInStream overrun: max itemSize exceeded"); if (end - ptr != 0) memmove(b, ptr, end - ptr); end -= ptr - b; ptr = b; while (end < b + itemSize) { size_t n = fread((U8 *)end, b + sizeof(b) - end, 1, file); if (n == 0) { if (ferror(file)) throw SystemException("fread", errno); if (feof(file)) throw EndOfStream(); return 0; } end += b + sizeof(b) - end; } if (itemSize * nItems > end - ptr) nItems = (end - ptr) / itemSize; return nItems; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); // Reinterprete the opaque data provided by user. OpData* data = reinterpret_cast<OpData*>(node->user_data); const TfLiteTensor* input1; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor1, &input1)); const TfLiteTensor* input2; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor2, &input2)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type); const TfLiteType type = input1->type; if (type != kTfLiteBool) { context->ReportError(context, "Logical ops only support bool type."); return kTfLiteError; } output->type = type; data->requires_broadcast = !HaveSameShapes(input1, input2); TfLiteIntArray* output_size = nullptr; if (data->requires_broadcast) { TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast( context, input1, input2, &output_size)); } else { output_size = TfLiteIntArrayCopy(input1->dims); } return context->ResizeTensor(context, output, output_size); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
static int intel_pmu_handle_irq(struct pt_regs *regs) { struct perf_sample_data data; struct cpu_hw_events *cpuc; int bit, loops; u64 status; int handled; perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); /* * Some chipsets need to unmask the LVTPC in a particular spot * inside the nmi handler. As a result, the unmasking was pushed * into all the nmi handlers. * * This handler doesn't seem to have any issues with the unmasking * so it was left at the top. */ apic_write(APIC_LVTPC, APIC_DM_NMI); intel_pmu_disable_all(); handled = intel_pmu_drain_bts_buffer(); status = intel_pmu_get_status(); if (!status) { intel_pmu_enable_all(0); return handled; } loops = 0; again: intel_pmu_ack_status(status); if (++loops > 100) { WARN_ONCE(1, "perfevents: irq loop stuck!\n"); perf_event_print_debug(); intel_pmu_reset(); goto done; } inc_irq_stat(apic_perf_irqs); intel_pmu_lbr_read(); /* * PEBS overflow sets bit 62 in the global status register */ if (__test_and_clear_bit(62, (unsigned long *)&status)) { handled++; x86_pmu.drain_pebs(regs); } for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) { struct perf_event *event = cpuc->events[bit]; handled++; if (!test_bit(bit, cpuc->active_mask)) continue; if (!intel_pmu_save_and_restart(event)) continue; data.period = event->hw.last_period; if (perf_event_overflow(event, 1, &data, regs)) x86_pmu_stop(event, 0); } /* * Repeat if there is more work to be done: */ status = intel_pmu_get_status(); if (status) goto again; done: intel_pmu_enable_all(0); return handled; }
0
C++
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
untrusted_launcher_response_callback (GtkDialog *dialog, int response_id, ActivateParametersDesktop *parameters) { GdkScreen *screen; char *uri; GFile *file; switch (response_id) { case RESPONSE_RUN: { screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); uri = nautilus_file_get_uri (parameters->file); DEBUG ("Launching untrusted launcher %s", uri); nautilus_launch_desktop_file (screen, uri, NULL, parameters->parent_window); g_free (uri); } break; case RESPONSE_MARK_TRUSTED: { file = nautilus_file_get_location (parameters->file); nautilus_file_mark_desktop_file_trusted (file, parameters->parent_window, TRUE, NULL, NULL); g_object_unref (file); } break; default: { /* Just destroy dialog */ } break; } gtk_widget_destroy (GTK_WIDGET (dialog)); activate_parameters_desktop_free (parameters); }
0
C++
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.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const { DoQuickSanityCheck(); ModularArithmetic modn(m_n); Integer r, rInv; // do this in a loop for people using small numbers for testing do { r.Randomize(rng, Integer::One(), m_n - Integer::One()); // Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting. // Squaring to satisfy Jacobi requirements suggested by JPM. r = modn.Square(r); rInv = modn.MultiplicativeInverse(r); } while (rInv.IsZero()); Integer re = modn.Square(r); re = modn.Multiply(re, x); // blind Integer cp=re%m_p, cq=re%m_q; if (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1) { cp = cp.IsOdd() ? (cp+m_p) >> 1 : cp >> 1; cq = cq.IsOdd() ? (cq+m_q) >> 1 : cq >> 1; } #pragma omp parallel #pragma omp sections { #pragma omp section cp = ModularSquareRoot(cp, m_p); #pragma omp section cq = ModularSquareRoot(cq, m_q); } Integer y = CRT(cq, m_q, cp, m_p, m_u); y = modn.Multiply(y, rInv); // unblind y = STDMIN(y, m_n-y); if (ApplyFunction(y) != x) // check throw Exception(Exception::OTHER_ERROR, "InvertibleRWFunction: computational error during private key operation"); return y; }
1
C++
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.
https://cwe.mitre.org/data/definitions/200.html
safe
TEST(TensorSliceReaderTest, MissingTensorData) { const string fname = io::JoinPath(testing::TmpDir(), "missing_data_checkpoint"); TensorSliceWriter writer(fname, CreateTableTensorSliceBuilder); const int32 data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; TF_ASSERT_OK(writer.Add("test", TensorShape({4, 5}), TensorSlice::ParseOrDie("0,2:-"), data)); TF_ASSERT_OK(writer.Finish()); MutateSavedTensorSlices(fname, [&](SavedTensorSlices sts) { if (sts.has_data()) { // Replace the data with only 4 elements. Fill(data, 4, sts.mutable_data()->mutable_data()); } return sts.SerializeAsString(); }); TensorSliceReader reader(fname, OpenTableTensorSliceReader); TF_ASSERT_OK(reader.status()); // The tensor should be present, but loading it should fail due to the missing // data. EXPECT_TRUE(reader.HasTensor("test", nullptr, nullptr)); std::unique_ptr<Tensor> tensor; EXPECT_FALSE(reader.GetTensor("test", &tensor).ok()); }
1
C++
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteIntArray* input_dims = input->dims; int input_dims_size = input_dims->size; TF_LITE_ENSURE(context, input_dims_size >= 2); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TfLiteIntArray* output_shape = TfLiteIntArrayCreate(input_dims_size); for (int i = 0; i < input_dims_size; i++) { output_shape->data[i] = input_dims->data[i]; } // Resize the output tensor to the same size as the input tensor. output->type = input->type; TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output, output_shape)); return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
void RequestContext::SetApiKeyHeader() { request_->AddHeaderToBackend(kDefaultApiKeyHeaderName, api_key_); }
0
C++
CWE-290
Authentication Bypass by Spoofing
This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks.
https://cwe.mitre.org/data/definitions/290.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const TfLiteTensor* axis; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxisTensor, &axis)); TF_LITE_ENSURE_EQ(context, NumDimensions(axis), 1); TF_LITE_ENSURE(context, NumDimensions(input) >= NumElements(axis)); if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 && input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 && input->type != kTfLiteInt64 && input->type != kTfLiteBool) { context->ReportError(context, "Type '%s' is not supported by reverse.", TfLiteTypeGetName(input->type)); return kTfLiteError; } if (axis->type != kTfLiteInt32) { context->ReportError(context, "Axis Type '%s' is not supported by reverse.", TfLiteTypeGetName(axis->type)); return kTfLiteError; } // TODO(renjieliu): support multi-axis case. if (NumElements(axis) > 1) { context->ReportError(context, "Current does not support more than 1 axis."); } TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims); TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type); return context->ResizeTensor(context, output, output_shape); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
Envoy::Ssl::ClientValidationStatus DefaultCertValidator::verifyCertificate( X509* cert, const std::vector<std::string>& verify_san_list, const std::vector<Matchers::StringMatcherImpl<envoy::type::matcher::v3::StringMatcher>>& subject_alt_name_matchers) { Envoy::Ssl::ClientValidationStatus validated = Envoy::Ssl::ClientValidationStatus::NotValidated; if (!verify_san_list.empty()) { if (!verifySubjectAltName(cert, verify_san_list)) { stats_.fail_verify_san_.inc(); return Envoy::Ssl::ClientValidationStatus::Failed; } validated = Envoy::Ssl::ClientValidationStatus::Validated; } if (!subject_alt_name_matchers.empty()) { if (!matchSubjectAltName(cert, subject_alt_name_matchers)) { stats_.fail_verify_san_.inc(); return Envoy::Ssl::ClientValidationStatus::Failed; } validated = Envoy::Ssl::ClientValidationStatus::Validated; } if (!verify_certificate_hash_list_.empty() || !verify_certificate_spki_list_.empty()) { const bool valid_certificate_hash = !verify_certificate_hash_list_.empty() && verifyCertificateHashList(cert, verify_certificate_hash_list_); const bool valid_certificate_spki = !verify_certificate_spki_list_.empty() && verifyCertificateSpkiList(cert, verify_certificate_spki_list_); if (!valid_certificate_hash && !valid_certificate_spki) { stats_.fail_verify_cert_hash_.inc(); return Envoy::Ssl::ClientValidationStatus::Failed; } validated = Envoy::Ssl::ClientValidationStatus::Validated; } return validated; }
0
C++
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
vulnerable
void Context::onDone() { if (wasm_->onDone_) { wasm_->onDone_(this, id_); } }
0
C++
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); auto* params = reinterpret_cast<TfLiteShapeParams*>(node->builtin_data); switch (params->out_type) { case kTfLiteInt32: output->type = kTfLiteInt32; break; case kTfLiteInt64: output->type = kTfLiteInt64; break; default: context->ReportError(context, "Unknown shape output data type: %d", params->out_type); return kTfLiteError; } // By design, the input shape is always known at the time of Prepare, even // if the preceding op that generates |input| is dynamic. Thus, we can // always compute the shape immediately, without waiting for Eval. SetTensorToPersistentRo(output); // Shape always produces a 1-dimensional output tensor, where each output // element is the length of the corresponding input tensor's dimension. TfLiteIntArray* output_size = TfLiteIntArrayCreate(1); output_size->data[0] = NumDimensions(input); TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_size)); TFLITE_DCHECK_EQ(NumDimensions(output), 1); TFLITE_DCHECK_EQ(SizeOfDimension(output, 0), NumDimensions(input)); // Immediately propagate the known shape to the output tensor. This allows // downstream ops that rely on the value to use it during prepare. switch (output->type) { case kTfLiteInt32: ExtractShape(input, GetTensorData<int32_t>(output)); break; case kTfLiteInt64: ExtractShape(input, GetTensorData<int64_t>(output)); break; default: return kTfLiteError; } return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
TfLiteStatus GatherStrings(TfLiteContext* context, const TfLiteTensor* input, const TfLiteTensor* positions, TfLiteTensor* output) { DynamicBuffer buffer; const PositionT* indexes = GetTensorData<PositionT>(positions); bool indices_has_only_positive_elements = true; const size_t num_indices = positions->bytes / sizeof(PositionT); for (size_t i = 0; i < num_indices; i++) { if (indexes[i] < 0) { indices_has_only_positive_elements = false; break; } } TF_LITE_ENSURE(context, indices_has_only_positive_elements); const PositionT num_strings = GetStringCount(input); const int num_indexes = NumElements(positions); for (int i = 0; i < num_indexes; ++i) { const PositionT pos = indexes[i]; TF_LITE_ENSURE(context, pos < num_strings); const auto string_ref = GetString(input, pos); buffer.AddString(string_ref.str, string_ref.len); } buffer.WriteToTensor(output, /*new_shape=*/nullptr); return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
TfLiteStatus PrepareSimple(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); OpContext op_context(context, node); TF_LITE_ENSURE_TYPES_EQ(context, op_context.axis->type, kTfLiteInt32); TF_LITE_ENSURE_OK(context, InitializeTemporaries(context, node, &op_context)); TfLiteTensor* resolved_axis = GetTemporary(context, node, /*index=*/1); // Leaves work to Eval if axis is not constant; else resizes output. if (!IsConstantTensor(op_context.axis)) { SetTensorToDynamic(op_context.output); SetTensorToDynamic(resolved_axis); return kTfLiteOk; } resolved_axis->allocation_type = kTfLiteArenaRw; TF_LITE_ENSURE_OK(context, ResizeTempAxis(context, &op_context, resolved_axis)); TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, &op_context)); return kTfLiteOk; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT if (pow((float) r+1, dim) <= entries) return -1; if ((int) floor(pow((float) r, dim)) > entries) return -1; return r; }
1
C++
CWE-617
Reachable Assertion
The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.
https://cwe.mitre.org/data/definitions/617.html
safe
TfLiteStatus Gather(const TfLiteGatherParams& params, const TfLiteTensor* input, const TfLiteTensor* positions, TfLiteTensor* output) { tflite::GatherParams op_params; op_params.axis = params.axis; op_params.batch_dims = params.batch_dims; optimized_ops::Gather(op_params, GetTensorShape(input), GetTensorData<InputT>(input), GetTensorShape(positions), GetTensorData<PositionsT>(positions), GetTensorShape(output), GetTensorData<InputT>(output)); return kTfLiteOk; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: AverageEvalFloat<kernel_type>(context, node, params, data, input, output); break; case kTfLiteUInt8: AverageEvalQuantizedUint8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt8: AverageEvalQuantizedInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt16: AverageEvalQuantizedInt16<kernel_type>(context, node, params, data, input, output); break; default: TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
void * alloc_bottom(size_t size, size_t align) {loop: align_bottom(align); byte * tmp = bottom; bottom += size; if (bottom > top) {new_chunk(); goto loop;} return tmp; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
void TileManager::crop( RawTile *ttt ){ int tw = image->getTileWidth(); int th = image->getTileHeight(); if( loglevel >= 5 ){ *logfile << "TileManager :: Edge tile: Base size: " << tw << "x" << th << ": This tile: " << ttt->width << "x" << ttt->height << endl; } // Create a new buffer, fill it with the old data, then copy // back the cropped part into the RawTile buffer int len = tw * th * ttt->channels * (ttt->bpc/8); unsigned char* buffer = (unsigned char*) malloc( len ); unsigned char* src_ptr = (unsigned char*) memcpy( buffer, ttt->data, len ); unsigned char* dst_ptr = (unsigned char*) ttt->data; // Copy one scanline at a time len = ttt->width * ttt->channels * (ttt->bpc/8); for( unsigned int i=0; i<ttt->height; i++ ){ memcpy( dst_ptr, src_ptr, len ); dst_ptr += len; src_ptr += tw * ttt->channels * (ttt->bpc/8); } free( buffer ); // Reset the data length len = ttt->width * ttt->height * ttt->channels * (ttt->bpc/8); ttt->dataLength = len; ttt->padded = false; }
0
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
void ecall_partition_for_sort(uint8_t *sort_order, size_t sort_order_length, uint32_t num_partitions, uint8_t *input_rows, size_t input_rows_length, uint8_t *boundary_rows, size_t boundary_rows_length, uint8_t **output_partitions, size_t *output_partition_lengths) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); assert(sgx_is_outside_enclave(boundary_rows, boundary_rows_length) == 1); sgx_lfence(); try { partition_for_sort(sort_order, sort_order_length, num_partitions, input_rows, input_rows_length, boundary_rows, boundary_rows_length, output_partitions, output_partition_lengths); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
TfLiteStatus AverageEvalQuantizedUint8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_AVERAGE_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ TF_LITE_ENSURE(context, type::AveragePool(op_params, GetTensorShape(input), \ GetTensorData<uint8_t>(input), \ GetTensorShape(output), \ GetTensorData<uint8_t>(output))) if (kernel_type == kReference) { TF_LITE_AVERAGE_POOL(reference_ops); } else { TF_LITE_AVERAGE_POOL(optimized_ops); } #undef TF_LITE_AVERAGE_POOL return kTfLiteOk; }
1
C++
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
void CConfig::Write(CFile& File, unsigned int iIndentation) { CString sIndentation = CString(iIndentation, '\t'); auto SingleLine = [](const CString& s) { return s.Replace_n("\r", "").Replace_n("\n", ""); }; for (const auto& it : m_ConfigEntries) { for (const CString& sValue : it.second) { File.Write(SingleLine(sIndentation + it.first + " = " + sValue) + "\n"); } } for (const auto& it : m_SubConfigs) { for (const auto& it2 : it.second) { File.Write("\n"); File.Write(SingleLine(sIndentation + "<" + it.first + " " + it2.first + ">") + "\n"); it2.second.m_pSubConfig->Write(File, iIndentation + 1); File.Write(SingleLine(sIndentation + "</" + it.first + ">") + "\n"); } } }
1
C++
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.
https://cwe.mitre.org/data/definitions/20.html
safe
TfLiteStatus ReverseSequenceHelper(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* seq_lengths_tensor = GetInput(context, node, kSeqLengthsTensor); switch (seq_lengths_tensor->type) { case kTfLiteInt32: { return ReverseSequenceImpl<T, int32_t>(context, node); } case kTfLiteInt64: { return ReverseSequenceImpl<T, int64_t>(context, node); } default: { context->ReportError( context, "Seq_lengths type '%s' is not supported by reverse_sequence.", TfLiteTypeGetName(seq_lengths_tensor->type)); return kTfLiteError; } } return kTfLiteOk; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
ObfuscatedPasswd::ObfuscatedPasswd(const PlainPasswd& plainPwd) : CharArray(8), length(8) { int l = strlen(plainPwd.buf), i; for (i=0; i<8; i++) buf[i] = i<l ? plainPwd.buf[i] : 0; deskey(d3desObfuscationKey, EN0); des((rdr::U8*)buf, (rdr::U8*)buf); }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
SilenceMessage(const std::string& mask, const std::string& flags) : ClientProtocol::Message("SILENCE") { PushParam(mask); PushParamRef(flags); }
1
C++
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
safe
CFontFileBase(char *sFile, int nLen, bool bFreeFileData) { m_sFileData = m_sFile = (unsigned char *)sFile; m_nLen = nLen; m_bFreeFileData = bFreeFileData; m_nPos = 0; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { case kTfLiteFloat32: return EvalImpl<kernel_type, kTfLiteFloat32>(context, node); case kTfLiteUInt8: return EvalImpl<kernel_type, kTfLiteUInt8>(context, node); case kTfLiteInt8: return EvalImpl<kernel_type, kTfLiteInt8>(context, node); case kTfLiteInt16: return EvalImpl<kernel_type, kTfLiteInt16>(context, node); default: TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
void FormatConverter<T>::Populate(const T* src_data, std::vector<int> indices, int level, int prev_idx, int* src_data_ptr, T* dest_data) { if (level == indices.size()) { int orig_rank = dense_shape_.size(); std::vector<int> orig_idx; orig_idx.resize(orig_rank); int i = 0; for (; i < orig_idx.size(); i++) { int orig_dim = traversal_order_[i]; orig_idx[orig_dim] = indices[i]; } for (; i < indices.size(); i++) { const int block_idx = traversal_order_[i] - orig_rank; const int orig_dim = block_map_[block_idx]; orig_idx[orig_dim] = orig_idx[orig_dim] * block_size_[block_idx] + indices[i]; } dest_data[GetFlattenedIndex(orig_idx, dense_shape_)] = src_data[*src_data_ptr]; *src_data_ptr = *src_data_ptr + 1; return; } const int metadata_idx = 2 * level; const int shape_of_level = dim_metadata_[metadata_idx][0]; if (format_[level] == kTfLiteDimDense) { for (int i = 0; i < shape_of_level; i++) { indices[level] = i; Populate(src_data, indices, level + 1, prev_idx * shape_of_level + i, src_data_ptr, dest_data); } } else if (prev_idx + 1 < dim_metadata_[metadata_idx].size()) { const auto& array_segments = dim_metadata_[metadata_idx]; const auto& array_indices = dim_metadata_[metadata_idx + 1]; for (int i = array_segments[prev_idx]; i < array_segments[prev_idx + 1]; i++) { if (i < array_indices.size() && level < indices.size()) { indices[level] = array_indices[i]; Populate(src_data, indices, level + 1, i, src_data_ptr, dest_data); } } } }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
static ssize_t _hostsock_sendto( oe_fd_t* sock_, const void* buf, size_t count, int flags, const struct oe_sockaddr* dest_addr, oe_socklen_t addrlen) { ssize_t ret = -1; sock_t* sock = _cast_sock(sock_); oe_errno = 0; if (!sock || (count && !buf)) OE_RAISE_ERRNO(OE_EINVAL); if (oe_syscall_sendto_ocall( &ret, sock->host_fd, buf, count, flags, (struct oe_sockaddr*)dest_addr, addrlen) != OE_OK) { OE_RAISE_ERRNO(OE_EINVAL); } done: return ret; }
0
C++
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a) { #ifdef BN_LLONG BN_ULLONG t,tt; #else BN_ULONG bl,bh; #endif BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); r[6]=c1; r[7]=c2; }
0
C++
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
req::ptr<XMLDocumentData> doc() const { return m_node ? m_node->doc() : nullptr; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
TfLiteStatus NonMaxSuppressionMultiClass(TfLiteContext* context, TfLiteNode* node, OpData* op_data) { // Get the input tensors const TfLiteTensor* input_box_encodings = GetInput(context, node, kInputTensorBoxEncodings); const TfLiteTensor* input_class_predictions = GetInput(context, node, kInputTensorClassPredictions); const int num_boxes = input_box_encodings->dims->data[1]; const int num_classes = op_data->num_classes; TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[0], kBatchSize); TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[1], num_boxes); const int num_classes_with_background = input_class_predictions->dims->data[2]; TF_LITE_ENSURE(context, (num_classes_with_background - num_classes <= 1)); TF_LITE_ENSURE(context, (num_classes_with_background >= num_classes)); const TfLiteTensor* scores; switch (input_class_predictions->type) { case kTfLiteUInt8: { TfLiteTensor* temporary_scores = &context->tensors[op_data->scores_index]; DequantizeClassPredictions(input_class_predictions, num_boxes, num_classes_with_background, temporary_scores); scores = temporary_scores; } break; case kTfLiteFloat32: scores = input_class_predictions; break; default: // Unsupported type. return kTfLiteError; } if (op_data->use_regular_non_max_suppression) TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassRegularHelper( context, node, op_data, GetTensorData<float>(scores))); else TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassFastHelper( context, node, op_data, GetTensorData<float>(scores))); return kTfLiteOk; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
static port::StatusOr<CudnnRnnSequenceTensorDescriptor> Create( GpuExecutor* parent, int max_seq_length, int batch_size, int data_size, cudnnDataType_t data_type) { CHECK_GT(max_seq_length, 0); int dims[] = {batch_size, data_size, 1}; int strides[] = {dims[1] * dims[2], dims[2], 1}; TensorDescriptor tensor_desc = CreateTensorDescriptor(); RETURN_IF_CUDNN_ERROR(cudnnSetTensorNdDescriptor( /*tensorDesc=*/tensor_desc.get(), /*dataType=*/data_type, /*nbDims=*/sizeof(dims) / sizeof(dims[0]), /*dimA=*/dims, /*strideA=*/strides)); return CudnnRnnSequenceTensorDescriptor(parent, max_seq_length, batch_size, data_size, data_type, nullptr, std::move(tensor_desc)); }
0
C++
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.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
otError Commissioner::GeneratePskc(const char * aPassPhrase, const char * aNetworkName, const Mac::ExtendedPanId &aExtPanId, Pskc & aPskc) { otError error = OT_ERROR_NONE; const char *saltPrefix = "Thread"; uint8_t salt[OT_PBKDF2_SALT_MAX_LEN]; uint16_t saltLen = 0; VerifyOrExit((strlen(aPassPhrase) >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) && (strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE), error = OT_ERROR_INVALID_ARGS); memset(salt, 0, sizeof(salt)); memcpy(salt, saltPrefix, strlen(saltPrefix)); saltLen += static_cast<uint16_t>(strlen(saltPrefix)); memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId)); saltLen += OT_EXT_PAN_ID_SIZE; memcpy(salt + saltLen, aNetworkName, strlen(aNetworkName)); saltLen += static_cast<uint16_t>(strlen(aNetworkName)); otPbkdf2Cmac(reinterpret_cast<const uint8_t *>(aPassPhrase), static_cast<uint16_t>(strlen(aPassPhrase)), reinterpret_cast<const uint8_t *>(salt), saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8); exit: return error; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
TEST_F(RouterTest, RetryUpstreamResetResponseStarted) { NiceMock<Http::MockRequestEncoder> encoder1; Http::ResponseDecoder* response_decoder = nullptr; expectNewStreamWithImmediateEncoder(encoder1, &response_decoder, Http::Protocol::Http10); expectResponseTimerCreate(); Http::TestRequestHeaderMapImpl headers{{"x-envoy-retry-on", "5xx"}, {"x-envoy-internal", "true"}}; HttpTestUtility::addDefaultHeaders(headers); router_.decodeHeaders(headers, true); EXPECT_EQ(1U, callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value()); // Since the response is already started we don't retry. EXPECT_CALL(*router_.retry_state_, shouldRetryHeaders(_, _, _)).WillOnce(Return(RetryStatus::No)); EXPECT_CALL(callbacks_, encodeHeaders_(_, false)); Http::ResponseHeaderMapPtr response_headers( new Http::TestResponseHeaderMapImpl{{":status", "200"}}); EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_, putHttpResponseCode(200)); response_decoder->decodeHeaders(std::move(response_headers), false); EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_, putResult(Upstream::Outlier::Result::LocalOriginConnectFailed, _)); // Normally, sendLocalReply will actually send the reply, but in this case the // HCM will detect the headers have already been sent and not route through // the encoder again. EXPECT_CALL(callbacks_, sendLocalReply(_, _, _, _, _)).WillOnce(testing::InvokeWithoutArgs([] { })); encoder1.stream_.resetStream(Http::StreamResetReason::RemoteReset); // For normal HTTP, once we have a 200 we consider this a success, even if a // later reset occurs. EXPECT_TRUE(verifyHostUpstreamStats(1, 0)); EXPECT_EQ(1U, callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value()); }
0
C++
CWE-670
Always-Incorrect Control Flow Implementation
The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated.
https://cwe.mitre.org/data/definitions/670.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); output->type = input->type; return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
inline void* aligned_malloc(size_t size, size_t alignment) { return folly::detail::aligned_malloc(size, alignment); }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
void ComputeAsync(OpKernelContext* c, DoneCallback done) override { auto col_params = new CollectiveParams(); auto done_with_cleanup = [col_params, done = std::move(done)]() { done(); col_params->Unref(); }; core::RefCountPtr<CollectiveGroupResource> resource; OP_REQUIRES_OK_ASYNC(c, LookupResource(c, HandleFromInput(c, 1), &resource), done_with_cleanup); Tensor group_assignment = c->input(2); OP_REQUIRES_OK_ASYNC( c, FillCollectiveParams(col_params, group_assignment, ALL_TO_ALL_COLLECTIVE, resource.get()), done); col_params->instance.shape = c->input(0).shape(); VLOG(1) << "CollectiveAllToAll group_size " << col_params->group.group_size << " group_key " << col_params->group.group_key << " instance_key " << col_params->instance.instance_key; // Allocate the output tensor, trying to reuse the input. Tensor* output = nullptr; OP_REQUIRES_OK_ASYNC(c, c->forward_input_or_allocate_output( {0}, 0, col_params->instance.shape, &output), done_with_cleanup); Run(c, col_params, std::move(done_with_cleanup)); }
1
C++
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
safe
void * alloc_top(size_t size) { top -= size; if (top < bottom) {new_chunk(); top -= size;} return top; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable