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
int64_t MemFile::readImpl(char *buffer, int64_t length) { assertx(m_len != -1); assertx(length > 0); assertx(m_cursor >= 0); int64_t remaining = m_len - m_cursor; if (remaining < length) length = remaining; if (length > 0) { memcpy(buffer, (const void *)(m_data + m_cursor), length); m_cursor += length; return length; } return 0; }
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(PlaintextRecordTest, TestSkipOversizedRecord) { read_.setSkipEncryptedRecords(true); addToQueue("170301fffb"); auto longBuf = IOBuf::create(0xfffb); longBuf->append(0xfffb); queue_.append(std::move(longBuf)); EXPECT_FALSE(read_.read(queue_).hasValue()); EXPECT_TRUE(queue_.empty()); }
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
static unsigned short get_ushort(const unsigned char *data) { unsigned short val = *(const unsigned short *)data; #ifdef OPJ_BIG_ENDIAN val = ((val & 0xffU) << 8) | (val >> 8); #endif return val; }
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 CheckAuthTest::TestValidToken(const std::string &auth_token, const std::string &user_info) { EXPECT_CALL(*raw_request_, FindHeader("x-goog-iap-jwt-assertion", _)) .WillOnce(Invoke([](const std::string &, std::string *token) { *token = ""; return false; })); EXPECT_CALL(*raw_request_, FindHeader(kAuthHeader, _)) .WillOnce(Invoke([auth_token](const std::string &, std::string *token) { *token = std::string(kBearer) + auth_token; return true; })); EXPECT_CALL(*raw_request_, SetAuthToken(auth_token)).Times(1); EXPECT_CALL(*raw_env_, DoRunHTTPRequest(_)) .Times(2) .WillOnce(Invoke([](HTTPRequest *req) { EXPECT_EQ(req->url(), kIssuer1OpenIdUrl); std::string body(kOpenIdContent); std::map<std::string, std::string> empty; req->OnComplete(Status::OK, std::move(empty), std::move(body)); })) .WillOnce(Invoke([](HTTPRequest *req) { EXPECT_EQ(req->url(), kIssuer1PubkeyUrl); std::string body(kPubkey); std::map<std::string, std::string> empty; req->OnComplete(Status::OK, std::move(empty), std::move(body)); })); std::cout << "need be replaced: " << user_info << std::endl; EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo, user_info)) .WillOnce(Return(utils::Status::OK)); CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); }); }
0
C++
CWE-290
Authentication Bypass by Spoofing
This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks.
https://cwe.mitre.org/data/definitions/290.html
vulnerable
const FieldID& activeUnionMemberId(const void* object, ptrdiff_t offset) { return *reinterpret_cast<const FieldID*>( offset + static_cast<const char*>(object)); }
0
C++
CWE-763
Release of Invalid Pointer or Reference
The application attempts to return a memory resource to the system, but calls the wrong release function or calls the appropriate release function incorrectly.
https://cwe.mitre.org/data/definitions/763.html
vulnerable
jas_matrix_t *jas_seq2d_input(FILE *in) { jas_matrix_t *matrix; int i; int j; long x; int numrows; int numcols; int xoff; int yoff; if (fscanf(in, "%d %d", &xoff, &yoff) != 2) return 0; if (fscanf(in, "%d %d", &numcols, &numrows) != 2) return 0; if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows))) return 0; if (jas_matrix_numrows(matrix) != numrows || jas_matrix_numcols(matrix) != numcols) { abort(); } /* Get matrix data. */ for (i = 0; i < jas_matrix_numrows(matrix); i++) { for (j = 0; j < jas_matrix_numcols(matrix); j++) { if (fscanf(in, "%ld", &x) != 1) { jas_matrix_destroy(matrix); return 0; } jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x)); } } 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
Http::FilterMetadataStatus Context::onRequestMetadata() { if (!wasm_->onRequestMetadata_) { return Http::FilterMetadataStatus::Continue; } if (wasm_->onRequestMetadata_(this, id_).u64_ == 0) { return Http::FilterMetadataStatus::Continue; } return Http::FilterMetadataStatus::Continue; // This is currently the only return code. }
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
Status CalculateOutputIndexValueRowID( const RowPartitionTensor& value_rowids, const vector<INDEX_TYPE>& parent_output_index, INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size, vector<INDEX_TYPE>* result) { const INDEX_TYPE index_size = value_rowids.size(); result->reserve(index_size); if (index_size == 0) { return Status::OK(); } INDEX_TYPE current_output_column = 0; INDEX_TYPE current_value_rowid = value_rowids(0); if (current_value_rowid >= parent_output_index.size()) { return errors::InvalidArgument( "Got current_value_rowid=", current_value_rowid, " which is not less than ", parent_output_index.size()); } INDEX_TYPE current_output_index = parent_output_index[current_value_rowid]; result->push_back(current_output_index); for (INDEX_TYPE i = 1; i < index_size; ++i) { INDEX_TYPE next_value_rowid = value_rowids(i); if (next_value_rowid == current_value_rowid) { if (current_output_index >= 0) { ++current_output_column; if (current_output_column < output_size) { current_output_index += output_index_multiplier; } else { current_output_index = -1; } } } else { current_output_column = 0; current_value_rowid = next_value_rowid; if (next_value_rowid >= parent_output_index.size()) { return errors::InvalidArgument( "Got next_value_rowid=", next_value_rowid, " which is not less than ", parent_output_index.size()); } current_output_index = parent_output_index[next_value_rowid]; } result->push_back(current_output_index); } if (result->size() != value_rowids.size()) { return errors::InvalidArgument("Invalid row ids."); } return Status::OK(); }
1
C++
CWE-131
Incorrect Calculation of Buffer Size
The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.
https://cwe.mitre.org/data/definitions/131.html
safe
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-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
void Compute(OpKernelContext* ctx) override { const Tensor& handle = ctx->input(0); const string& name = handle.scalar<tstring>()(); Tensor val; auto session_state = ctx->session_state(); OP_REQUIRES(ctx, session_state != nullptr, errors::FailedPrecondition( "GetSessionTensor called on null session state")); OP_REQUIRES_OK(ctx, session_state->GetTensor(name, &val)); ctx->set_output(0, val); }
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
void FormatConverter<T>::Populate(const T* src_data, std::vector<int> indices, int level, int prev_idx, int* src_data_ptr, T* dest_data) { if (level == indices.size()) { int orig_rank = dense_shape_.size(); std::vector<int> orig_idx; orig_idx.resize(orig_rank); int i = 0; for (; i < orig_idx.size(); i++) { int orig_dim = traversal_order_[i]; orig_idx[orig_dim] = indices[i]; } for (; i < indices.size(); i++) { const int block_idx = traversal_order_[i] - orig_rank; const int orig_dim = block_map_[block_idx]; orig_idx[orig_dim] = orig_idx[orig_dim] * block_size_[block_idx] + indices[i]; } dest_data[GetFlattenedIndex(orig_idx, dense_shape_)] = src_data[*src_data_ptr]; *src_data_ptr = *src_data_ptr + 1; return; } const int metadata_idx = 2 * level; const int shape_of_level = dim_metadata_[metadata_idx][0]; if (format_[level] == kTfLiteDimDense) { for (int i = 0; i < shape_of_level; i++) { indices[level] = i; Populate(src_data, indices, level + 1, prev_idx * shape_of_level + i, src_data_ptr, dest_data); } } else { const auto& array_segments = dim_metadata_[metadata_idx]; const auto& array_indices = dim_metadata_[metadata_idx + 1]; for (int i = array_segments[prev_idx]; i < array_segments[prev_idx + 1]; i++) { indices[level] = array_indices[i]; Populate(src_data, indices, level + 1, i, src_data_ptr, dest_data); } } }
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 ActiveStreamDecoderFilter::complete() { return parent_.state_.remote_complete_; }
0
C++
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
vulnerable
int size() const { return m_str ? m_str->size() : 0; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
static int requireDirective(MaState *state, cchar *key, cchar *value) { char *age, *type, *rest, *option, *ovalue, *tok; int domains; if (!maTokenize(state, value, "%S ?*", &type, &rest)) { return MPR_ERR_BAD_SYNTAX; } if (scaselesscmp(type, "ability") == 0) { httpSetAuthRequiredAbilities(state->auth, rest); /* Support require group for legacy support */ // DEPRECATE "group" } else if (scaselesscmp(type, "group") == 0 || scaselesscmp(type, "role") == 0) { httpSetAuthRequiredAbilities(state->auth, rest); } else if (scaselesscmp(type, "secure") == 0) { domains = 0; age = 0; for (option = stok(sclone(rest), " \t", &tok); option; option = stok(0, " \t", &tok)) { option = stok(option, " =\t,", &ovalue); ovalue = strim(ovalue, "\"'", MPR_TRIM_BOTH); if (smatch(option, "age")) { age = sfmt("%lld", (int64) httpGetTicks(ovalue)); } else if (smatch(option, "domains")) { domains = 1; } } if (age) { if (domains) { /* Negative age signifies subdomains */ age = sjoin("-1", age, NULL); } } addCondition(state, "secure", age, HTTP_ROUTE_STRICT_TLS); } else if (scaselesscmp(type, "user") == 0) { httpSetAuthPermittedUsers(state->auth, rest); } else if (scaselesscmp(type, "valid-user") == 0) { httpSetAuthAnyValidUser(state->auth); } else { return configError(state, key); } return 0; }
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 Eval(TfLiteContext* context, TfLiteNode* node) { 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)); if (type == kGenericOptimized) { optimized_ops::Floor(GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } else { reference_ops::Floor(GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(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
std::wstring CreateUniqueTempDirectory() { // We need to put downloaded updates into a directory of their own, because // if we put it in $TMP, some DLLs could be there and interfere with the // installer. // // This code creates a new randomized directory name and tries to create it; // this process is repeated if the directory already exists. const std::wstring tmpdir = GetUniqueTempDirectoryPrefix(); for ( ;; ) { std::wstring dir(tmpdir); UUID uuid; UuidCreate(&uuid); RPC_WSTR uuidStr; RPC_STATUS status = UuidToString(&uuid, &uuidStr); dir += reinterpret_cast<wchar_t*>(uuidStr); RpcStringFree(&uuidStr); if ( CreateDirectory(dir.c_str(), NULL) ) return dir; else if ( GetLastError() != ERROR_ALREADY_EXISTS ) throw Win32Exception("Cannot create temporary directory"); } }
1
C++
CWE-426
Untrusted Search Path
The application searches for critical resources using an externally-supplied search path that can point to resources that are not under the application's direct control.
https://cwe.mitre.org/data/definitions/426.html
safe
public static boolean excludes( final Collection<String> patterns, final Path path ) { checkNotNull( "patterns", patterns ); checkNotNull( "path", path ); return matches( patterns, path ); }
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
R_API ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *evp) { ut64 sz = 0; if (evp == NULL) { return sz; } // evp->element_name_idx = r_bin_java_read_short(bin, bin->b->cur); sz += 2; // evp->value = r_bin_java_element_value_new (bin, offset+2); if (evp->value) { sz += r_bin_java_element_value_calc_size (evp->value); } return sz; }
0
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
vulnerable
bool IsIdentityConsumingSwitch(const MutableGraphView& graph, const NodeDef& node) { if ((IsIdentity(node) || IsIdentityNSingleInput(node)) && node.input_size() > 0) { TensorId tensor_id = ParseTensorName(node.input(0)); if (IsTensorIdControlling(tensor_id)) { return false; } NodeDef* input_node = graph.GetNode(tensor_id.node()); if (input_node == nullptr) { return false; } return IsSwitch(*input_node); } return false; }
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
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]); 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]); } } }
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 Prepare(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32); output->type = input->type; TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims); 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
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: return EvalImpl<kernel_type, kTfLiteFloat32>(context, node); case kTfLiteUInt8: return EvalImpl<kernel_type, kTfLiteUInt8>(context, node); case kTfLiteInt8: return EvalImpl<kernel_type, kTfLiteInt8>(context, node); case kTfLiteInt16: return EvalImpl<kernel_type, kTfLiteInt16>(context, node); default: context->ReportError(context, "Type %d not currently supported.", input->type); return kTfLiteError; } }
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
cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID, cmsUInt32Number n, cmsUInt32Number ColorantCount, const char* Prefix, const char* Suffix) { cmsNAMEDCOLORLIST* v = (cmsNAMEDCOLORLIST*) _cmsMallocZero(ContextID, sizeof(cmsNAMEDCOLORLIST)); if (v == NULL) return NULL; v ->List = NULL; v ->nColors = 0; v ->ContextID = ContextID; while (v -> Allocated < n) GrowNamedColorList(v); strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix)-1); strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix)-1); v->Prefix[32] = v->Suffix[32] = 0; v -> ColorantCount = ColorantCount; return v; }
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
TfLiteStatus ResizeOutputTensor(TfLiteContext* context, const TfLiteTensor* data, const TfLiteTensor* segment_ids, TfLiteTensor* output) { // Segment ids should be of same cardinality as first input dimension and they // should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid) const int segment_id_size = segment_ids->dims->data[0]; TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]); int previous_segment_id = -1; for (int i = 0; i < segment_id_size; i++) { const int current_segment_id = GetTensorData<int32_t>(segment_ids)[i]; if (i == 0) { TF_LITE_ENSURE_EQ(context, current_segment_id, 0); } else { int delta = current_segment_id - previous_segment_id; TF_LITE_ENSURE(context, delta == 0 || delta == 1); } previous_segment_id = current_segment_id; } const int max_index = previous_segment_id; const int data_rank = NumDimensions(data); TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data)); output_shape->data[0] = max_index + 1; for (int i = 1; i < data_rank; ++i) { output_shape->data[i] = data->dims->data[i]; } return context->ResizeTensor(context, output, output_shape); }
1
C++
CWE-770
Allocation of Resources Without Limits or Throttling
The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input_tensor)); TF_LITE_ENSURE_TYPES_EQ(context, input_tensor->type, kTfLiteString); TfLiteTensor* output_tensor; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output_tensor)); TF_LITE_ENSURE_TYPES_EQ(context, output_tensor->type, kTfLiteString); 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
AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector) { inspector.AddField("Configuration Version", m_ConfigurationVersion); const char* profile_name = GetProfileName(m_Profile); if (profile_name) { inspector.AddField("Profile", profile_name); } else { inspector.AddField("Profile", m_Profile); } inspector.AddField("Profile Compatibility", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX); inspector.AddField("Level", m_Level); inspector.AddField("NALU Length Size", m_NaluLengthSize); for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) { inspector.AddField("Sequence Parameter", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize()); } for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) { inspector.AddField("Picture Parameter", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize()); } return AP4_SUCCESS; }
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
Status CalculateOutputIndexRowSplit( const RowPartitionTensor& row_split, const vector<INDEX_TYPE>& parent_output_index, INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size, vector<INDEX_TYPE>* result) { INDEX_TYPE row_split_size = row_split.size(); if (row_split_size > 0) { result->reserve(row_split(row_split_size - 1)); } for (INDEX_TYPE i = 0; i < row_split_size - 1; ++i) { INDEX_TYPE row_length = row_split(i + 1) - row_split(i); INDEX_TYPE real_length = std::min(output_size, row_length); INDEX_TYPE parent_output_index_current = parent_output_index[i]; if (parent_output_index_current == -1) { real_length = 0; } for (INDEX_TYPE j = 0; j < real_length; ++j) { result->push_back(parent_output_index_current); parent_output_index_current += output_index_multiplier; } for (INDEX_TYPE j = 0; j < row_length - real_length; ++j) { result->push_back(-1); } } if (row_split_size > 0 && result->size() != row_split(row_split_size - 1)) { return errors::InvalidArgument("Invalid row split size."); } return Status::OK(); }
1
C++
CWE-131
Incorrect Calculation of Buffer Size
The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.
https://cwe.mitre.org/data/definitions/131.html
safe
bool AveragePool(const float* input_data, const Dims<4>& input_dims, int stride, int pad_width, int pad_height, int filter_width, int filter_height, float* output_data, const Dims<4>& output_dims) { return AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width, pad_height, filter_width, filter_height, output_data, output_dims); }
1
C++
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
void Lua::setParamsTable(lua_State* vm, const char* table_name, const char* query) const { char outbuf[FILENAME_MAX]; char *where; char *tok; char *query_string = query ? strdup(query) : NULL; lua_newtable(L); if (query_string) { // ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string); tok = strtok_r(query_string, "&", &where); while(tok != NULL) { char *_equal; if(strncmp(tok, "csrf", strlen("csrf")) /* Do not put csrf into the params table */ && (_equal = strchr(tok, '=')) && (strlen(_equal) > 1)) { char *decoded_buf; int len; _equal[0] = '\0'; _equal = &_equal[1]; len = strlen(_equal); purifyHTTPParameter(tok), purifyHTTPParameter(_equal); // ntop->getTrace()->traceEvent(TRACE_WARNING, "%s = %s", tok, _equal); if((decoded_buf = (char*)malloc(len+1)) != NULL) { Utils::urlDecode(_equal, decoded_buf, len+1); Utils::purifyHTTPparam(tok, true, false); Utils::purifyHTTPparam(decoded_buf, false, false); /* Now make sure that decoded_buf is not a file path */ FILE *fd; if((decoded_buf[0] == '.') && ((fd = fopen(decoded_buf, "r")) || (fd = fopen(realpath(decoded_buf, outbuf), "r")))) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded '%s'='%s' as argument is a valid file path", tok, decoded_buf); decoded_buf[0] = '\0'; fclose(fd); } /* ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, decoded_buf); */ /* put tok and the decoded buffer in to the table */ lua_push_str_table_entry(vm, tok, decoded_buf); free(decoded_buf); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } tok = strtok_r(NULL, "&", &where); } /* while */ } if(query_string) free(query_string); if(table_name) lua_setglobal(L, table_name); else lua_setglobal(L, (char*)"_GET"); /* Default */ }
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 AverageEvalQuantizedInt16(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_AVERAGE_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ TF_LITE_ENSURE(context, type::AveragePool(op_params, GetTensorShape(input), \ GetTensorData<int16_t>(input), \ GetTensorShape(output), \ GetTensorData<int16_t>(output))) TF_LITE_AVERAGE_POOL(reference_integer_ops); #undef TF_LITE_AVERAGE_POOL return kTfLiteOk; }
1
C++
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { static const int kOutputUniqueTensor = 0; static const int kOutputIndexTensor = 1; TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output_unique_tensor; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputUniqueTensor, &output_unique_tensor)); TfLiteTensor* output_index_tensor; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputIndexTensor, &output_index_tensor)); // The op only supports 1D input. TF_LITE_ENSURE_EQ(context, NumDimensions(input), 1); TfLiteIntArray* output_index_shape = TfLiteIntArrayCopy(input->dims); // The unique values are determined during evaluation, so we don't know yet // the size of the output tensor. SetTensorToDynamic(output_unique_tensor); return context->ResizeTensor(context, output_index_tensor, output_index_shape); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
TfLiteStatus L2Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: L2EvalFloat<kernel_type>(context, node, params, data, input, output); break; case kTfLiteUInt8: // We don't have a quantized implementation, so just fall through to the // 'default' case. default: context->ReportError(context, "Type %d not currently supported.", input->type); return kTfLiteError; } return kTfLiteOk; }
1
C++
CWE-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 SetLineWidth(double w) { sprintf(outputbuffer," %12.3f w",w); sendClean(outputbuffer); }
1
C++
NVD-CWE-noinfo
null
null
null
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) { if (offset < 0) return false; m_cursor = offset; } else if (whence == SEEK_END) { if (m_len + offset < 0) return false; m_cursor = m_len + offset; } else { return false; } setPosition(m_cursor); return true; }
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
jas_matrix_t *jas_matrix_copy(jas_matrix_t *x) { jas_matrix_t *y; jas_matind_t i; jas_matind_t 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; }
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
bool RepeatedAttrDefEqual( const protobuf::RepeatedPtrField<OpDef::AttrDef>& a1, const protobuf::RepeatedPtrField<OpDef::AttrDef>& a2) { std::unordered_map<string, const OpDef::AttrDef*> a1_set; for (const OpDef::AttrDef& def : a1) { DCHECK(a1_set.find(def.name()) == a1_set.end()) << "AttrDef names must be unique, but '" << def.name() << "' appears more than once"; a1_set[def.name()] = &def; } for (const OpDef::AttrDef& def : a2) { auto iter = a1_set.find(def.name()); if (iter == a1_set.end()) return false; if (!AttrDefEqual(*iter->second, def)) return false; a1_set.erase(iter); } if (!a1_set.empty()) 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
absl::Status IsSupported(const TfLiteContext* context, const TfLiteNode* tflite_node, const TfLiteRegistration* registration) final { RETURN_IF_ERROR(CheckMaxSupportedOpVersion(registration, 3)); if (tflite_node->inputs->size != 2) { return absl::UnimplementedError("MUL requires two input tensors."); } auto input0 = tflite::GetInput(context, tflite_node, 0); auto input1 = tflite::GetInput(context, tflite_node, 1); if (input0 == nullptr || input1 == nullptr) { return absl::InvalidArgumentError("At least one input tensor is null"); } if (input0->dims->size == input1->dims->size) { // this code checks that at least one input of Mul not smaller in all // dimensions. Sometimes Mul used for matrix-vector multiplication that we // currently don't support. For example input0 HWC(1, 256, 1), input1 // HWC(1, 1, 256) -> output HWC (1, 256, 256). In this case it can be // replaced with Convolution operation. bool first_has_smaller_dim = false; bool second_has_smaller_dim = false; for (int i = 0; i < input0->dims->size; ++i) { if (input0->dims->data[i] < input1->dims->data[i]) { first_has_smaller_dim = true; } if (input1->dims->data[i] < input0->dims->data[i]) { second_has_smaller_dim = true; } } if (first_has_smaller_dim && second_has_smaller_dim) { return absl::UnimplementedError( "MUL requires one tensor that not less than second in all " "dimensions."); } } const TfLiteMulParams* tf_options; RETURN_IF_ERROR(RetrieveBuiltinData(tflite_node, &tf_options)); return IsActivationSupported(tf_options->activation); }
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 ReluEval(TfLiteContext* context, TfLiteNode* node) { 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)); const ReluOpData* data = reinterpret_cast<ReluOpData*>(node->user_data); switch (input->type) { case kTfLiteFloat32: { optimized_ops::Relu(GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } break; // TODO(renjieliu): We may revisit the quantization calculation logic, // the unbounded upper limit is actually hard to quantize. case kTfLiteUInt8: { QuantizedReluX<uint8_t>(0.0f, std::numeric_limits<float>::infinity(), input, output, data); } break; case kTfLiteInt8: { QuantizedReluX<int8_t>(0.0f, std::numeric_limits<float>::infinity(), input, output, data); } break; default: TF_LITE_KERNEL_LOG( context, "Only float32 & int8/uint8 is supported currently, got %s.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
TfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) { for (int i = 0; i < NumOutputs(node); ++i) { TfLiteTensor* tensor; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor)); SetTensorToDynamic(tensor); } 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
TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node, int index) { const int tensor_index = ValidateTensorIndexing( context, index, node->outputs->size, node->outputs->data); if (tensor_index < 0) { return nullptr; } return GetTensorAtIndex(context, tensor_index); }
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 PrepareHashtableFind(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 3); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input_resource_id_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputResourceIdTensor, &input_resource_id_tensor)); TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32); TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1); TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1); const TfLiteTensor* default_value_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDefaultValueTensor, &default_value_tensor)); const TfLiteTensor* key_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kKeyTensor, &key_tensor)); TfLiteTensor* output_tensor; TF_LITE_ENSURE_OK( context, GetOutputSafe(context, node, kOutputTensor, &output_tensor)); TF_LITE_ENSURE_EQ(context, default_value_tensor->type, output_tensor->type); TF_LITE_ENSURE(context, (key_tensor->type == kTfLiteInt64 && output_tensor->type == kTfLiteString) || (key_tensor->type == kTfLiteString && output_tensor->type == kTfLiteInt64)); return context->ResizeTensor(context, output_tensor, TfLiteIntArrayCopy(key_tensor->dims)); }
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
QString Helper::temporaryMountDevice(const QString &device, const QString &name, bool readonly) { QString mount_point = mountPoint(device); if (!mount_point.isEmpty()) return mount_point; mount_point = "%1/.%2/mount/%3"; const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation); mount_point = mount_point.arg(tmp_paths.isEmpty() ? "/tmp" : tmp_paths.first()).arg(qApp->applicationName()).arg(name); if (!QDir::current().mkpath(mount_point)) { dCError("mkpath \"%s\" failed", qPrintable(mount_point)); return QString(); } if (!mountDevice(device, mount_point, readonly)) { dCError("Mount the device \"%s\" to \"%s\" failed", qPrintable(device), qPrintable(mount_point)); return QString(); } return mount_point; }
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
static bool is_legal_file(const std::string &filename) { DBG_FS << "Looking for '" << filename << "'.\n"; if (filename.empty()) { LOG_FS << " invalid filename\n"; return false; } if (filename.find("..") != std::string::npos) { ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed).\n"; return false; } if (ends_with(filename, ".pbl")) { ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl; return false; } return true; }
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 void Launch(OpKernelContext* context, const Tensor& in_x, const Tensor& in_y, bool adjoint, bool lower, const MatMulBCast& bcast, Tensor* out) { // Number of banded matrix triangular solves i.e. size of the batch. const int64 batch_size = bcast.output_batch_size(); const int64 cost_per_unit = in_x.dim_size(1) * in_x.dim_size(2) * in_y.dim_size(2); auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads()); using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; using ConstMatrixMap = Eigen::Map<const Matrix>; using RealScalar = typename Eigen::NumTraits<Scalar>::Real; // Check diagonal before doing any solves. This is the first row in the // lower case and else is the last row. auto matrix = ConstMatrixMap(in_x.flat<Scalar>().data(), in_x.dim_size(1), in_x.dim_size(2)); RealScalar min_abs_pivot; if (lower) { min_abs_pivot = matrix.row(0).cwiseAbs().minCoeff(); } else { min_abs_pivot = matrix.row(in_x.dim_size(1) - 1).cwiseAbs().minCoeff(); } OP_REQUIRES(context, min_abs_pivot > RealScalar(0), errors::InvalidArgument("Input matrix is not invertible.")); Shard(worker_threads.num_threads, worker_threads.workers, batch_size, cost_per_unit, [&in_x, &in_y, adjoint, lower, &bcast, out](int start, int limit) { SequentialBandedTriangularSolveKernel<Scalar>::Run( in_x, in_y, lower, adjoint, bcast, out, start, limit); }); }
0
C++
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
void CSecurityTLS::initGlobal() { static bool globalInitDone = false; if (!globalInitDone) { gnutls_global_init(); globalInitDone = 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
static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; JAS_DBGLOG(100, ( "jas_image_cmpt_create(%ld, %ld, %ld, %ld, %ld, %ld, %d, %d, %d)\n", JAS_CAST(long, tlx), JAS_CAST(long, tly), JAS_CAST(long, hstep), JAS_CAST(long, vstep), JAS_CAST(long, width), JAS_CAST(long, height), JAS_CAST(int, depth), sgnd, inmem )); cmpt = 0; if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { goto error; } if (!jas_safe_intfast32_add(tlx, width, 0) || !jas_safe_intfast32_add(tly, height, 0)) { goto error; } if (!jas_safe_intfast32_mul3(width, height, depth, 0)) { goto error; } if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; // Compute the number of samples in the image component, while protecting // against overflow. // size = cmpt->width_ * cmpt->height_ * cmpt->cps_; if (!jas_safe_size_mul3(cmpt->width_, cmpt->height_, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (size > 0) { if (size - 1 > LONG_MAX) { goto error; } if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; }
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
int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1) { jas_matind_t i; jas_matind_t j; if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ != mat1->numcols_) { return 1; } for (i = 0; i < mat0->numrows_; i++) { for (j = 0; j < mat0->numcols_; j++) { if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) { return 1; } } } return 0; }
1
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
inline typename V::SetType FBUnserializer<V>::unserializeSet(size_t depth) { p_ += CODE_SIZE; // the set size is written so we can reserve it in the set // in future. Skip past it for now. unserializeInt64(); typename V::SetType ret = V::createSet(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::setAppend(ret, unserializeThing(depth + 1)); code = nextCode(); } p_ += CODE_SIZE; return ret; }
1
C++
CWE-674
Uncontrolled Recursion
The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.
https://cwe.mitre.org/data/definitions/674.html
safe
TfLiteStatus EvalHashtable(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE(context, node->user_data != nullptr); const auto* params = reinterpret_cast<const TfLiteHashtableParams*>(node->user_data); // The resource id is generated based on the given table name. const int resource_id = std::hash<std::string>{}(params->table_name); TfLiteTensor* resource_handle_tensor; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kResourceHandleTensor, &resource_handle_tensor)); auto* resource_handle_data = GetTensorData<std::int32_t>(resource_handle_tensor); resource_handle_data[0] = resource_id; Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_); auto& resources = subgraph->resources(); resource::CreateHashtableResourceIfNotAvailable( &resources, resource_id, params->key_dtype, params->value_dtype); 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
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, size_t mincodes, size_t numcodes, unsigned maxbitlen) { unsigned error = 0; while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/ tree->maxbitlen = maxbitlen; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ tree->lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned)); if(!tree->lengths) return 83; /*alloc fail*/ /*initialize all lengths to 0*/ memset(tree->lengths, 0, numcodes * sizeof(unsigned)); error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); if(!error) error = HuffmanTree_makeFromLengths2(tree); return error; }
0
C++
CWE-401
Missing Release of Memory after Effective Lifetime
The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.
https://cwe.mitre.org/data/definitions/401.html
vulnerable
bool AES_GCM_DecryptContext::Decrypt( const void *pEncryptedDataAndTag, size_t cbEncryptedDataAndTag, const void *pIV, void *pPlaintextData, uint32 *pcbPlaintextData, const void *pAdditionalAuthenticationData, size_t cbAuthenticationData ) { unsigned long long pcbPlaintextData_longlong; const int nDecryptResult = crypto_aead_aes256gcm_decrypt_afternm( static_cast<unsigned char*>( pPlaintextData ), &pcbPlaintextData_longlong, nullptr, static_cast<const unsigned char*>( pEncryptedDataAndTag ), cbEncryptedDataAndTag, static_cast<const unsigned char*>( pAdditionalAuthenticationData ), cbAuthenticationData, static_cast<const unsigned char*>( pIV ), static_cast<const crypto_aead_aes256gcm_state*>( m_ctx ) ); *pcbPlaintextData = pcbPlaintextData_longlong; return nDecryptResult == 0; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
Status OpLevelCostEstimator::PredictFusedBatchNormGrad( const OpContext& op_context, NodeCosts* node_costs) const { bool found_unknown_shapes = false; const auto& op_info = op_context.op_info; // y_backprop: op_info.inputs(0) // x: op_info.inputs(1) // scale: op_info.inputs(2) // mean: op_info.inputs(3) // variance or inverse of variance: op_info.inputs(4) TF_ASSIGN_OR_RETURN(ConvolutionDimensions dims, OpDimensionsFromInputs(op_info.inputs(1).shape(), op_info, &found_unknown_shapes)); int64_t ops = 0; const auto rsqrt_cost = Eigen::internal::functor_traits< Eigen::internal::scalar_rsqrt_op<float>>::Cost; ops = dims.iz * (dims.batch * dims.ix * dims.iy * 11 + 5 + rsqrt_cost); node_costs->num_compute_ops = ops; const int64_t size_nhwc = CalculateTensorSize(op_info.inputs(1), &found_unknown_shapes); const int64_t size_c = CalculateTensorSize(op_info.inputs(2), &found_unknown_shapes); // TODO(dyoon): fix missing memory cost for variance input (size_c) and // yet another read of y_backprop (size_nhwc) internally. node_costs->num_input_bytes_accessed = {size_nhwc, size_nhwc, size_c, size_c}; node_costs->num_output_bytes_accessed = {size_nhwc, size_c, size_c}; // FusedBatchNormGrad has to read y_backprop internally. node_costs->internal_read_bytes = size_nhwc; node_costs->max_memory = node_costs->num_total_output_bytes(); if (found_unknown_shapes) { node_costs->inaccurate = true; node_costs->num_nodes_with_unknown_shapes = 1; } return Status::OK(); }
1
C++
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
TEST(DefaultCertValidatorTest, TestMatchSubjectAltNameWildcardDNSMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir " "}}/test/extensions/transport_sockets/tls/test_data/san_multiple_dns_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.set_exact("api.example.com"); std::vector<Matchers::StringMatcherImpl<envoy::type::matcher::v3::StringMatcher>> subject_alt_name_matchers; subject_alt_name_matchers.push_back(Matchers::StringMatcherImpl(matcher)); EXPECT_TRUE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers)); }
0
C++
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
vulnerable
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteUnpackParams* data = reinterpret_cast<TfLiteUnpackParams*>(node->builtin_data); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); switch (input->type) { case kTfLiteFloat32: { UnpackImpl<float>(context, node, input, data->num, data->axis); break; } case kTfLiteInt32: { UnpackImpl<int32_t>(context, node, input, data->num, data->axis); break; } case kTfLiteUInt8: { UnpackImpl<uint8_t>(context, node, input, data->num, data->axis); break; } case kTfLiteInt8: { UnpackImpl<int8_t>(context, node, input, data->num, data->axis); break; } case kTfLiteBool: { UnpackImpl<bool>(context, node, input, data->num, data->axis); break; } case kTfLiteInt16: { UnpackImpl<int16_t>(context, node, input, data->num, data->axis); break; } default: { context->ReportError(context, "Type '%s' is not supported by unpack.", TfLiteTypeGetName(input->type)); return kTfLiteError; } } return kTfLiteOk; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
void readDataAvailable(size_t len) noexcept override { VLOG(3) << "Read of size: " << len; s_->setReadCB(nullptr); s_->getEventBase()->runInLoop([this]() { s_->setReadCB(this); }); }
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
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { ut64 offset = 0; RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); if (!attr) { return NULL; } offset += 6; attr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR; attr->size = offset; return attr; }
0
C++
CWE-788
Access of Memory Location After End of Buffer
The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer.
https://cwe.mitre.org/data/definitions/788.html
vulnerable
Http::FilterMetadataStatus Context::onResponseMetadata() { if (!wasm_->onResponseMetadata_) { return Http::FilterMetadataStatus::Continue; } if (wasm_->onResponseMetadata_(this, id_).u64_ == 0) { return Http::FilterMetadataStatus::Continue; } return Http::FilterMetadataStatus::Continue; // This is currently the only return code. }
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 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; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); 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); }
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
R_API RBinJavaAttrInfo *r_bin_java_rtv_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { ut32 i = 0; 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) { attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR; attr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free); for (i = 0; i < attr->info.annotation_array.num_annotations; i++) { if (offset >= sz) { break; } RBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset); if (annotation) { offset += annotation->size; r_list_append (attr->info.annotation_array.annotations, (void *) annotation); } } attr->size = offset; } return attr; }
1
C++
CWE-788
Access of Memory Location After End of Buffer
The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer.
https://cwe.mitre.org/data/definitions/788.html
safe
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast<OpData*>(node->user_data); const TfLiteTensor* input1; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor1, &input1)); const TfLiteTensor* input2; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor2, &input2)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); switch (input1->type) { case kTfLiteInt32: { return EvalImpl<int32_t>(context, data->requires_broadcast, input1, input2, output); } case kTfLiteFloat32: { return EvalImpl<float>(context, data->requires_broadcast, input1, input2, output); } default: { context->ReportError(context, "Type '%s' is not supported by floor_div.", TfLiteTypeGetName(input1->type)); return kTfLiteError; } } }
1
C++
CWE-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 ArcMemory::Load(const byte *Data,size_t Size) { ArcData.Alloc(Size); memcpy(&ArcData[0],Data,Size); Loaded=true; SeekPos=0; }
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
jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms, int clrspc) { jas_image_t *image; size_t rawsize; uint_fast32_t inmem; int cmptno; jas_image_cmptparm_t *cmptparm; image = 0; JAS_DBGLOG(100, ("jas_image_create(%d, %p, %d)\n", numcmpts, cmptparms, clrspc)); if (!(image = jas_image_create0())) { goto error; } image->clrspc_ = clrspc; image->maxcmpts_ = numcmpts; // image->inmem_ = true; /* Allocate memory for the per-component information. */ if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_, sizeof(jas_image_cmpt_t *)))) { goto error; } /* Initialize in case of failure. */ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) { image->cmpts_[cmptno] = 0; } #if 0 /* Compute the approximate raw size of the image. */ rawsize = 0; for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { rawsize += cmptparm->width * cmptparm->height * (cmptparm->prec + 7) / 8; } /* Decide whether to buffer the image data in memory, based on the raw size of the image. */ inmem = (rawsize < JAS_IMAGE_INMEMTHRESH); #endif /* Create the individual image components. */ for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { if (!jas_safe_size_mul3(cmptparm->width, cmptparm->height, (cmptparm->prec + 7), &rawsize)) { goto error; } rawsize /= 8; inmem = (rawsize < JAS_IMAGE_INMEMTHRESH); if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx, cmptparm->tly, cmptparm->hstep, cmptparm->vstep, cmptparm->width, cmptparm->height, cmptparm->prec, cmptparm->sgnd, inmem))) { goto error; } ++image->numcmpts_; } /* Determine the bounding box for all of the components on the reference grid (i.e., the image area) */ jas_image_setbbox(image); return image; error: if (image) { jas_image_destroy(image); } return 0; }
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 CIRCNetwork::SetEncoding(const CString& s) { m_sEncoding = s; if (GetIRCSock()) { GetIRCSock()->SetEncoding(s); } }
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 Eval(TfLiteContext* context, TfLiteNode* node) { TfLiteTensor* output = GetOutput(context, node, kOutputTensor); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* diag = GetInput(context, node, kDiagonalTensor); FillDiagHelper(input, diag, 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
void ComputeAsync(OpKernelContext* c, DoneCallback done) override { auto col_params = new CollectiveParams(); auto done_with_cleanup = [col_params, done = std::move(done)]() { done(); col_params->Unref(); }; core::RefCountPtr<CollectiveGroupResource> resource; OP_REQUIRES_OK_ASYNC(c, LookupResource(c, HandleFromInput(c, 1), &resource), done_with_cleanup); Tensor group_assignment = c->input(2); OP_REQUIRES_OK_ASYNC( c, FillCollectiveParams(col_params, group_assignment, REDUCTION_COLLECTIVE, resource.get()), done); col_params->instance.shape = c->input(0).shape(); col_params->merge_op = merge_op_.get(); col_params->final_op = final_op_.get(); VLOG(1) << "CollectiveReduceV3 group_size " << col_params->group.group_size << " group_key " << col_params->group.group_key << " instance_key " << col_params->instance.instance_key; // Allocate the output tensor, trying to reuse the input. Tensor* output = nullptr; OP_REQUIRES_OK_ASYNC(c, c->forward_input_or_allocate_output( {0}, 0, col_params->instance.shape, &output), done_with_cleanup); Run(c, col_params, std::move(done_with_cleanup)); }
1
C++
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
safe
TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", "[dkg-aes-pub-shares]") { vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0); vector<char> errMsg(BUF_LEN, 0); int errStatus = 0; uint32_t encLen = 0; unsigned t = 32, n = 32; PRINT_SRC_LINE auto status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, n); REQUIRE(status == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS); vector<char> errMsg1(BUF_LEN, 0); char colon = ':'; vector<char> pubShares(10000, 0); PRINT_SRC_LINE status = trustedGetPublicSharesAES(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), encLen, pubShares.data(), t, n); REQUIRE(status == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS); vector <string> g2Strings = splitString(pubShares.data(), ','); vector <libff::alt_bn128_G2> pubSharesG2; for (u_int64_t i = 0; i < g2Strings.size(); i++) { vector <string> coeffStr = splitString(g2Strings.at(i).c_str(), ':'); pubSharesG2.push_back(TestUtils::vectStringToG2(coeffStr)); } vector<char> secret(BUF_LEN, 0); PRINT_SRC_LINE status = trustedDecryptDkgSecretAES(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), encLen, (uint8_t *) secret.data()); REQUIRE(status == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS); signatures::Dkg dkgObj(t, n); vector <libff::alt_bn128_Fr> poly = TestUtils::splitStringToFr(secret.data(), colon); vector <libff::alt_bn128_G2> pubSharesDkg = dkgObj.VerificationVector(poly); for (uint32_t i = 0; i < pubSharesDkg.size(); i++) { libff::alt_bn128_G2 el = pubSharesDkg.at(i); el.to_affine_coordinates(); } REQUIRE(pubSharesG2 == pubSharesDkg); }
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 Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const Tensor& filter = context->input(1); // Determine relevant sizes from input and filters. int stride_rows = 0, stride_cols = 0; int rate_rows = 0, rate_cols = 0; int64 pad_top = 0, pad_left = 0; int64 out_rows = 0, out_cols = 0; ParseSizes(context, strides_, rates_, padding_, &stride_rows, &stride_cols, &rate_rows, &rate_cols, &pad_top, &pad_left, &out_rows, &out_cols); if (!context->status().ok()) return; // Output tensor is of the following dimensions: // [ batch, out_rows, out_cols, depth ] const int batch = input.dim_size(0); const int depth = input.dim_size(3); const std::vector<int64> out_sizes = {batch, out_rows, out_cols, depth}; TensorShape out_shape(out_sizes); Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, out_shape, &output)); // If there is nothing to compute, return. if (out_shape.num_elements() == 0) { return; } functor::Dilation<Device, T>()( context->eigen_device<Device>(), input.tensor<T, 4>(), filter.tensor<T, 3>(), stride_rows, stride_cols, rate_rows, rate_cols, pad_top, pad_left, output->tensor<T, 4>()); }
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
TEST(ImmutableConstantOpTest, FromFile) { const TensorShape kFileTensorShape({1000, 1}); Env* env = Env::Default(); auto root = Scope::NewRootScope().ExitOnError(); string two_file, three_file; TF_ASSERT_OK(CreateTempFile(env, 2.0f, 1000, &two_file)); TF_ASSERT_OK(CreateTempFile(env, 3.0f, 1000, &three_file)); auto node1 = ops::ImmutableConst(root, DT_FLOAT, kFileTensorShape, two_file); auto node2 = ops::ImmutableConst(root, DT_FLOAT, kFileTensorShape, three_file); auto result = ops::MatMul(root, node1, node2, ops::MatMul::TransposeB(true)); GraphDef graph_def; TF_ASSERT_OK(root.ToGraphDef(&graph_def)); SessionOptions session_options; session_options.config.mutable_graph_options() ->mutable_optimizer_options() ->set_opt_level(OptimizerOptions::L0); 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; TF_ASSERT_OK(session->Run({}, {result.node()->name() + ":0"}, {}, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_EQ(outputs.front().flat<float>()(0), 2.0f * 3.0f); EXPECT_EQ(outputs.front().flat<float>()(1), 2.0f * 3.0f); EXPECT_EQ(outputs.front().flat<float>()(2), 2.0f * 3.0f); }
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
xmlNodePtr SimpleXMLElement_exportNode(const Object& sxe) { assert(sxe->instanceof(SimpleXMLElement_classof())); auto data = Native::data<SimpleXMLElement>(sxe.get()); return php_sxe_get_first_node(data, data->nodep()); }
0
C++
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
vulnerable
void SetBackgroundColor(int par) { if ( par == STROKING ) { send(" 0 0 0 0 K"); } else { send(" 0 0 0 0 k"); } }
1
C++
NVD-CWE-noinfo
null
null
null
safe
Status OpLevelCostEstimator::PredictMaxPool(const OpContext& op_context, NodeCosts* node_costs) const { bool found_unknown_shapes = false; const auto& op_info = op_context.op_info; // x: op_info.inputs(0) ConvolutionDimensions dims = OpDimensionsFromInputs( op_info.inputs(0).shape(), op_info, &found_unknown_shapes); // kx * ky - 1 comparisons per output (kx * xy > 1) // or 1 copy per output (kx * k1 = 1). int per_output_ops = dims.kx * dims.ky == 1 ? 1 : dims.kx * dims.ky - 1; int64_t ops = dims.batch * dims.ox * dims.oy * dims.oz * per_output_ops; node_costs->num_compute_ops = ops; int64_t input_size = 0; if (dims.ky >= dims.sy) { input_size = CalculateTensorSize(op_info.inputs(0), &found_unknown_shapes); } else { // dims.ky < dims.sy // Vertical stride is larger than vertical kernel; assuming row-major // format, skip unnecessary rows (or read every kx rows per sy rows, as the // others are not used for output). const auto data_size = DataTypeSize(BaseType(op_info.inputs(0).dtype())); input_size = data_size * dims.batch * dims.ix * dims.ky * dims.oy * dims.iz; } node_costs->num_input_bytes_accessed = {input_size}; const int64_t output_size = CalculateOutputSize(op_info, &found_unknown_shapes); node_costs->num_output_bytes_accessed = {output_size}; node_costs->max_memory = output_size; if (found_unknown_shapes) { node_costs->inaccurate = true; node_costs->num_nodes_with_unknown_shapes = 1; } return Status::OK(); }
0
C++
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
vulnerable
bool FontData::Bound(int32_t offset) { if (offset > Size() || offset < 0) return false; bound_offset_ += offset; return true; }
0
C++
CWE-189
Numeric Errors
Weaknesses in this category are related to improper calculation or conversion of numbers.
https://cwe.mitre.org/data/definitions/189.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); 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 == kTfLiteInt8 || input_type == kTfLiteInt16 || input_type == kTfLiteInt32); for (int i = 0; i < NumOutputs(node); ++i) { GetOutput(context, node, i)->type = input_type; } // If we know the contents of the 'axis' tensor, resize all outputs. // Otherwise, wait until Eval(). if (IsConstantTensor(op_context.axis)) { return ResizeOutputTensors(context, node, op_context.axis, op_context.input, op_context.params->num_splits); } else { return UseDynamicOutputTensors(context, node); } }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
static inline bool isValid(const RemoteFsDevice::Details &d) { return d.isLocalFile() || RemoteFsDevice::constSshfsProtocol==d.url.scheme(); }
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
void AuthChecker::PassUserInfoOnSuccess() { char *json_buf = auth::WriteUserInfoToJson(user_info_); if (json_buf == nullptr) { return; } char *base64_json_buf = auth::esp_base64_encode( json_buf, strlen(json_buf), true, false, true /*padding*/); context_->request()->AddHeaderToBackend(auth::kEndpointApiUserInfo, base64_json_buf); auth::esp_grpc_free(json_buf); auth::esp_grpc_free(base64_json_buf); TRACE(trace_span_) << "Authenticated."; trace_span_.reset(); on_done_(Status::OK); }
0
C++
CWE-290
Authentication Bypass by Spoofing
This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks.
https://cwe.mitre.org/data/definitions/290.html
vulnerable
void RemoteFsDevice::unmount() { if (details.isLocalFile()) { return; } if (!isConnected() || proc) { return; } if (messageSent) { return; } if (constSambaProtocol==details.url.scheme() || constSambaAvahiProtocol==details.url.scheme()) { mounter()->umount(mountPoint(details, false), getpid()); setStatusMessage(tr("Disconnecting...")); messageSent=true; return; } QString cmd; QStringList args; if (!details.isLocalFile()) { QString mp=mountPoint(details, false); if (!mp.isEmpty()) { cmd=Utils::findExe("fusermount"); if (!cmd.isEmpty()) { args << QLatin1String("-u") << QLatin1String("-z") << mp; } else { emit error(tr("\"fusermount\" is not installed!")); } } } if (!cmd.isEmpty()) { setStatusMessage(tr("Disconnecting...")); proc=new QProcess(this); proc->setProperty("unmount", true); connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int))); proc->start(cmd, args, QIODevice::ReadOnly); } }
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
R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { ut64 offset = 0; RBinJavaAttrInfo *attr = NULL; 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; }
0
C++
CWE-788
Access of Memory Location After End of Buffer
The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer.
https://cwe.mitre.org/data/definitions/788.html
vulnerable
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
0
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
vulnerable
int ZlibOutStream::length() { return offset + ptr - start; }
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
virtual void requestInit() { m_use_error = false; m_errors.reset(); m_entity_loader_disabled = false; xmlParserInputBufferCreateFilenameDefault(hphp_libxml_input_buffer); }
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
CString CZNC::FixupEncoding(const CString& sEncoding) const { if (sEncoding.empty() && m_uiForceEncoding) { return "UTF-8"; } return sEncoding; }
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
String preg_quote(const String& str, const String& delimiter /* = null_string */) { const char* in_str = str.data(); const char* in_str_end = in_str + str.size(); /* Nothing to do if we got an empty string */ if (in_str == in_str_end) { return str; } char delim_char = 0; /* Delimiter character to be quoted */ bool quote_delim = false; /* Whether to quote additional delim char */ if (!delimiter.empty()) { delim_char = delimiter.charAt(0); quote_delim = true; } /* Allocate enough memory so that even if each character is quoted, we won't run out of room */ static_assert( (StringData::MaxSize * 4 + 1) < std::numeric_limits<int64_t>::max() ); String ret(4 * str.size() + 1, ReserveString); char* out_str = ret.mutableData(); /* Go through the string and quote necessary characters */ const char* p; char* q; for (p = in_str, q = out_str; p != in_str_end; p++) { char c = *p; switch (c) { case '.': case '\\': case '+': case '*': case '?': case '[': case '^': case ']': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '>': case '<': case '|': case ':': case '-': case '#': *q++ = '\\'; *q++ = c; break; case '\0': *q++ = '\\'; *q++ = '0'; *q++ = '0'; *q++ = '0'; break; default: if (quote_delim && c == delim_char) *q++ = '\\'; *q++ = c; break; } } *q = '\0'; return ret.setSize(q - out_str); }
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
HexInStream::HexInStream(InStream& is, int bufSize_) : bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_LEN), offset(0), in_stream(is) { ptr = end = start = new U8[bufSize]; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteMulParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input1; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor1, &input1)); const TfLiteTensor* input2; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor2, &input2)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type); const bool requires_broadcast = !HaveSameShapes(input1, input2); TfLiteIntArray* output_size = nullptr; if (requires_broadcast) { TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast( context, input1, input2, &output_size)); } else { output_size = TfLiteIntArrayCopy(input1->dims); } if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 || output->type == kTfLiteInt16) { TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized( context, params->activation, output, &data->output_activation_min, &data->output_activation_max)); double real_multiplier = input1->params.scale * input2->params.scale / output->params.scale; QuantizeMultiplier(real_multiplier, &data->output_multiplier, &data->output_shift); } 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
inline static bool jas_safe_size_mul3(size_t a, size_t b, size_t c, size_t *result) { size_t tmp; if (!jas_safe_size_mul(a, b, &tmp) || !jas_safe_size_mul(tmp, c, &tmp)) { return false; } if (result) { *result = tmp; } return true; }
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
Http::Response AbstractWebApplication::processRequest(const Http::Request &request, const Http::Environment &env) { session_ = 0; request_ = request; env_ = env; // clear response clear(); // avoid clickjacking attacks header(Http::HEADER_X_FRAME_OPTIONS, "SAMEORIGIN"); sessionInitialize(); if (!sessionActive() && !isAuthNeeded()) sessionStart(); if (isBanned()) { status(403, "Forbidden"); print(QObject::tr("Your IP address has been banned after too many failed authentication attempts."), Http::CONTENT_TYPE_TXT); } else { processRequest(); } return response(); }
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
const TfLiteTensor* GetIntermediates(TfLiteContext* context, const TfLiteNode* node, int index) { const int tensor_index = ValidateTensorIndexing( context, index, node->intermediates->size, node->intermediates->data); if (tensor_index < 0) { return nullptr; } return GetTensorAtIndex(context, tensor_index); }
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 Prepare(TfLiteContext* context, TfLiteNode* node) { auto* data = reinterpret_cast<TfLiteAudioMicrofrontendParams*>(node->user_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_EQ(context, NumDimensions(input), 1); TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt16); output->type = kTfLiteInt32; if (data->out_float) { output->type = kTfLiteFloat32; } TfLiteIntArray* output_size = TfLiteIntArrayCreate(2); int num_frames = 0; if (input->dims->data[0] >= data->state->window.size) { num_frames = (input->dims->data[0] - data->state->window.size) / data->state->window.step / data->frame_stride + 1; } output_size->data[0] = num_frames; output_size->data[1] = data->state->filterbank.num_channels * (1 + data->left_context + data->right_context); return context->ResizeTensor(context, output, output_size); }
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 int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { const int qslen = blen - qs; memmove(s+j, s+qs, (size_t)qslen); qs = j; j += qslen; } buffer_string_set_length(b, j); return qs; }
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
TEST(CudnnRNNOpsTest, ForwardV2Lstm_ShapeFn) { int seq_length = 2; int batch_size = 3; int num_units = 4; int num_layers = 5; int dir_count = 1; std::vector<int> input_shape = {seq_length, batch_size, num_units}; std::vector<int> input_h_shape = {num_layers * dir_count, batch_size, num_units}; std::vector<int> output_shape = {seq_length, batch_size, num_units * dir_count}; auto shape_to_str = [](const std::vector<int>& v) { return strings::StrCat("[", absl::StrJoin(v, ","), "]"); }; string input_shapes_desc = strings::StrCat( shape_to_str(input_shape), ";", shape_to_str(input_h_shape), ";", shape_to_str(input_h_shape), ";", "[?]"); string output_shapes_desc = "[d0_0,d0_1,d1_2];in1;in1;?;?"; ShapeInferenceTestOp op("CudnnRNNV2"); TF_ASSERT_OK(NodeDefBuilder("test", "CudnnRNNV2") .Input({"input", 0, DT_FLOAT}) .Input({"input_h", 0, DT_FLOAT}) .Input({"input_c", 0, DT_FLOAT}) .Input({"params", 0, DT_FLOAT}) .Attr("rnn_mode", "lstm") .Attr("input_mode", "auto_select") .Attr("direction", "unidirectional") .Finalize(&op.node_def)); INFER_OK(op, input_shapes_desc, output_shapes_desc); INFER_ERROR("Shape must be rank 3 ", op, "[];[?,?,?];[?,?,?];[?]"); INFER_ERROR("Shape must be rank 3 ", op, "[?,?,?];[];[?,?,?];[?]"); // Disabled because the kernel does not check shape of input_c. // INFER_ERROR("Shape must be rank 3 ", op, "[?,?,?];[?,?,?];[?];[?]"); INFER_ERROR("Shape must be rank 1 ", op, "[?,?,?];[?,?,?];[?,?,?];[]"); }
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 bool IsValidPermutation(const std::string& src, const std::string& dst) { if (src.size() != dst.size()) { return false; } std::map<char, bool> characters; // Every character in `src` must be present only once for (const auto c : src) { if (characters[c]) { return false; } characters[c] = true; } // Every character in `dst` must show up in `src` exactly once for (const auto c : dst) { if (!characters[c]) { return false; } characters[c] = false; } // At this point, characters[] has been switched to true and false exactly // once for all character in `src` (and `dst`) so we have a valid permutation return true; }
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 StoreAllDecodedSequences( TfLiteContext* context, const std::vector<std::vector<std::vector<int>>>& sequences, TfLiteNode* node, int top_paths) { const int32_t batch_size = sequences.size(); std::vector<int32_t> num_entries(top_paths, 0); // Calculate num_entries per path for (const auto& batch_s : sequences) { TF_LITE_ENSURE_EQ(context, batch_s.size(), top_paths); for (int p = 0; p < top_paths; ++p) { num_entries[p] += batch_s[p].size(); } } for (int p = 0; p < top_paths; ++p) { const int32_t p_num = num_entries[p]; // Resize the decoded outputs. TfLiteTensor* indices; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, p, &indices)); TF_LITE_ENSURE_OK(context, Resize(context, {p_num, 2}, indices)); TfLiteTensor* values; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, p + top_paths, &values)); TF_LITE_ENSURE_OK(context, Resize(context, {p_num}, values)); TfLiteTensor* decoded_shape; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, p + 2 * top_paths, &decoded_shape)); TF_LITE_ENSURE_OK(context, Resize(context, {2}, decoded_shape)); int32_t max_decoded = 0; int32_t offset = 0; int32_t* indices_data = GetTensorData<int32_t>(indices); int32_t* values_data = GetTensorData<int32_t>(values); int32_t* decoded_shape_data = GetTensorData<int32_t>(decoded_shape); for (int b = 0; b < batch_size; ++b) { auto& p_batch = sequences[b][p]; int32_t num_decoded = p_batch.size(); max_decoded = std::max(max_decoded, num_decoded); std::copy_n(p_batch.begin(), num_decoded, values_data + offset); for (int32_t t = 0; t < num_decoded; ++t, ++offset) { indices_data[offset * 2] = b; indices_data[offset * 2 + 1] = t; } } decoded_shape_data[0] = batch_size; decoded_shape_data[1] = max_decoded; } 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
CharArray(int len) { buf = new char[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
int64_t size() const { return m_str ? m_str->size() : 0; }
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 CharCodeToUnicode::addMapping(CharCode code, char *uStr, int n, int offset) { CharCode oldLen, i; Unicode u; char uHex[5]; int j; if (code >= mapLen) { oldLen = mapLen; mapLen = (code + 256) & ~255; map = (Unicode *)greallocn(map, mapLen, sizeof(Unicode)); for (i = oldLen; i < mapLen; ++i) { map[i] = 0; } } if (n <= 4) { if (sscanf(uStr, "%x", &u) != 1) { error(-1, "Illegal entry in ToUnicode CMap"); return; } map[code] = u + offset; } else { if (sMapLen >= sMapSize) { sMapSize = sMapSize + 16; sMap = (CharCodeToUnicodeString *) greallocn(sMap, sMapSize, sizeof(CharCodeToUnicodeString)); } map[code] = 0; sMap[sMapLen].c = code; sMap[sMapLen].len = n / 4; for (j = 0; j < sMap[sMapLen].len && j < maxUnicodeString; ++j) { strncpy(uHex, uStr + j*4, 4); uHex[4] = '\0'; if (sscanf(uHex, "%x", &sMap[sMapLen].u[j]) != 1) { error(-1, "Illegal entry in ToUnicode CMap"); } } sMap[sMapLen].u[sMap[sMapLen].len - 1] += offset; ++sMapLen; } }
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
inline void StringData::setSize(int len) { assertx(!isImmutable() && !hasMultipleRefs()); assertx(len >= 0 && len <= capacity()); mutableData()[len] = 0; m_lenAndHash = len; assertx(m_hash == 0); assertx(checkSane()); }
0
C++
CWE-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 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
TEST_F(ListenerManagerImplQuicOnlyTest, QuicListenerFactoryWithWrongTransportSocket) { const std::string yaml = TestEnvironment::substitute(R"EOF( address: socket_address: address: 127.0.0.1 protocol: UDP port_value: 1234 filter_chains: - filter_chain_match: transport_protocol: "quic" filters: [] transport_socket: name: envoy.transport_sockets.quic typed_config: "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext common_tls_context: tls_certificates: - certificate_chain: filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem" private_key: filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_key.pem" validation_context: trusted_ca: filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem" match_subject_alt_names: - exact: localhost - exact: 127.0.0.1 udp_listener_config: quic_options: {} )EOF", Network::Address::IpVersion::v4); envoy::config::listener::v3::Listener listener_proto = parseListenerFromV3Yaml(yaml); #if defined(ENVOY_ENABLE_QUIC) EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(listener_proto, "", true), EnvoyException, "wrong transport socket config specified for quic transport socket"); #else EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(listener_proto, "", true), EnvoyException, "QUIC is configured but not enabled in the build."); #endif }
0
C++
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
vulnerable
StatusOr<FullTypeDef> SpecializeType(const AttrSlice& attrs, const OpDef& op_def) { FullTypeDef ft; ft.set_type_id(TFT_PRODUCT); for (int i = 0; i < op_def.output_arg_size(); i++) { auto* t = ft.add_args(); *t = op_def.output_arg(i).experimental_full_type(); // Resolve dependent types. The convention for op registrations is to use // attributes as type variables. // See https://www.tensorflow.org/guide/create_op#type_polymorphism. // Once the op signature can be defined entirely in FullType, this // convention can be deprecated. // // Note: While this code performs some basic verifications, it generally // assumes consistent op defs and attributes. If more complete // verifications are needed, they should be done by separately, and in a // way that can be reused for type inference. for (int j = 0; j < t->args_size(); j++) { auto* arg = t->mutable_args(i); if (arg->type_id() == TFT_VAR) { const auto* attr = attrs.Find(arg->s()); DCHECK(attr != nullptr); if (attr->value_case() == AttrValue::kList) { const auto& attr_list = attr->list(); arg->set_type_id(TFT_PRODUCT); for (int i = 0; i < attr_list.type_size(); i++) { map_dtype_to_tensor(attr_list.type(i), arg->add_args()); } } else if (attr->value_case() == AttrValue::kType) { map_dtype_to_tensor(attr->type(), arg); } else { return Status(error::UNIMPLEMENTED, absl::StrCat("unknown attribute type", attrs.DebugString(), " key=", arg->s())); } arg->clear_s(); } } } return ft; }
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
void Compute(OpKernelContext* ctx) override { const auto splits = ctx->input(0).flat<int64>(); 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 weights_size = weights.size(); 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-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