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
void* TFE_HandleToDLPack(TFE_TensorHandle* h, TF_Status* status) { auto tf_dlm_context = GetDlContext(h, status); if (!status->status.ok()) { return nullptr; } auto* tf_dlm_data = TFE_TensorHandleDevicePointer(h, status); if (!status->status.ok()) { return nullptr; } const Tensor* tensor = GetTensorFromHandle(h, status); TF_DataType data_type = static_cast<TF_DataType>(tensor->dtype()); auto tf_dlm_type = GetDlDataType(data_type, status); if (!status->status.ok()) { return nullptr; } TensorReference tensor_ref(*tensor); // This will call buf_->Ref() auto* tf_dlm_tensor_ctx = new TfDlManagedTensorCtx(tensor_ref); tf_dlm_tensor_ctx->reference = tensor_ref; DLManagedTensor* dlm_tensor = &tf_dlm_tensor_ctx->tensor; dlm_tensor->manager_ctx = tf_dlm_tensor_ctx; dlm_tensor->deleter = &DLManagedTensorDeleter; dlm_tensor->dl_tensor.ctx = tf_dlm_context; int ndim = tensor->dims(); dlm_tensor->dl_tensor.ndim = ndim; dlm_tensor->dl_tensor.data = tf_dlm_data; dlm_tensor->dl_tensor.dtype = tf_dlm_type; std::vector<int64_t>* shape_arr = &tf_dlm_tensor_ctx->shape; std::vector<int64_t>* stride_arr = &tf_dlm_tensor_ctx->strides; shape_arr->resize(ndim); stride_arr->resize(ndim, 1); for (int i = 0; i < ndim; i++) { (*shape_arr)[i] = tensor->dim_size(i); } for (int i = ndim - 2; i >= 0; --i) { (*stride_arr)[i] = (*shape_arr)[i + 1] * (*stride_arr)[i + 1]; } dlm_tensor->dl_tensor.shape = shape_arr->data(); // There are two ways to represent compact row-major data // 1) nullptr indicates tensor is compact and row-majored. // 2) fill in the strides array as the real case for compact row-major data. // Here we choose option 2, since some frameworks didn't handle the strides // argument properly. dlm_tensor->dl_tensor.strides = stride_arr->data(); dlm_tensor->dl_tensor.byte_offset = 0; // TF doesn't handle the strides and byte_offsets here return static_cast<void*>(dlm_tensor); }
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
DSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/, const std::string& params, const std::string& provider) const { if(provider == "base" || provider.empty()) return std::unique_ptr<PK_Ops::Signature>(new DSA_Signature_Operation(*this, params)); throw Provider_Not_Found(algo_name(), provider); }
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
TfLiteStatus InitializeTemporaries(TfLiteContext* context, TfLiteNode* node, OpContext* op_context) { // Creates a temp index to iterate through input data. OpData* op_data = reinterpret_cast<OpData*>(node->user_data); TfLiteIntArrayFree(node->temporaries); node->temporaries = TfLiteIntArrayCreate(3); node->temporaries->data[0] = op_data->scratch_tensor_index; TfLiteTensor* scratch_tensor = GetTemporary(context, node, /*index=*/0); scratch_tensor->type = kTfLiteInt32; scratch_tensor->allocation_type = kTfLiteArenaRw; TfLiteIntArray* index_size = TfLiteIntArrayCreate(1); index_size->data[0] = NumDimensions(op_context->input); TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scratch_tensor, index_size)); // Creates a temp tensor to store resolved axis given input data. node->temporaries->data[1] = op_data->scratch_tensor_index + 1; TfLiteTensor* resolved_axis = GetTemporary(context, node, /*index=*/1); resolved_axis->type = kTfLiteInt32; // Creates a temp tensor to store temp sums when calculating mean. node->temporaries->data[2] = op_data->scratch_tensor_index + 2; TfLiteTensor* temp_sum = GetTemporary(context, node, /*index=*/2); switch (op_context->input->type) { case kTfLiteFloat32: temp_sum->type = kTfLiteFloat32; break; case kTfLiteInt32: temp_sum->type = kTfLiteInt64; break; case kTfLiteInt64: temp_sum->type = kTfLiteInt64; break; case kTfLiteUInt8: case kTfLiteInt8: case kTfLiteInt16: temp_sum->type = kTfLiteInt32; break; case kTfLiteBool: temp_sum->type = kTfLiteBool; break; default: 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 Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data); 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); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); auto data_type = output->type; TF_LITE_ENSURE(context, data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 || data_type == kTfLiteInt8 || data_type == kTfLiteInt32 || data_type == kTfLiteInt64); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); const int block_size = params->block_size; const int input_height = input->dims->data[1]; const int input_width = input->dims->data[2]; int output_height = input_height / block_size; int output_width = input_width / block_size; TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size); TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size); TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = input->dims->data[0]; output_size->data[1] = output_height; output_size->data[2] = output_width; output_size->data[3] = input->dims->data[3] * block_size * block_size; return context->ResizeTensor(context, output, output_size); }
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
int FileInStream::pos() { if (!file) throw Exception("File is not open"); return ftell(file) + ptr - b; }
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 EvalLogic(TfLiteContext* context, TfLiteNode* node, OpContext* op_context, T init_value, T reducer(const T current, const T in)) { int64_t num_axis = NumElements(op_context->axis); TfLiteTensor* temp_index; TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/0, &temp_index)); TfLiteTensor* resolved_axis; TF_LITE_ENSURE_OK( context, GetTemporarySafe(context, node, /*index=*/1, &resolved_axis)); // Resize the output tensor if the output tensor is dynamic. if (IsDynamicTensor(op_context->output)) { TF_LITE_ENSURE_OK(context, ResizeTempAxis(context, op_context, resolved_axis)); TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, op_context)); } if (op_context->input->type == kTfLiteUInt8 || op_context->input->type == kTfLiteInt8) { TF_LITE_ENSURE_EQ(context, op_context->input->params.scale, op_context->output->params.scale); TF_LITE_ENSURE_EQ(context, op_context->input->params.zero_point, op_context->output->params.zero_point); } TF_LITE_ENSURE( context, reference_ops::ReduceGeneric<T>( GetTensorData<T>(op_context->input), op_context->input->dims->data, op_context->input->dims->size, GetTensorData<T>(op_context->output), op_context->output->dims->data, op_context->output->dims->size, GetTensorData<int>(op_context->axis), num_axis, op_context->params->keep_dims, GetTensorData<int>(temp_index), GetTensorData<int>(resolved_axis), init_value, reducer)); 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 ftoa_bounded_extra(JsVarFloat val,char *str, size_t len, int radix, int fractionalDigits) { const JsVarFloat stopAtError = 0.0000001; if (isnan(val)) strncpy(str,"NaN",len); else if (!isfinite(val)) { if (val<0) strncpy(str,"-Infinity",len); else strncpy(str,"Infinity",len); } else { if (val<0) { if (--len <= 0) { *str=0; return; } // bounds check *(str++) = '-'; val = -val; } // what if we're really close to an integer? Just use that... if (((JsVarInt)(val+stopAtError)) == (1+(JsVarInt)val)) val = (JsVarFloat)(1+(JsVarInt)val); JsVarFloat d = 1; while (d*radix <= val) d*=radix; while (d >= 1) { int v = (int)(val / d); val -= v*d; if (--len <= 0) { *str=0; return; } // bounds check *(str++) = itoch(v); d /= radix; } #ifndef USE_NO_FLOATS if (((fractionalDigits<0) && val>0) || fractionalDigits>0) { bool hasPt = false; val*=radix; while (((fractionalDigits<0) && (fractionalDigits>-12) && (val > stopAtError)) || (fractionalDigits > 0)) { int v = (int)(val+((fractionalDigits==1) ? 0.4 : 0.00000001) ); val = (val-v)*radix; if (v==radix) v=radix-1; if (!hasPt) { hasPt = true; if (--len <= 0) { *str=0; return; } // bounds check *(str++)='.'; } if (--len <= 0) { *str=0; return; } // bounds check *(str++)=itoch(v); fractionalDigits--; } } #endif *(str++)=0; } }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
TEST_F(QuantizedConv2DTest, OddPaddingBatch) { const int stride = 2; TF_ASSERT_OK(NodeDefBuilder("quantized_conv_op", "QuantizedConv2D") .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Attr("out_type", DataTypeToEnum<qint32>::v()) .Attr("strides", {1, stride, stride, 1}) .Attr("padding", "SAME") .Finalize(node_def())); TF_ASSERT_OK(InitOp()); const int depth = 1; const int image_width = 4; const int image_height = 4; const int image_batch_count = 3; AddInputFromArray<quint8>( TensorShape({image_batch_count, image_height, image_width, depth}), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); const int filter_size = 3; const int filter_count = 1; AddInputFromArray<quint8>( TensorShape({filter_size, filter_size, depth, filter_count}), {1, 2, 3, 4, 5, 6, 7, 8, 9}); AddInputFromArray<float>(TensorShape({1}), {0}); AddInputFromArray<float>(TensorShape({1}), {255.0f}); AddInputFromArray<float>(TensorShape({1}), {0}); AddInputFromArray<float>(TensorShape({1}), {255.0f}); TF_ASSERT_OK(RunOpKernel()); const int expected_width = image_width / stride; const int expected_height = (image_height * filter_count) / stride; Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height, expected_width, filter_count})); test::FillValues<qint32>(&expected, {348, 252, 274, 175, // 348, 252, 274, 175, // 348, 252, 274, 175}); test::ExpectTensorEqual<qint32>(expected, *GetOutput(0)); }
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 Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDivParams*>(node->builtin_data); 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)); if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) { EvalDiv<kernel_type>(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteUInt8) { TF_LITE_ENSURE_OK( context, EvalQuantized<kernel_type>(context, node, params, data, input1, input2, output)); } else { context->ReportError( context, "Div only supports FLOAT32, INT32 and quantized UINT8 now, got %d.", output->type); return kTfLiteError; } return kTfLiteOk; }
0
C++
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
vulnerable
cmsBool CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* NamedColorList, const char* Name, cmsUInt16Number PCS[3], cmsUInt16Number Colorant[cmsMAXCHANNELS]) { cmsUInt32Number i; if (NamedColorList == NULL) return FALSE; if (NamedColorList ->nColors + 1 > NamedColorList ->Allocated) { if (!GrowNamedColorList(NamedColorList)) return FALSE; } for (i=0; i < NamedColorList ->ColorantCount; i++) NamedColorList ->List[NamedColorList ->nColors].DeviceColorant[i] = Colorant == NULL? 0 : Colorant[i]; for (i=0; i < 3; i++) NamedColorList ->List[NamedColorList ->nColors].PCS[i] = PCS == NULL ? 0 : PCS[i]; if (Name != NULL) { strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name, sizeof(NamedColorList ->List[NamedColorList ->nColors].Name)); NamedColorList ->List[NamedColorList ->nColors].Name[cmsMAX_PATH-1] = 0; } else NamedColorList ->List[NamedColorList ->nColors].Name[0] = 0; NamedColorList ->nColors++; return TRUE; }
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
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TFLITE_DCHECK(node->user_data != nullptr); OpData* data = static_cast<OpData*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, 0); TF_LITE_ENSURE(context, input != nullptr); TfLiteTensor* output = GetOutput(context, node, 0); TF_LITE_ENSURE(context, output != nullptr); // TODO(b/128934713): Add support for fixed-point per-channel quantization. // Currently this only support affine per-layer quantization. TF_LITE_ENSURE_EQ(context, output->quantization.type, kTfLiteAffineQuantization); const auto* affine_quantization = reinterpret_cast<TfLiteAffineQuantization*>(output->quantization.params); TF_LITE_ENSURE(context, affine_quantization); TF_LITE_ENSURE(context, affine_quantization->scale); TF_LITE_ENSURE(context, affine_quantization->scale->size == 1); TF_LITE_ENSURE(context, input->type == kTfLiteFloat32 || input->type == kTfLiteInt16 || input->type == kTfLiteInt8); TF_LITE_ENSURE(context, output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 || output->type == kTfLiteInt16); if (((input->type == kTfLiteInt16 || input->type == kTfLiteInt8) && output->type == kTfLiteInt8) || (input->type == kTfLiteInt16 && output->type == kTfLiteInt16)) { double effective_scale = static_cast<double>(input->params.scale) / static_cast<double>(output->params.scale); QuantizeMultiplier(effective_scale, &data->output_multiplier, &data->output_shift); } data->quantization_params.zero_point = output->params.zero_point; data->quantization_params.scale = static_cast<double>(output->params.scale); data->input_zero_point = input->params.zero_point; 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
TfLiteStatus EvalHashtableImport(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input_resource_id_tensor = GetInput(context, node, kInputResourceIdTensor); const int resource_id = input_resource_id_tensor->data.i32[0]; const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor); const TfLiteTensor* value_tensor = GetInput(context, node, kValueTensor); 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; }
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
jas_matrix_t *jas_matrix_copy(jas_matrix_t *x) { jas_matrix_t *y; int i; int j; y = jas_matrix_create(x->numrows_, x->numcols_); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; }
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
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 3); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const TfLiteTensor* begin; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBeginTensor, &begin)); const TfLiteTensor* size; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kSizeTensor, &size)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); // Ensure validity of input tensor and its dimension. TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); TF_LITE_ENSURE(context, begin->type == kTfLiteInt32 || begin->type == kTfLiteInt64); TF_LITE_ENSURE(context, size->type == kTfLiteInt32 || size->type == kTfLiteInt64); TF_LITE_ENSURE_EQ(context, NumDimensions(begin), 1); TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1); TF_LITE_ENSURE_EQ(context, NumElements(begin), NumElements(size)); TF_LITE_ENSURE_MSG(context, NumDimensions(input) <= kMaxDim, "Slice op only supports 1D-4D input arrays."); // Postpone allocation of output if any of the indexing tensors is not // constant if (!(IsConstantTensor(begin) && IsConstantTensor(size))) { SetTensorToDynamic(output); return kTfLiteOk; } return ResizeOutputShape(context, input, begin, size, output); }
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 MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) { assertx(m_len != -1); if (whence == SEEK_CUR) { if (offset > 0 && offset < bufferedLen()) { setReadPosition(getReadPosition() + offset); setPosition(getPosition() + offset); return true; } offset += getPosition(); whence = SEEK_SET; } // invalidate the current buffer setWritePosition(0); setReadPosition(0); if (whence == SEEK_SET) { m_cursor = offset; } else { assertx(whence == SEEK_END); m_cursor = m_len + offset; } setPosition(m_cursor); 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
int ecall_restore(const char *input, uint64_t input_len, char **output, uint64_t *output_len) { if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input, input_len) || !asylo::primitives::TrustedPrimitives::IsOutsideEnclave( output_len, sizeof(uint64_t))) { asylo::primitives::TrustedPrimitives::BestEffortAbort( "ecall_restore: input/output found to not be in untrusted memory."); } int result = 0; size_t tmp_output_len; try { result = asylo::Restore(input, static_cast<size_t>(input_len), output, &tmp_output_len); } catch (...) { LOG(FATAL) << "Uncaught exception in enclave"; } if (output_len) { *output_len = static_cast<uint64_t>(tmp_output_len); } return result; }
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
bool DNP3_Base::ParseAppLayer(Endpoint* endp) { bool orig = (endp == &orig_state); binpac::DNP3::DNP3_Flow* flow = orig ? interp->upflow() : interp->downflow(); u_char* data = endp->buffer + PSEUDO_TRANSPORT_INDEX; // The transport layer byte counts as app-layer it seems. int len = endp->pkt_length - 5; // DNP3 Packet : DNP3 Pseudo Link Layer | DNP3 Pseudo Transport Layer | DNP3 Pseudo Application Layer // DNP3 Serial Transport Layer data is always 1 byte. // Get FIN FIR seq field in transport header. // FIR indicate whether the following DNP3 Serial Application Layer is first chunk of bytes or not. // FIN indicate whether the following DNP3 Serial Application Layer is last chunk of bytes or not. int is_first = (endp->tpflags & 0x40) >> 6; // Initial chunk of data in this packet. int is_last = (endp->tpflags & 0x80) >> 7; // Last chunk of data in this packet. int transport = PSEUDO_TRANSPORT_LEN; int i = 0; while ( len > 0 ) { int n = min(len, 16); // Make sure chunk has a correct checksum. if ( ! CheckCRC(n, data, data + n, "app_chunk") ) return false; // Pass on to BinPAC. assert(data + n < endp->buffer + endp->buffer_len); flow->flow_buffer()->BufferData(data + transport, data + n); transport = 0; data += n + 2; len -= n; } if ( is_first ) endp->encountered_first_chunk = true; if ( ! is_first && ! endp->encountered_first_chunk ) { // We lost the first chunk. analyzer->Weird("dnp3_first_application_layer_chunk_missing"); return false; } if ( is_last ) { flow->flow_buffer()->FinishBuffer(); flow->FlowEOF(); ClearEndpointState(orig); } return true; }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
void Compute(OpKernelContext* ctx) override { const auto splits = ctx->input(0).flat<int64_t>(); const auto values = ctx->input(1).flat<Tidx>(); const Tensor& size_t = ctx->input(2); const auto weights = ctx->input(3).flat<T>(); const int64_t weights_size = weights.size(); OP_REQUIRES(ctx, size_t.dims() == 0, errors::InvalidArgument("Shape must be rank 0 but is rank ", size_t.dims())); Tidx size = size_t.scalar<Tidx>()(); OP_REQUIRES( ctx, size >= 0, errors::InvalidArgument("size (", size, ") must be non-negative")); int num_rows = splits.size() - 1; int num_values = values.size(); int batch_idx = 0; OP_REQUIRES(ctx, splits(0) == 0, errors::InvalidArgument("Splits must start with 0, not with ", splits(0))); OP_REQUIRES(ctx, splits(num_rows) == num_values, errors::InvalidArgument( "Splits must end with the number of values, got ", splits(num_rows), " instead of ", num_values)); Tensor* out_t; OP_REQUIRES_OK( ctx, ctx->allocate_output(0, TensorShape({num_rows, size}), &out_t)); functor::SetZeroFunctor<Device, T> fill; fill(ctx->eigen_device<Device>(), out_t->flat<T>()); const auto out = out_t->matrix<T>(); for (int idx = 0; idx < num_values; ++idx) { while (idx >= splits(batch_idx)) { batch_idx++; } Tidx bin = values(idx); OP_REQUIRES(ctx, bin >= 0, errors::InvalidArgument("Input must be non-negative")); if (bin < size) { if (binary_output_) { out(batch_idx - 1, bin) = T(1); } else { T value = (weights_size > 0) ? weights(idx) : T(1); out(batch_idx - 1, bin) += value; } } } }
1
C++
CWE-754
Improper Check for Unusual or Exceptional Conditions
The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.
https://cwe.mitre.org/data/definitions/754.html
safe
int ZlibOutStream::overrun(int itemSize, int nItems) { #ifdef ZLIBOUT_DEBUG vlog.debug("overrun"); #endif if (itemSize > bufSize) throw Exception("ZlibOutStream overrun: max itemSize exceeded"); checkCompressionLevel(); while (end - ptr < itemSize) { zs->next_in = start; zs->avail_in = ptr - start; deflate(Z_NO_FLUSH); // output buffer not full if (zs->avail_in == 0) { offset += ptr - start; ptr = start; } else { // but didn't consume all the data? try shifting what's left to the // start of the buffer. vlog.info("z out buf not full, but in data not consumed"); memmove(start, zs->next_in, ptr - zs->next_in); offset += zs->next_in - start; ptr -= zs->next_in - start; } } 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
int bmp_validate(jas_stream_t *in) { int n; int i; jas_uchar buf[2]; assert(JAS_STREAM_MAXPUTBACK >= 2); /* Read the first two characters that constitute the signature. */ if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) { return -1; } /* Put the characters read back onto the stream. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Did we read enough characters? */ if (n < 2) { return -1; } /* Is the signature correct for the BMP format? */ if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) { return 0; } return -1; }
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
TfLiteStatus ReverseSequenceHelper(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* seq_lengths_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kSeqLengthsTensor, &seq_lengths_tensor)); 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; }
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-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 DependencyOptimizer::SafeToRemoveIdentity(const NodeDef& node) const { if (!IsIdentity(node) && !IsIdentityN(node)) { return true; } if (nodes_to_preserve_.find(node.name()) != nodes_to_preserve_.end()) { return false; } if (!fetch_nodes_known_) { // The output values of this node may be needed. return false; } if (node.input_size() < 1) { // Node lacks input, is invalid return false; } const NodeDef* input = node_map_->GetNode(NodeName(node.input(0))); CHECK(input != nullptr) << "node = " << node.name() << " input = " << node.input(0); // Don't remove Identity nodes corresponding to Variable reads or following // Recv. if (IsVariable(*input) || IsRecv(*input)) { return false; } for (const auto& consumer : node_map_->GetOutputs(node.name())) { if (node.input_size() > 1 && (IsRetval(*consumer) || IsMerge(*consumer))) { return false; } if (IsSwitch(*input)) { for (const string& consumer_input : consumer->input()) { if (consumer_input == AsControlDependency(node.name())) { return false; } } } } return true; }
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 Resize(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteLSHProjectionParams*>(node->builtin_data); TF_LITE_ENSURE(context, NumInputs(node) == 2 || NumInputs(node) == 3); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* hash; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &hash)); TF_LITE_ENSURE_EQ(context, NumDimensions(hash), 2); // Support up to 32 bits. TF_LITE_ENSURE(context, SizeOfDimension(hash, 1) <= 32); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &input)); TF_LITE_ENSURE(context, NumDimensions(input) >= 1); if (NumInputs(node) == 3) { const TfLiteTensor* weight; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &weight)); TF_LITE_ENSURE_EQ(context, NumDimensions(weight), 1); TF_LITE_ENSURE_EQ(context, SizeOfDimension(weight, 0), SizeOfDimension(input, 0)); } TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1); switch (params->type) { case kTfLiteLshProjectionSparse: outputSize->data[0] = SizeOfDimension(hash, 0); break; case kTfLiteLshProjectionDense: outputSize->data[0] = SizeOfDimension(hash, 0) * SizeOfDimension(hash, 1); break; default: return kTfLiteError; } return context->ResizeTensor(context, output, outputSize); }
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
TEST_F(HTTP2DownstreamSessionTest, TestDuplicateRequestStream) { // Send the following: // HEADERS id=1 // HEADERS id=2 // HEADERS id=1 (trailers) // HEADERS id=2 -> contains pseudo-headers after EOM so ignored auto handler2 = addSimpleStrictHandler(); auto handler1 = addSimpleStrictHandler(); auto streamID1 = sendRequest("/withtrailers", 0, false); auto streamID2 = sendRequest(); HTTPHeaders trailers; trailers.add("Foo", "Bar"); clientCodec_->generateTrailers(requests_, streamID1, trailers); clientCodec_->generateEOM(requests_, streamID1); clientCodec_->generateHeader(requests_, streamID2, getGetRequest(), false); handler1->expectHeaders(); handler2->expectHeaders(); handler2->expectEOM(); handler1->expectTrailers(); handler1->expectEOM([&] { handler1->sendReplyWithBody(200, 100); // 2 got an error after EOM, which gets ignored - need a response to // cleanly terminate it handler2->sendReplyWithBody(200, 100); }); handler1->expectDetachTransaction(); handler2->expectDetachTransaction(); flushRequestsAndLoop(); gracefulShutdown(); }
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 Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInput); const TfLiteTensor* axis = GetInput(context, node, kAxis); TfLiteTensor* output = GetOutput(context, node, 0); output->type = input->type; if (IsConstantTensor(axis)) { int axis_value; TF_LITE_ENSURE_OK(context, GetAxisValueFromTensor(context, *axis, &axis_value)); return ExpandTensorDim(context, *input, axis_value, output); } SetTensorToDynamic(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 NotEqualEval(TfLiteContext* context, TfLiteNode* node) { 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)); bool requires_broadcast = !HaveSameShapes(input1, input2); switch (input1->type) { case kTfLiteBool: Comparison<bool, reference_ops::NotEqualFn>(input1, input2, output, requires_broadcast); break; case kTfLiteFloat32: Comparison<float, reference_ops::NotEqualFn>(input1, input2, output, requires_broadcast); break; case kTfLiteInt32: Comparison<int32_t, reference_ops::NotEqualFn>(input1, input2, output, requires_broadcast); break; case kTfLiteInt64: Comparison<int64_t, reference_ops::NotEqualFn>(input1, input2, output, requires_broadcast); break; case kTfLiteUInt8: ComparisonQuantized<uint8_t, reference_ops::NotEqualFn>( input1, input2, output, requires_broadcast); break; case kTfLiteInt8: ComparisonQuantized<int8_t, reference_ops::NotEqualFn>( input1, input2, output, requires_broadcast); break; case kTfLiteString: ComparisonString(reference_ops::StringRefNotEqualFn, input1, input2, output, requires_broadcast); break; default: context->ReportError( context, "Does not support type %d, requires bool|float|int|uint8|string", input1->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
mptctl_eventenable (unsigned long arg) { struct mpt_ioctl_eventenable __user *uarg = (void __user *) arg; struct mpt_ioctl_eventenable karg; MPT_ADAPTER *ioc; int iocnum; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventenable))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_eventenable - " "Unable to read in mpt_ioctl_eventenable 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_eventenable() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventenable called.\n", ioc->name)); if (ioc->events == NULL) { /* Have not yet allocated memory - do so now. */ int sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS); ioc->events = kzalloc(sz, GFP_KERNEL); if (!ioc->events) { printk(MYIOC_s_ERR_FMT ": ERROR - Insufficient memory to add adapter!\n", ioc->name); return -ENOMEM; } ioc->alloc_total += sz; ioc->eventContext = 0; } /* Update the IOC event logging flag. */ ioc->eventTypes = karg.eventTypes; 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
void Compute(OpKernelContext* ctx) override { const Tensor& in0 = ctx->input(0); const Tensor& in1 = ctx->input(1); OP_REQUIRES( ctx, in0.NumElements() == in1.NumElements(), errors::InvalidArgument("The two arguments to a cwise op must have " "same number of elements, got ", in0.NumElements(), " and ", in1.NumElements())); auto in0_flat = in0.flat<Tin>(); auto in1_flat = in1.flat<Tin>(); const Device& eigen_device = ctx->eigen_device<Device>(); Tensor* out = nullptr; if (std::is_same<Tin, Tout>::value) { OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output( {0, 1}, 0, in0.shape(), &out)); } else { OP_REQUIRES_OK(ctx, ctx->allocate_output(0, in0.shape(), &out)); } auto out_flat = out->flat<Tout>(); functor::SimpleBinaryFunctor<Device, Functor>()(eigen_device, out_flat, in0_flat, in1_flat); }
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 Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteMfccParams*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input_wav = GetInput(context, node, kInputTensorWav); const TfLiteTensor* input_rate = GetInput(context, node, kInputTensorRate); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_EQ(context, NumDimensions(input_wav), 3); TF_LITE_ENSURE_EQ(context, NumElements(input_rate), 1); TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32); TF_LITE_ENSURE_TYPES_EQ(context, input_wav->type, output->type); TF_LITE_ENSURE_TYPES_EQ(context, input_rate->type, kTfLiteInt32); TfLiteIntArray* output_size = TfLiteIntArrayCreate(3); output_size->data[0] = input_wav->dims->data[0]; output_size->data[1] = input_wav->dims->data[1]; output_size->data[2] = params->dct_coefficient_count; return context->ResizeTensor(context, output, output_size); }
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
R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) { RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj); if (!se) { return NULL; } se->tag = type; if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) { se->info.obj_val_cp_idx = (ut16) value; } else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) { /*if (bin->offset_sz == 4) { se->info.uninit_offset = value; } else { se->info.uninit_offset = (ut16) value; }*/ se->info.uninit_offset = (ut16) value; } return se; }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength; if (uprv_add32_overflow(oldLength, srcLength, &newLength)) { setToBogus(); return *this; } // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; }
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
void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, jas_matind_t xstart, jas_matind_t ystart, jas_matind_t xend, jas_matind_t yend) { jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_, yend - s1->ystart_ - 1, xend - s1->xstart_ - 1); }
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 Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteMulParams*>(node->builtin_data); 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)); if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) { EvalMul<kernel_type>(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 || output->type == kTfLiteInt16) { TF_LITE_ENSURE_OK( context, EvalQuantized<kernel_type>(context, node, params, data, input1, input2, output)); } else { context->ReportError(context, "Mul only supports FLOAT32, INT32 and quantized UINT8," " INT8 and INT16 now, got %d.", output->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
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteResizeBilinearParams*>(node->builtin_data); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); const TfLiteTensor* size = GetInput(context, node, kSizeTensor); if (IsDynamicTensor(output)) { TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, input, size, output)); } if (output->type == kTfLiteFloat32) { #define TF_LITE_RESIZE_BILINEAR(type, datatype) \ tflite::ResizeBilinearParams op_params; \ op_params.align_corners = params->align_corners; \ op_params.half_pixel_centers = params->half_pixel_centers; \ type::ResizeBilinear(op_params, GetTensorShape(input), \ GetTensorData<datatype>(input), GetTensorShape(size), \ GetTensorData<int32>(size), GetTensorShape(output), \ GetTensorData<datatype>(output)) if (kernel_type == kReference) { TF_LITE_RESIZE_BILINEAR(reference_ops, float); } if (kernel_type == kGenericOptimized || kernel_type == kNeonOptimized) { TF_LITE_RESIZE_BILINEAR(optimized_ops, float); } } else if (output->type == kTfLiteUInt8) { if (kernel_type == kReference) { TF_LITE_RESIZE_BILINEAR(reference_ops, uint8_t); } if (kernel_type == kGenericOptimized || kernel_type == kNeonOptimized) { TF_LITE_RESIZE_BILINEAR(optimized_ops, uint8_t); } } else if (output->type == kTfLiteInt8) { TF_LITE_RESIZE_BILINEAR(reference_ops, int8_t); #undef TF_LITE_RESIZE_BILINEAR } 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 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); 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); }
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 ReverseSequenceImpl(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const TfLiteTensor* seq_lengths_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kSeqLengthsTensor, &seq_lengths_tensor)); const TS* seq_lengths = GetTensorData<TS>(seq_lengths_tensor); auto* params = reinterpret_cast<TfLiteReverseSequenceParams*>(node->builtin_data); int seq_dim = params->seq_dim; int batch_dim = params->batch_dim; TF_LITE_ENSURE(context, seq_dim >= 0); TF_LITE_ENSURE(context, batch_dim >= 0); TF_LITE_ENSURE(context, seq_dim != batch_dim); TF_LITE_ENSURE(context, seq_dim < NumDimensions(input)); TF_LITE_ENSURE(context, batch_dim < NumDimensions(input)); TF_LITE_ENSURE_EQ(context, SizeOfDimension(seq_lengths_tensor, 0), SizeOfDimension(input, batch_dim)); for (int i = 0; i < NumDimensions(seq_lengths_tensor); ++i) { TF_LITE_ENSURE(context, seq_lengths[i] <= SizeOfDimension(input, seq_dim)); } TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); reference_ops::ReverseSequence<T, TS>( seq_lengths, seq_dim, batch_dim, GetTensorShape(input), GetTensorData<T>(input), GetTensorShape(output), GetTensorData<T>(output)); 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 On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { tokens["ESILENCE"] = "CcdiNnPpsTtx"; tokens["SILENCE"] = ConvToStr(cmd.maxsilence); }
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
R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { ut64 offset = 0; if (sz < 8) { return NULL; } RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); offset += 6; if (attr && sz >= offset) { attr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR; attr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset); if (attr->info.annotation_default_attr.default_value) { offset += attr->info.annotation_default_attr.default_value->size; } } r_bin_java_print_annotation_default_attr_summary (attr); return attr; }
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
SpawnPreparationInfo prepareSpawn(const Options &options) { TRACE_POINT(); SpawnPreparationInfo info; prepareChroot(info, options); info.userSwitching = prepareUserSwitching(options); prepareSwitchingWorkingDirectory(info, options); inferApplicationInfo(info); return info; }
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
static int16_t decodeSample(ms_adpcm_state &state, uint8_t code, const int16_t *coefficient) { int linearSample = (state.sample1 * coefficient[0] + state.sample2 * coefficient[1]) >> 8; linearSample += ((code & 0x08) ? (code - 0x10) : code) * state.delta; linearSample = clamp(linearSample, MIN_INT16, MAX_INT16); int delta = (state.delta * adaptationTable[code]) >> 8; if (delta < 16) delta = 16; state.delta = delta; state.sample2 = state.sample1; state.sample1 = linearSample; return static_cast<int16_t>(linearSample); }
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 CLASS panasonic_load_raw() { int row, col, i, j, sh = 0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width) derror(); } } }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
int jas_seq2d_output(jas_matrix_t *matrix, FILE *out) { #define MAXLINELEN 80 int i; int j; jas_seqent_t x; char buf[MAXLINELEN + 1]; char sbuf[MAXLINELEN + 1]; int n; fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix), jas_seq2d_ystart(matrix)); fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix), jas_matrix_numrows(matrix)); buf[0] = '\0'; for (i = 0; i < jas_matrix_numrows(matrix); ++i) { for (j = 0; j < jas_matrix_numcols(matrix); ++j) { x = jas_matrix_get(matrix, i, j); sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "", JAS_CAST(long, x)); n = JAS_CAST(int, strlen(buf)); if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } strcat(buf, sbuf); if (j == jas_matrix_numcols(matrix) - 1) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } } } fputs(buf, out); return 0; }
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
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-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) { 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); TF_LITE_ENSURE(context, num_rows != 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-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
int jas_seq2d_output(jas_matrix_t *matrix, FILE *out) { #define MAXLINELEN 80 int i; int j; jas_seqent_t x; char buf[MAXLINELEN + 1]; char sbuf[MAXLINELEN + 1]; int n; fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix), jas_seq2d_ystart(matrix)); fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix), jas_matrix_numrows(matrix)); buf[0] = '\0'; for (i = 0; i < jas_matrix_numrows(matrix); ++i) { for (j = 0; j < jas_matrix_numcols(matrix); ++j) { x = jas_matrix_get(matrix, i, j); sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "", JAS_CAST(long, x)); n = JAS_CAST(int, strlen(buf)); if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } strcat(buf, sbuf); if (j == jas_matrix_numcols(matrix) - 1) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } } } fputs(buf, out); return 0; }
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
int size() const { return m_str ? m_str->size() : 0; }
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 Polygon::Insert( sal_uInt16 nPos, const Point& rPt ) { ImplMakeUnique(); if( nPos >= mpImplPolygon->mnPoints ) nPos = mpImplPolygon->mnPoints; if (mpImplPolygon->ImplSplit(nPos, 1)) mpImplPolygon->mpPointAry[ nPos ] = rPt; }
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 __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-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
static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { // Skip whitespace while (begin && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } else if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } else if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } }
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
TEST(TensorSliceReaderTest, UnsupportedTensorType) { const string fname = io::JoinPath(testing::TmpDir(), "int32_ref_checkpoint"); TensorSliceWriter writer(fname, CreateTableTensorSliceBuilder); const int32 data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; TensorShape shape({4, 5}); TensorSlice slice = TensorSlice::ParseOrDie("0,2:-"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); TF_CHECK_OK(writer.Finish()); MutateSavedTensorSlices(fname, [](SavedTensorSlices sts) { if (sts.has_meta()) { for (auto& tensor : *sts.mutable_meta()->mutable_tensor()) { tensor.set_type(DT_INT32_REF); } } return sts.SerializeAsString(); }); TensorSliceReader reader(fname, OpenTableTensorSliceReader); TF_CHECK_OK(reader.status()); // The tensor should be present, but loading it should fail due to the // unsupported type. 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
const std::string& get_tenant() const { ceph_assert(t != Wildcard); return u.tenant; }
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 Eval(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast<OpData*>(node->user_data); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); switch (output->type) { case kTfLiteInt32: { // TensorFlow does not support negative for int32. TF_LITE_ENSURE_OK(context, CheckValue(context, input2)); PowImpl<int32_t>(input1, input2, output, data->requires_broadcast); break; } case kTfLiteFloat32: { PowImpl<float>(input1, input2, output, data->requires_broadcast); break; } default: { context->ReportError(context, "Unsupported data type: %d", output->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
String StringUtil::Crypt(const String& input, const char *salt /* = "" */) { if (salt && salt[0] == '\0') { raise_notice("crypt(): No salt parameter was specified." " You must use a randomly generated salt and a strong" " hash function to produce a secure hash."); } return String(string_crypt(input.c_str(), salt), AttachString); }
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
static void HeaderMapImplGetByteSize(benchmark::State& state) { HeaderMapImpl headers; addDummyHeaders(headers, state.range(0)); uint64_t size = 0; for (auto _ : state) { size += headers.byteSize(); } benchmark::DoNotOptimize(size); }
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
Status ValidateInputTensor(const Tensor& tensor, const std::string& tensor_name, const Tensor& rhs) { const int ndims = rhs.dims(); if (tensor.dims() != ndims) { return errors::InvalidArgument(tensor_name, " must have same rank as rhs, but got ", tensor.dims(), " and ", ndims); } for (int i = 0; i < ndims - 2; i++) { if (tensor.dim_size(i) != rhs.dim_size(i)) { return errors::InvalidArgument( tensor_name, " must have same outer dimensions as rhs, but for index ", i, ", got ", tensor.dim_size(i), " and ", rhs.dim_size(i)); } } if (tensor.dim_size(ndims - 2) != 1) { return errors::InvalidArgument( tensor_name, "'s second-to-last dimension must be 1, but got ", tensor.dim_size(ndims - 2)); } if (tensor.dim_size(ndims - 1) != rhs.dim_size(ndims - 2)) { return errors::InvalidArgument(tensor_name, "'s last dimension size must be rhs's " "second-to-last dimension size, but got ", tensor.dim_size(ndims - 1), " and ", rhs.dim_size(ndims - 2)); } return Status::OK(); }
1
C++
CWE-354
Improper Validation of Integrity Check Value
The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
safe
BOOL nego_read_request(rdpNego* nego, wStream* s) { BYTE li; BYTE type; UINT16 length; if (!tpkt_read_header(s, &length)) return FALSE; if (!tpdu_read_connection_request(s, &li, length)) return FALSE; if (li != Stream_GetRemainingLength(s) + 6) { WLog_ERR(TAG, "Incorrect TPDU length indicator."); return FALSE; } if (!nego_read_request_token_or_cookie(nego, s)) { WLog_ERR(TAG, "Failed to parse routing token or cookie."); return FALSE; } if (Stream_GetRemainingLength(s) >= 8) { /* rdpNegData (optional) */ Stream_Read_UINT8(s, type); /* Type */ if (type != TYPE_RDP_NEG_REQ) { WLog_ERR(TAG, "Incorrect negotiation request type %" PRIu8 "", type); return FALSE; } if (!nego_process_negotiation_request(nego, s)) return FALSE; } return tpkt_ensure_stream_consumed(s, length); }
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
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[100]; Jsi_NumberItoA10(key, unibuf, sizeof(unibuf)); Jsi_ObjInsert(interp, obj, unibuf, val, flags); return JSI_OK; }
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 Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 3); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* begin = GetInput(context, node, kBeginTensor); const TfLiteTensor* size = GetInput(context, node, kSizeTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); // Ensure validity of input tensor and its dimension. TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); TF_LITE_ENSURE(context, begin->type == kTfLiteInt32 || begin->type == kTfLiteInt64); TF_LITE_ENSURE(context, size->type == kTfLiteInt32 || size->type == kTfLiteInt64); TF_LITE_ENSURE_EQ(context, NumDimensions(begin), 1); TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1); TF_LITE_ENSURE_EQ(context, NumElements(begin), NumElements(size)); TF_LITE_ENSURE_MSG(context, NumDimensions(input) <= kMaxDim, "Slice op only supports 1D-4D input arrays."); // Postpone allocation of output if any of the indexing tensors is not // constant if (!(IsConstantTensor(begin) && IsConstantTensor(size))) { SetTensorToDynamic(output); return kTfLiteOk; } return ResizeOutputShape(context, input, begin, size, output); }
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) { auto* params = reinterpret_cast<TfLiteDivParams*>(node->builtin_data); 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)); // TODO(b/193904910): This can written with C++ templates #define TF_LITE_CHECK_DIV_NON_ZERO(data_type) \ const auto* input2_data = GetTensorData<data_type>(input2); \ const size_t input2_elements = input2->bytes / sizeof(data_type); \ for (size_t i = 0; i < input2_elements; i++) { \ TF_LITE_ENSURE(context, input2_data[i] != 0); \ } if (output->type == kTfLiteFloat32) { // Div by zero seems ok in this case, just like in TF case infinities are // returned. So we don't do a check at this point. EvalDiv<kernel_type>(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteInt32) { TF_LITE_CHECK_DIV_NON_ZERO(int32_t); EvalDiv<kernel_type>(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteUInt8) { TF_LITE_CHECK_DIV_NON_ZERO(uint8_t); TF_LITE_ENSURE_OK( context, EvalQuantized<kernel_type>(context, node, params, data, input1, input2, output)); } else { context->ReportError( context, "Div only supports FLOAT32, INT32 and quantized UINT8 now, got %d.", output->type); return kTfLiteError; } #undef TF_LITE_CHECK_DIV_NON_ZERO return kTfLiteOk; }
1
C++
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
Array& ObjectData::reserveProperties(int numDynamic /* = 2 */) { if (getAttribute(HasDynPropArr)) { return dynPropArray(); } auto const allocsz = MixedArray::computeAllocBytesFromMaxElms(numDynamic); if (UNLIKELY(allocsz > kMaxSmallSize && tl_heap->preAllocOOM(allocsz))) { check_non_safepoint_surprise(); } return setDynPropArray( Array::attach(MixedArray::MakeReserveMixed(numDynamic)) ); }
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
CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2, value n) { memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n)); return Val_unit; }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
bool AdminRequestHandler::handleDumpStaticStringsRequest( const std::string& /*cmd*/, const std::string& filename) { auto const& list = lookupDefinedStaticStrings(); std::ofstream out(filename.c_str()); SCOPE_EXIT { out.close(); }; for (auto item : list) { out << formatStaticString(item); 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; }
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(context, NumInputs(node) == 1 || NumInputs(node) == 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); // Always postpone sizing string tensors, even if we could in principle // calculate their shapes now. String tensors don't benefit from having their // shapes precalculated because the actual memory can only be allocated after // we know all the content. TfLiteTensor* output = GetOutput(context, node, kOutputTensor); if (output->type != kTfLiteString) { if (NumInputs(node) == 1 || IsConstantTensor(GetInput(context, node, kShapeTensor))) { TF_LITE_ENSURE_OK(context, ResizeOutput(context, node)); } else { SetTensorToDynamic(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
RemoteFsDevice::Details RemoteDevicePropertiesWidget::details() { int t=type->itemData(type->currentIndex()).toInt(); RemoteFsDevice::Details det; det.name=name->text().trimmed(); switch (t) { case Type_SshFs: { det.url.setHost(sshHost->text().trimmed()); det.url.setUserName(sshUser->text().trimmed()); det.url.setPath(sshFolder->text().trimmed()); det.url.setPort(sshPort->value()); det.url.setScheme(RemoteFsDevice::constSshfsProtocol); det.extraOptions=sshExtra->text().trimmed(); break; } case Type_File: { QString path=fileFolder->text().trimmed(); if (path.isEmpty()) { path="/"; } det.url.setPath(path); det.url.setScheme(RemoteFsDevice::constFileProtocol); break; } } return det; }
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
int linenoiseHistorySave(const char* filename) { FILE* fp; #if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE int fd = open(filename, O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) { // report errno somehow? return -1; } fp = fdopen(fd, "wt"); #else fp = fopen(filename, "wt"); #endif // _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE if (fp == NULL) { return -1; } for (int j = 0; j < historyLen; ++j) { if (history[j][0] != '\0') { fprintf(fp, "%s\n", history[j]); } } fclose(fp); // Also causes fd to be closed. return 0; }
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
void Init(void) { for(int i = 0;i < 15;i++) { X[i].Init(); M[i].Init(); } }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
MONGO_EXPORT int bson_append_finish_object( bson *b ) { char *start; int i; if ( bson_ensure_space( b, 1 ) == BSON_ERROR ) return BSON_ERROR; bson_append_byte( b , 0 ); start = b->data + b->stack[ --b->stackPos ]; i = b->cur - start; bson_little_endian32( start, &i ); return BSON_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
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers); if (IsDynamicTensor(output)) { TF_LITE_ENSURE_OK(context, ResizeOutput(context, node)); } switch (output->type) { case kTfLiteFloat32: Tile<float>(*(input->dims), input, multipliers, output); break; case kTfLiteUInt8: Tile<uint8_t>(*(input->dims), input, multipliers, output); break; case kTfLiteInt32: Tile<int32_t>(*(input->dims), input, multipliers, output); break; case kTfLiteInt64: Tile<int64_t>(*(input->dims), input, multipliers, output); break; case kTfLiteString: { DynamicBuffer buffer; TileString(*(input->dims), input, multipliers, &buffer, output); buffer.WriteToTensor(output, /*new_shape=*/nullptr); break; } case kTfLiteBool: Tile<bool>(*(input->dims), input, multipliers, output); break; default: context->ReportError(context, "Type '%s' is not supported by tile.", TfLiteTypeGetName(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
void PacketReader::getLabelFromContent(const vector<uint8_t>& content, uint16_t& frompos, string& ret, int recurs, size_t& wirelength) { if(recurs > 100) // the forward reference-check below should make this test 100% obsolete throw MOADNSException("Loop"); int pos = frompos; // it is tempting to call reserve on ret, but it turns out it creates a malloc/free storm in the loop for(;;) { unsigned char labellen=content.at(frompos++); wirelength++; if (wirelength > 255) { throw MOADNSException("Overly long DNS name ("+lexical_cast<string>(wirelength)+")"); } if(!labellen) { if(ret.empty()) ret.append(1,'.'); break; } else if((labellen & 0xc0) == 0xc0) { uint16_t offset=256*(labellen & ~0xc0) + (unsigned int)content.at(frompos++) - sizeof(dnsheader); // cout<<"This is an offset, need to go to: "<<offset<<endl; if(offset >= pos) throw MOADNSException("forward reference during label decompression"); /* the compression pointer does not count into the wire length */ return getLabelFromContent(content, offset, ret, ++recurs, --wirelength); } else if(labellen > 63) throw MOADNSException("Overly long label during label decompression ("+lexical_cast<string>((unsigned int)labellen)+")"); else { if (wirelength + labellen > 255) { throw MOADNSException("Overly long DNS name ("+lexical_cast<string>(wirelength)+")"); } wirelength += labellen; // XXX FIXME THIS MIGHT BE VERY SLOW! for(string::size_type n = 0 ; n < labellen; ++n, frompos++) { if(content.at(frompos)=='.' || content.at(frompos)=='\\') { ret.append(1, '\\'); ret.append(1, content[frompos]); } else if(content.at(frompos)==' ') { ret+="\\032"; } else ret.append(1, content[frompos]); } ret.append(1,'.'); } if (ret.length() > 1024) throw MOADNSException("Total name too long"); } }
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
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 = GetInput(context, node, kInputTensor); const TfLiteTensor* size = GetInput(context, node, kSizeTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); // TODO(ahentz): Our current implementations rely on the inputs being 4D. TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1); TF_LITE_ENSURE_EQ(context, size->type, kTfLiteInt32); // ResizeBilinear creates a float tensor even when the input is made of // integers. output->type = input->type; if (!IsConstantTensor(size)) { SetTensorToDynamic(output); return kTfLiteOk; } // Ensure params are valid. auto* params = reinterpret_cast<TfLiteResizeBilinearParams*>(node->builtin_data); if (params->half_pixel_centers && params->align_corners) { context->ReportError( context, "If half_pixel_centers is True, align_corners must be False."); return kTfLiteError; } return ResizeOutputTensor(context, input, size, output); }
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 GenericPrepare(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, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->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
inline bool AveragePool(const float* input_data, const Dims<4>& input_dims, int stride_width, int stride_height, int pad_width, int pad_height, int kwidth, int kheight, float output_activation_min, float output_activation_max, float* output_data, const Dims<4>& output_dims) { tflite::PoolParams params; params.stride_height = stride_height; params.stride_width = stride_width; params.filter_height = kheight; params.filter_width = kwidth; params.padding_values.height = pad_height; params.padding_values.width = pad_width; params.float_activation_min = output_activation_min; params.float_activation_max = output_activation_max; return AveragePool(params, DimsToShape(input_dims), input_data, DimsToShape(output_dims), output_data); }
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
int TLSOutStream::overrun(int itemSize, int nItems) { if (itemSize > bufSize) throw Exception("TLSOutStream overrun: max itemSize exceeded"); flush(); 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 GenericPrepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TfLiteTensor* output = GetOutput(context, node, 0); const TfLiteTensor* input = GetInput(context, node, 0); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); int batches = input->dims->data[0]; int height = input->dims->data[1]; int width = input->dims->data[2]; int channels_out = input->dims->data[3]; // Matching GetWindowedOutputSize in TensorFlow. auto padding = params->padding; int out_width, out_height; data->padding = ComputePaddingHeightWidth( params->stride_height, params->stride_width, 1, 1, height, width, params->filter_height, params->filter_width, padding, &out_height, &out_width); if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) { if (pool_type == kAverage || pool_type == kMax) { TFLITE_DCHECK_LE(std::abs(input->params.scale - output->params.scale), 1.0e-6); TFLITE_DCHECK_EQ(input->params.zero_point, output->params.zero_point); } if (pool_type == kL2) { // We currently don't have a quantized implementation of L2Pool TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32); } } TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = batches; output_size->data[1] = out_height; output_size->data[2] = out_width; output_size->data[3] = channels_out; return context->ResizeTensor(context, output, output_size); }
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 Ogg::XiphComment::parse(const ByteVector &data) { // The first thing in the comment data is the vendor ID length, followed by a // UTF8 string with the vendor ID. int pos = 0; int vendorLength = data.mid(0, 4).toUInt(false); pos += 4; d->vendorID = String(data.mid(pos, vendorLength), String::UTF8); pos += vendorLength; // Next the number of fields in the comment vector. int commentFields = data.mid(pos, 4).toUInt(false); pos += 4; for(int i = 0; i < commentFields; i++) { // Each comment field is in the format "KEY=value" in a UTF8 string and has // 4 bytes before the text starts that gives the length. int commentLength = data.mid(pos, 4).toUInt(false); pos += 4; String comment = String(data.mid(pos, commentLength), String::UTF8); pos += commentLength; int commentSeparatorPosition = comment.find("="); String key = comment.substr(0, commentSeparatorPosition); String value = comment.substr(commentSeparatorPosition + 1); addField(key, value, false); } }
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
void RunOneAveragePoolTest(const PoolParams& params, const RuntimeShape& input_shape, const int8* input_data, const RuntimeShape& output_shape) { const int buffer_size = output_shape.FlatSize(); std::vector<int8> optimized_averagePool_output(buffer_size); std::vector<int8> reference_averagePool_output(buffer_size); bool reference_success = reference_integer_ops::AveragePool( params, input_shape, input_data, output_shape, reference_averagePool_output.data()); bool optimized_success = optimized_integer_ops::AveragePool( params, input_shape, input_data, output_shape, optimized_averagePool_output.data()); EXPECT_TRUE(reference_success); EXPECT_TRUE(optimized_success); for (int i = 0; i < buffer_size; i++) { EXPECT_TRUE(reference_averagePool_output[i] == optimized_averagePool_output[i]); } }
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
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 3); OpContext op_context(context, node); TF_LITE_ENSURE_EQ(context, NumOutputs(node), op_context.params->num_splits); auto input_type = op_context.input->type; TF_LITE_ENSURE(context, input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 || input_type == kTfLiteInt16 || input_type == kTfLiteInt32 || input_type == kTfLiteInt64 || input_type == kTfLiteInt8); for (int i = 0; i < NumOutputs(node); ++i) { TfLiteTensor* tensor; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor)); tensor->type = input_type; } auto size_splits = op_context.size_splits; TF_LITE_ENSURE_EQ(context, NumDimensions(size_splits), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), NumElements(size_splits)); // If we know the contents of the 'size_splits' tensor and the 'axis' tensor, // resize all outputs. Otherwise, wait until Eval(). if (IsConstantTensor(op_context.size_splits) && IsConstantTensor(op_context.axis)) { return ResizeOutputTensors(context, node, op_context.input, op_context.size_splits, op_context.axis); } else { return UseDynamicOutputTensors(context, node); } }
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 *Sys_LoadDll( const char *name, qboolean useSystemLib ) { void *dllhandle = NULL; // Don't load any DLLs that end with the pk3 extension if ( COM_CompareExtension( name, ".pk3" ) ) { Com_Printf( S_COLOR_YELLOW "WARNING: Rejecting DLL named \"%s\"", name ); return NULL; } if ( useSystemLib ) { Com_Printf( "Trying to load \"%s\"...\n", name ); dllhandle = Sys_LoadLibrary( name ); if ( dllhandle ) return dllhandle; Com_Printf( "%s(%s) failed: \"%s\"\n", __FUNCTION__, name, Sys_LibraryError() ); } const char *binarypath = Sys_BinaryPath(); const char *basepath = Cvar_VariableString( "fs_basepath" ); if ( !*binarypath ) binarypath = "."; const char *searchPaths[] = { binarypath, basepath, }; const size_t numPaths = ARRAY_LEN( searchPaths ); for ( size_t i = 0; i < numPaths; i++ ) { const char *libDir = searchPaths[i]; if ( !libDir[0] ) continue; Com_Printf( "Trying to load \"%s\" from \"%s\"...\n", name, libDir ); char *fn = va( "%s%c%s", libDir, PATH_SEP, name ); dllhandle = Sys_LoadLibrary( fn ); if ( dllhandle ) return dllhandle; Com_Printf( "%s(%s) failed: \"%s\"\n", __FUNCTION__, fn, Sys_LibraryError() ); } return NULL; }
1
C++
NVD-CWE-noinfo
null
null
null
safe
BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize) : bufferSize_(bufferSize), buffer_(new unsigned char[bufferSize]), ptr_(buffer_.get() + bufferSize) { // refill on first use call_once(flag, [this]() { detail::AtFork::registerHandler( this, /*prepare*/ []() { return true; }, /*parent*/ []() {}, /*child*/ []() { using Single = SingletonThreadLocal<BufferedRandomDevice, RandomTag>; auto& t = Single::get(); // Clear out buffered data on fork. // // Ensure child and parent do not share same entropy pool. t.ptr_ = t.buffer_.get() + t.bufferSize_; }); }); }
1
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
safe
Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const { DoQuickSanityCheck(); ModularArithmetic modn(m_n); Integer r, rInv; do { // do this in a loop for people using small numbers for testing r.Randomize(rng, Integer::One(), m_n - Integer::One()); 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; }
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
bool IsReshapeOpSupported(const TfLiteRegistration* registration, const TfLiteNode* node, TfLiteContext* context, int coreml_version) { if (coreml_version >= 3) { return false; } if (node->inputs->size == 1) { const auto* params = reinterpret_cast<TfLiteReshapeParams*>(node->builtin_data); return params->num_dimensions == 3 || params->num_dimensions == 4; } const int kShapeTensor = 1; const auto* shape = GetInput(context, node, kShapeTensor); if (shape->allocation_type != kTfLiteMmapRo) { TF_LITE_KERNEL_LOG(context, "Reshape has non-const shape."); return false; } const bool is_shape_tensor = shape->dims->size == 1 && shape->type == kTfLiteInt32; return is_shape_tensor && (shape->dims->data[0] == 3 || shape->dims->data[0] == 4); }
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 CheckInputs(Tensor group_size_t, Tensor group_key_t) { if (group_size_t.dims() > 0) { return errors::InvalidArgument( "Unexpected dimensions on input group_size. " "It shoulbe a scalar, got tensor with shape ", group_size_t.shape().DebugString()); } if (group_key_t.dims() > 0) { return errors::InvalidArgument( "Unexpected dimensions on input group_key, got ", group_key_t.shape().DebugString()); } auto group_size = group_size_t.unaligned_flat<int32>()(0); if (group_size <= 0) { return errors::InvalidArgument( "group_size must be positive integer but got ", group_size); } return Status::OK(); }
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
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteL2NormParams*>(node->builtin_data); 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(context, NumDimensions(input) <= 4); TF_LITE_ENSURE(context, output->type == kTfLiteFloat32 || output->type == kTfLiteUInt8 || output->type == kTfLiteInt8); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { TF_LITE_ENSURE_EQ(context, output->params.scale, (1. / 128.)); if (output->type == kTfLiteUInt8) { TF_LITE_ENSURE_EQ(context, output->params.zero_point, 128); } if (output->type == kTfLiteInt8) { TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); } } // TODO(ahentz): For some reason our implementations don't support // activations. TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone); TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->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
MpdCantataMounterInterface * RemoteFsDevice::mounter() { if (!mounterIface) { if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) { QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName()); } mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(), "/Mounter", QDBusConnection::systemBus(), this); connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int))); connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int))); } return mounterIface; }
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
TEST_F(HeaderTableTests, reduce_capacity) { HPACKHeader accept("accept-encoding", "gzip"); uint32_t max = 10; uint32_t capacity = accept.bytes() * max; HeaderTable table(capacity); EXPECT_GT(table.length(), max); // fill the table for (size_t i = 0; i < max; i++) { EXPECT_EQ(table.add(accept), true); } // change capacity table.setCapacity(capacity / 2); EXPECT_EQ(table.size(), max / 2); EXPECT_EQ(table.bytes(), capacity / 2); }
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
TEST(ImmutableConstantOpTest, FromFileStringUnimplmented) { const TensorShape kFileTensorShape({1}); Env* env = Env::Default(); auto root = Scope::NewRootScope().ExitOnError(); string bad_file; TF_ASSERT_OK(CreateTempFileBadString(env, '\xe2', 128, "bad_e2", &bad_file)); auto result = ops::ImmutableConst(root, DT_STRING, kFileTensorShape, bad_file); GraphDef graph_def; TF_ASSERT_OK(root.ToGraphDef(&graph_def)); SessionOptions session_options; session_options.env = Env::Default(); std::unique_ptr<Session> session(NewSession(session_options)); ASSERT_TRUE(session != nullptr) << "Failed to create session"; TF_ASSERT_OK(session->Create(graph_def)) << "Can't create test graph"; std::vector<Tensor> outputs; // Check that the run returned error. EXPECT_EQ( session->Run({}, {result.node()->name() + ":0"}, {}, &outputs).code(), error::UNIMPLEMENTED); }
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
RemoteDevicePropertiesWidget::RemoteDevicePropertiesWidget(QWidget *parent) : QWidget(parent) , modified(false) , saveable(false) { setupUi(this); if (qobject_cast<QTabWidget *>(parent)) { verticalLayout->setMargin(4); } type->addItem(tr("Samba Share"), (int)Type_Samba); type->addItem(tr("Samba Share (Auto-discover host and port)"), (int)Type_SambaAvahi); type->addItem(tr("Secure Shell (sshfs)"), (int)Type_SshFs); type->addItem(tr("Locally Mounted Folder"), (int)Type_File); }
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
TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node, TfLiteMulParams* params, OpData* data) { const TfLiteTensor* input1 = GetInput(context, node, kInput1Tensor); TF_LITE_ENSURE(context, input1 != nullptr); const TfLiteTensor* input2 = GetInput(context, node, kInput2Tensor); TF_LITE_ENSURE(context, input2 != nullptr); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE(context, output != nullptr); TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type); if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized( context, params->activation, output, &data->output_activation_min, &data->output_activation_max)); double real_multiplier = static_cast<double>(input1->params.scale) * static_cast<double>(input2->params.scale) / static_cast<double>(output->params.scale); QuantizeMultiplier(real_multiplier, &data->output_multiplier, &data->output_shift); data->input1_zero_point = input1->params.zero_point; data->input2_zero_point = input2->params.zero_point; data->output_zero_point = output->params.zero_point; } else { CalculateActivationRange(params->activation, &data->output_activation_min_f32, &data->output_activation_max_f32); } 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
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* data; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputDataTensor, &data)); const TfLiteTensor* segment_ids; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputSegmentIdsTensor, &segment_ids)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); if (IsDynamicTensor(output)) { TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, data, segment_ids, output)); } #define TF_LITE_SEGMENT_SUM(dtype) \ reference_ops::SegmentSum<dtype>( \ GetTensorShape(data), GetTensorData<dtype>(data), \ GetTensorShape(segment_ids), GetTensorData<int32_t>(segment_ids), \ GetTensorShape(output), GetTensorData<dtype>(output)); switch (data->type) { case kTfLiteInt32: TF_LITE_SEGMENT_SUM(int32_t); break; case kTfLiteFloat32: TF_LITE_SEGMENT_SUM(float); break; default: context->ReportError(context, "Currently SegmentSum doesn't support type: %s", TfLiteTypeGetName(data->type)); return kTfLiteError; } #undef TF_LITE_SEGMENT_SUM 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 TemporaryFile::deleteTemporaryFile() const { // Have a few attempts at deleting the file before giving up.. for (int i = 5; --i >= 0;) { if (temporaryFile.deleteFile()) return true; Thread::sleep (50); } return false; }
0
C++
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.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 = GetOutput(context, node, 0); const TfLiteTensor* input = GetInput(context, node, 0); 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; }
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 AllocatesOpaqueHandle() const override { return true; }
1
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
safe
char* HexOutStream::binToHexStr(const char* data, int length) { char* buffer = new char[length*2+1]; for (int i=0; i<length; i++) { buffer[i*2] = intToHex((data[i] >> 4) & 15); buffer[i*2+1] = intToHex((data[i] & 15)); if (!buffer[i*2] || !buffer[i*2+1]) { delete [] buffer; return 0; } } buffer[length*2] = 0; return buffer; }
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 GreaterEqualEval(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::GreaterEqualFn>(input1, input2, output, requires_broadcast); break; case kTfLiteInt32: Comparison<int32_t, reference_ops::GreaterEqualFn>(input1, input2, output, requires_broadcast); break; case kTfLiteInt64: Comparison<int64_t, reference_ops::GreaterEqualFn>(input1, input2, output, requires_broadcast); break; case kTfLiteUInt8: ComparisonQuantized<uint8_t, reference_ops::GreaterEqualFn>( input1, input2, output, requires_broadcast); break; case kTfLiteInt8: ComparisonQuantized<int8_t, reference_ops::GreaterEqualFn>( 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-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 skip(Protocol_& prot, TType arg_type) { switch (arg_type) { case TType::T_BOOL: { bool boolv; prot.readBool(boolv); return; } case TType::T_BYTE: { int8_t bytev; prot.readByte(bytev); return; } case TType::T_I16: { int16_t i16; prot.readI16(i16); return; } case TType::T_I32: { int32_t i32; prot.readI32(i32); return; } case TType::T_I64: { int64_t i64; prot.readI64(i64); return; } case TType::T_DOUBLE: { double dub; prot.readDouble(dub); return; } case TType::T_FLOAT: { float flt; prot.readFloat(flt); return; } case TType::T_STRING: { std::string str; prot.readBinary(str); return; } case TType::T_STRUCT: { std::string name; int16_t fid; TType ftype; prot.readStructBegin(name); while (true) { prot.readFieldBegin(name, ftype, fid); if (ftype == TType::T_STOP) { break; } apache::thrift::skip(prot, ftype); prot.readFieldEnd(); } prot.readStructEnd(); return; } case TType::T_MAP: { TType keyType; TType valType; uint32_t i, size; prot.readMapBegin(keyType, valType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, keyType); apache::thrift::skip(prot, valType); } prot.readMapEnd(); return; } case TType::T_SET: { TType elemType; uint32_t i, size; prot.readSetBegin(elemType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, elemType); } prot.readSetEnd(); return; } case TType::T_LIST: { TType elemType; uint32_t i, size; prot.readListBegin(elemType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, elemType); } prot.readListEnd(); return; } default: return; } }
0
C++
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
vulnerable
void Compute(OpKernelContext* context) override { // Get the input Tensors. OpInputList params_nested_splits_in; OP_REQUIRES_OK(context, context->input_list("params_nested_splits", &params_nested_splits_in)); OP_REQUIRES( context, params_nested_splits_in.size() > 0, errors::InvalidArgument("params_nested_splits must be non empty")); const Tensor& params_dense_values_in = context->input(params_nested_splits_in.size()); const Tensor& indices_in = context->input(params_nested_splits_in.size() + 1); OP_REQUIRES(context, params_nested_splits_in[0].dims() > 0, errors::InvalidArgument("Split tensors must not be scalars")); SPLITS_TYPE num_params = params_nested_splits_in[0].dim_size(0) - 1; OP_REQUIRES_OK(context, ValidateIndices(indices_in, num_params)); OP_REQUIRES(context, params_dense_values_in.dims() > 0, errors::InvalidArgument("params.rank must be nonzero")); SPLITS_TYPE num_params_dense_values = params_dense_values_in.dim_size(0); // Calculate the `splits`, and store the value slices that we need to // copy in `value_slices`. std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>> value_slices; SPLITS_TYPE num_values = 0; std::vector<std::vector<SPLITS_TYPE>> out_splits; OP_REQUIRES_OK(context, MakeSplits(indices_in, params_nested_splits_in, num_params_dense_values, &out_splits, &value_slices, &num_values)); // Write the output tensors. OP_REQUIRES_OK(context, WriteSplits(out_splits, context)); OP_REQUIRES_OK(context, WriteValues(params_dense_values_in, value_slices, out_splits.size(), num_values, context)); }
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
public static boolean includes( final Collection<String> patterns, final URI uri ) { checkNotNull( "patterns", patterns ); checkNotNull( "uri", uri ); return matches( patterns, uri ); }
1
C++
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
safe
jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; if (numrows < 0 || numcols < 0) { return 0; } if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { return 0; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = numrows * numcols; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { jas_matrix_destroy(matrix); return 0; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { jas_matrix_destroy(matrix); return 0; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; }
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
Array HHVM_FUNCTION(compact, const Variant& varname, const Array& args /* = null array */) { raise_disallowed_dynamic_call("compact should not be called dynamically"); Array ret = Array::attach(PackedArray::MakeReserve(args.size() + 1)); VarEnv* v = g_context->getOrCreateVarEnv(); if (v) { compact(v, ret, varname); compact(v, ret, args); } 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