code
stringlengths
23
2.05k
label_name
stringlengths
6
7
label
int64
0
37
HeaderLookupTable_t::lookup (const char *buf, const std::size_t len) const { const HeaderTableRecord *r = HttpHeaderHashTable::lookup(buf, len); if (!r) return BadHdr; return *r; }
CWE-116
15
static inline long decode_twos_comp(ulong c, int prec) { long result; assert(prec >= 2); jas_eprintf("warning: support for signed data is untested\n"); // NOTE: Is this correct? result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1))); return result; }
CWE-20
0
bool MemoryManager::validate_user_read(const Process& process, VirtualAddress vaddr) const { auto* region = region_from_vaddr(process, vaddr); return region && region->is_readable(); }
CWE-119
26
void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const { ParaNdis_CheckSumVerifyFlat(IpHeader, EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum, __FUNCTION__); }
CWE-20
0
TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ) { TPM2B_DIGEST tmpResult; TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2; UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0]; UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0]; TPM2B_DIGEST *bufferList[8]; UINT32 bitsSwizzled, i_Swizzled; TPM_RC rval; int i, j; UINT16 bytes = bits / 8; resultKey->t .size = 0; tpm2b_i_2.t.size = 4; tpm2bBits.t.size = 4; bitsSwizzled = string_bytes_endian_convert_32( bits ); *(UINT32 *)tpm2bBitsPtr = bitsSwizzled; for(i = 0; label[i] != 0 ;i++ ); tpm2bLabel.t.size = i+1; for( i = 0; i < tpm2bLabel.t.size; i++ ) { tpm2bLabel.t.buffer[i] = label[i]; } resultKey->t.size = 0; i = 1; while( resultKey->t.size < bytes ) { // Inner loop i_Swizzled = string_bytes_endian_convert_32( i ); *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled; j = 0; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b); bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b); bufferList[j++] = (TPM2B_DIGEST *)contextU; bufferList[j++] = (TPM2B_DIGEST *)contextV; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b); bufferList[j++] = (TPM2B_DIGEST *)0; rval = tpm_hmac(sapi_context, hashAlg, key, (TPM2B **)&( bufferList[0] ), &tmpResult ); if( rval != TPM_RC_SUCCESS ) { return( rval ); } bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b)); if (!res) { return TSS2_SYS_RC_BAD_VALUE; } } // Truncate the result to the desired size. resultKey->t.size = bytes; return TPM_RC_SUCCESS; }
CWE-522
19
char *QuotedString::extractFrom(char *input, char **endPtr) { char firstChar = *input; if (!isQuote(firstChar)) { // must start with a quote return NULL; } char stopChar = firstChar; // closing quote is the same as opening quote char *startPtr = input + 1; // skip the quote char *readPtr = startPtr; char *writePtr = startPtr; char c; for (;;) { c = *readPtr++; if (c == '\0') { // premature ending return NULL; } if (c == stopChar) { // closing quote break; } if (c == '\\') { // replace char c = unescapeChar(*readPtr++); } *writePtr++ = c; } // end the string here *writePtr = '\0'; // update end ptr *endPtr = readPtr; return startPtr; }
CWE-119
26
Status TensorSliceReader::GetTensor( const string& name, std::unique_ptr<tensorflow::Tensor>* out_tensor) const { DataType type; TensorShape shape; TensorSlice slice; { mutex_lock l(mu_); const TensorSliceSet* tss = gtl::FindPtrOrNull(tensors_, name); if (tss == nullptr) { return errors::NotFound(name, " not found in checkpoint file"); } if (tss->Slices().size() > 1) { // TODO(sherrym): Support multi-slice checkpoints. return errors::Unimplemented("Sliced checkpoints are not supported"); } type = tss->type(); shape = tss->shape(); slice = tss->Slices().begin()->second.slice; } std::unique_ptr<tensorflow::Tensor> t(new tensorflow::Tensor(type, shape)); bool success = false; #define READER_COPY(dt) \ case dt: \ success = CopySliceData(name, slice, \ t->flat<EnumToDataType<dt>::Type>().data()); \ break; switch (type) { READER_COPY(DT_FLOAT); READER_COPY(DT_DOUBLE); READER_COPY(DT_INT32); READER_COPY(DT_UINT8); READER_COPY(DT_INT16); READER_COPY(DT_INT8); READER_COPY(DT_INT64); READER_COPY(DT_STRING); default: return errors::Unimplemented("Data type not supported"); } #undef READER_COPY if (!success) { return errors::NotFound(name, " not found in checkpoint file"); } std::swap(*out_tensor, t); return Status::OK(); }
CWE-345
22
void RemoteFsDevice::load() { if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) { // Start Avahi listener... Avahi::self(); QUrlQuery q(details.url); if (q.hasQueryItem(constServiceNameQuery)) { details.serviceName=q.queryItemValue(constServiceNameQuery); } if (!details.serviceName.isEmpty()) { AvahiService *srv=Avahi::self()->getService(details.serviceName); if (!srv || srv->getHost().isEmpty()) { sub=tr("Not Available"); } else { sub=tr("Available"); } } connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString))); connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString))); } if (isConnected()) { setAudioFolder(); readOpts(settingsFileName(), opts, true); rescan(false); // Read from cache if we have it! } }
CWE-20
0
bool MemoryManager::validate_user_write(const Process& process, VirtualAddress vaddr) const { auto* region = region_from_vaddr(process, vaddr); return region && region->is_writable(); }
CWE-119
26
void ConnectionImpl::onHeaderValue(const char* data, size_t length) { if (header_parsing_state_ == HeaderParsingState::Done) { // Ignore trailers. return; } const absl::string_view header_value = absl::string_view(data, length); if (strict_header_validation_) { if (!Http::HeaderUtility::headerIsValid(header_value)) { ENVOY_CONN_LOG(debug, "invalid header value: {}", connection_, header_value); error_code_ = Http::Code::BadRequest; sendProtocolError(); throw CodecProtocolException("http/1.1 protocol error: header value contains invalid chars"); } } else if (header_value.find('\0') != absl::string_view::npos) { // http-parser should filter for this // (https://tools.ietf.org/html/rfc7230#section-3.2.6), but it doesn't today. HeaderStrings // have an invariant that they must not contain embedded zero characters // (NUL, ASCII 0x0). throw CodecProtocolException("http/1.1 protocol error: header value contains NUL"); } header_parsing_state_ = HeaderParsingState::Value; current_header_value_.append(data, length); const uint32_t total = current_header_field_.size() + current_header_value_.size() + current_header_map_->byteSize(); if (total > (max_request_headers_kb_ * 1024)) { error_code_ = Http::Code::RequestHeaderFieldsTooLarge; sendProtocolError(); throw CodecProtocolException("headers size exceeds limit"); } }
CWE-400
2
auto ReferenceHandle::Get(Local<Value> key_handle, MaybeLocal<Object> maybe_options) -> Local<Value> { return ThreePhaseTask::Run<async, GetRunner>(*isolate, *this, key_handle, maybe_options, inherit); }
CWE-913
24
void LibRaw::exp_bef(float shift, float smooth) { // params limits if(shift>8) shift = 8; if(shift<0.25) shift = 0.25; if(smooth < 0.0) smooth = 0.0; if(smooth > 1.0) smooth = 1.0; unsigned short *lut = (ushort*)malloc((TBLN+1)*sizeof(unsigned short)); if(shift <=1.0) { for(int i=0;i<=TBLN;i++) lut[i] = (unsigned short)((float)i*shift); } else { float x1,x2,y1,y2; float cstops = log(shift)/log(2.0f); float room = cstops*2; float roomlin = powf(2.0f,room); x2 = (float)TBLN; x1 = (x2+1)/roomlin-1; y1 = x1*shift; y2 = x2*(1+(1-smooth)*(shift-1)); float sq3x=powf(x1*x1*x2,1.0f/3.0f); float B = (y2-y1+shift*(3*x1-3.0f*sq3x)) / (x2+2.0f*x1-3.0f*sq3x); float A = (shift - B)*3.0f*powf(x1*x1,1.0f/3.0f); float CC = y2 - A*powf(x2,1.0f/3.0f)-B*x2; for(int i=0;i<=TBLN;i++) { float X = (float)i; float Y = A*powf(X,1.0f/3.0f)+B*X+CC; if(i<x1) lut[i] = (unsigned short)((float)i*shift); else lut[i] = Y<0?0:(Y>TBLN?TBLN:(unsigned short)(Y)); } } for(int i=0; i< S.height*S.width; i++) { imgdata.image[i][0] = lut[imgdata.image[i][0]]; imgdata.image[i][1] = lut[imgdata.image[i][1]]; imgdata.image[i][2] = lut[imgdata.image[i][2]]; imgdata.image[i][3] = lut[imgdata.image[i][3]]; } C.data_maximum = lut[C.data_maximum]; C.maximum = lut[C.maximum]; // no need to adjust the minumum, black is already subtracted free(lut); }
CWE-119
26
mptctl_eventreport (unsigned long arg) { struct mpt_ioctl_eventreport __user *uarg = (void __user *) arg; struct mpt_ioctl_eventreport karg; MPT_ADAPTER *ioc; int iocnum; int numBytes, maxEvents, max; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_eventreport - " "Unable to read in mpt_ioctl_eventreport struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_eventreport() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventreport called.\n", ioc->name)); numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header); maxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS); max = MPTCTL_EVENT_LOG_SIZE < maxEvents ? MPTCTL_EVENT_LOG_SIZE : maxEvents; /* If fewer than 1 event is requested, there must have * been some type of error. */ if ((max < 1) || !ioc->events) return -ENODATA; /* reset this flag so SIGIO can restart */ ioc->aen_event_read_flag=0; /* Copy the data from kernel memory to user memory */ numBytes = max * sizeof(MPT_IOCTL_EVENTS); if (copy_to_user(uarg->eventData, ioc->events, numBytes)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventreport - " "Unable to write out mpt_ioctl_eventreport struct @ %p\n", ioc->name, __FILE__, __LINE__, ioc->events); return -EFAULT; } return 0; }
CWE-362
18
void Init(void) { for(int i = 0;i < 18;i++) { X[i].Init(); M[i].Init(); } }
CWE-119
26
void ZlibInStream::deinit() { assert(zs != NULL); removeUnderlying(); inflateEnd(zs); delete zs; zs = NULL; }
CWE-672
37
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; }
CWE-20
0
CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2, value n) { memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n)); return Val_unit; }
CWE-119
26
CAMLprim value caml_bitvect_test(value bv, value n) { int pos = Int_val(n); return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7))); }
CWE-200
10
void Ogg::XiphComment::parse(const ByteVector &data) { // The first thing in the comment data is the vendor ID length, followed by a // UTF8 string with the vendor ID. int pos = 0; int vendorLength = data.mid(0, 4).toUInt(false); pos += 4; d->vendorID = String(data.mid(pos, vendorLength), String::UTF8); pos += vendorLength; // Next the number of fields in the comment vector. int commentFields = data.mid(pos, 4).toUInt(false); pos += 4; for(int i = 0; i < commentFields; i++) { // Each comment field is in the format "KEY=value" in a UTF8 string and has // 4 bytes before the text starts that gives the length. int commentLength = data.mid(pos, 4).toUInt(false); pos += 4; String comment = String(data.mid(pos, commentLength), String::UTF8); pos += commentLength; int commentSeparatorPosition = comment.find("="); String key = comment.substr(0, commentSeparatorPosition); String value = comment.substr(commentSeparatorPosition + 1); addField(key, value, false); } }
CWE-20
0
TEST_F(SQLiteUtilTests, test_column_type_determination) { // Correct identification of text and ints testTypesExpected("select path, inode from file where path like '%'", TypeMap({{"path", TEXT_TYPE}, {"inode", INTEGER_TYPE}})); // Correctly treating BLOBs as text testTypesExpected("select CAST(seconds AS BLOB) as seconds FROM time", TypeMap({{"seconds", TEXT_TYPE}})); // Correctly treating ints cast as double as doubles testTypesExpected("select CAST(seconds AS DOUBLE) as seconds FROM time", TypeMap({{"seconds", DOUBLE_TYPE}})); // Correctly treating bools as ints testTypesExpected("select CAST(seconds AS BOOLEAN) as seconds FROM time", TypeMap({{"seconds", INTEGER_TYPE}})); // Correctly recognizing values from columns declared double as double, even // if they happen to have integer value. And also test multi-statement // queries. testTypesExpected( "CREATE TABLE test_types_table (username varchar(30) primary key, age " "double);INSERT INTO test_types_table VALUES (\"mike\", 23); SELECT age " "from test_types_table", TypeMap({{"age", DOUBLE_TYPE}})); }
CWE-77
14
void skip(Protocol_& prot, TType arg_type) { switch (arg_type) { case TType::T_BOOL: { bool boolv; prot.readBool(boolv); return; } case TType::T_BYTE: { int8_t bytev; prot.readByte(bytev); return; } case TType::T_I16: { int16_t i16; prot.readI16(i16); return; } case TType::T_I32: { int32_t i32; prot.readI32(i32); return; } case TType::T_I64: { int64_t i64; prot.readI64(i64); return; } case TType::T_DOUBLE: { double dub; prot.readDouble(dub); return; } case TType::T_FLOAT: { float flt; prot.readFloat(flt); return; } case TType::T_STRING: { std::string str; prot.readBinary(str); return; } case TType::T_STRUCT: { std::string name; int16_t fid; TType ftype; prot.readStructBegin(name); while (true) { prot.readFieldBegin(name, ftype, fid); if (ftype == TType::T_STOP) { break; } apache::thrift::skip(prot, ftype); prot.readFieldEnd(); } prot.readStructEnd(); return; } case TType::T_MAP: { TType keyType; TType valType; uint32_t i, size; prot.readMapBegin(keyType, valType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, keyType); apache::thrift::skip(prot, valType); } prot.readMapEnd(); return; } case TType::T_SET: { TType elemType; uint32_t i, size; prot.readSetBegin(elemType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, elemType); } prot.readSetEnd(); return; } case TType::T_LIST: { TType elemType; uint32_t i, size; prot.readListBegin(elemType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, elemType); } prot.readListEnd(); return; } default: return; } }
CWE-755
21
void RemoteFsDevice::serviceRemoved(const QString &name) { if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) { sub=tr("Not Available"); updateStatus(); } }
CWE-20
0
int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; }
CWE-119
26
void CZNC::ForceEncoding() { m_uiForceEncoding++; #ifdef HAVE_ICU for (Csock* pSock : GetManager()) { if (pSock->GetEncoding().empty()) { pSock->SetEncoding("UTF-8"); } } #endif }
CWE-20
0
mptctl_eventquery (unsigned long arg) { struct mpt_ioctl_eventquery __user *uarg = (void __user *) arg; struct mpt_ioctl_eventquery karg; MPT_ADAPTER *ioc; int iocnum; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_eventquery - " "Unable to read in mpt_ioctl_eventquery struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_eventquery() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventquery called.\n", ioc->name)); karg.eventEntries = MPTCTL_EVENT_LOG_SIZE; karg.eventTypes = ioc->eventTypes; /* Copy the data from kernel memory to user memory */ if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventquery - " "Unable to write out mpt_ioctl_eventquery struct @ %p\n", ioc->name, __FILE__, __LINE__, uarg); return -EFAULT; } return 0; }
CWE-362
18
HttpIntegrationTest::waitForNextUpstreamRequest(const std::vector<uint64_t>& upstream_indices) { uint64_t upstream_with_request; // If there is no upstream connection, wait for it to be established. if (!fake_upstream_connection_) { AssertionResult result = AssertionFailure(); for (auto upstream_index : upstream_indices) { result = fake_upstreams_[upstream_index]->waitForHttpConnection( *dispatcher_, fake_upstream_connection_, TestUtility::DefaultTimeout, max_request_headers_kb_); if (result) { upstream_with_request = upstream_index; break; } } RELEASE_ASSERT(result, result.message()); } // Wait for the next stream on the upstream connection. AssertionResult result = fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_); RELEASE_ASSERT(result, result.message()); // Wait for the stream to be completely received. result = upstream_request_->waitForEndStream(*dispatcher_); RELEASE_ASSERT(result, result.message()); return upstream_with_request; }
CWE-400
2
static Status ValidateSavedTensors(const GraphDef& graph_def) { for (const auto& node : graph_def.node()) { const auto node_iterator = node.attr().find("value"); if (node_iterator != node.attr().end()) { AttrValue node_value = node_iterator->second; if (node_value.has_tensor()) { const PartialTensorShape node_shape(node_value.tensor().tensor_shape()); if (node_shape.num_elements() < 0) { return errors::FailedPrecondition( "Saved model contains node \"", node.name(), "\" (op \"", node.op(), "\") which initializes from a tensor with ", node_shape.num_elements(), " elements"); } } } else if (node.op() == "Const") { return errors::FailedPrecondition( "Saved model contains node \"", node.name(), "\" which is a constant tensor but no value has been provided"); } } return Status::OK(); }
CWE-20
0
TEST_F(QuantizedConv2DTest, OddPaddingBatch) { const int stride = 2; TF_ASSERT_OK(NodeDefBuilder("quantized_conv_op", "QuantizedConv2D") .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Attr("out_type", DataTypeToEnum<qint32>::v()) .Attr("strides", {1, stride, stride, 1}) .Attr("padding", "SAME") .Finalize(node_def())); TF_ASSERT_OK(InitOp()); const int depth = 1; const int image_width = 4; const int image_height = 4; const int image_batch_count = 3; AddInputFromArray<quint8>( TensorShape({image_batch_count, image_height, image_width, depth}), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); const int filter_size = 3; const int filter_count = 1; AddInputFromArray<quint8>( TensorShape({filter_size, filter_size, depth, filter_count}), {1, 2, 3, 4, 5, 6, 7, 8, 9}); AddInputFromArray<float>(TensorShape({1}), {0}); AddInputFromArray<float>(TensorShape({1}), {255.0f}); AddInputFromArray<float>(TensorShape({1}), {0}); AddInputFromArray<float>(TensorShape({1}), {255.0f}); TF_ASSERT_OK(RunOpKernel()); const int expected_width = image_width / stride; const int expected_height = (image_height * filter_count) / stride; Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height, expected_width, filter_count})); test::FillValues<qint32>(&expected, {348, 252, 274, 175, // 348, 252, 274, 175, // 348, 252, 274, 175}); test::ExpectTensorEqual<qint32>(expected, *GetOutput(0)); }
CWE-20
0
inline boost::system::error_code make_error_code(error_code_enum e) { return boost::system::error_code(e, get_bdecode_category()); }
CWE-119
26
ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) { if (streamId == 0) { goawayErrorMessage_ = folly::to<string>( "GOAWAY error: received streamID=", streamId, " as invalid new stream for lastStreamID_=", lastStreamID_); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } parsingDownstreamTrailers_ = trailersAllowed && (streamId <= lastStreamID_); if (parsingDownstreamTrailers_) { VLOG(4) << "Parsing downstream trailers streamId=" << streamId; } if (sessionClosing_ != ClosingState::CLOSED) { lastStreamID_ = streamId; } if (isInitiatedStream(streamId)) { // this stream should be initiated by us, not by peer goawayErrorMessage_ = folly::to<string>( "GOAWAY error: invalid new stream received with streamID=", streamId); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } else { return ErrorCode::NO_ERROR; } }
CWE-20
0
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; 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 (!(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_mul(cmpt->width_, cmpt->height_, &size) || !jas_safe_size_mul(size, 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; }
CWE-20
0
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; }
CWE-119
26
R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { if (!sz) { return NULL; } ut64 offset = 0; RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); offset += 6; if (!attr) { return NULL; } attr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR; // if (buffer + offset > buffer + sz) return NULL; attr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->size = offset; // IFDBG r_bin_java_print_source_code_file_attr_summary(attr); return attr; }
CWE-119
26
CString CZNC::FixupEncoding(const CString& sEncoding) const { if (sEncoding.empty() && m_uiForceEncoding) { return "UTF-8"; } return sEncoding; }
CWE-20
0
bool PamBackend::start(const QString &user) { bool result; QString service = QStringLiteral("sddm"); if (user == QStringLiteral("sddm") && m_greeter) service = QStringLiteral("sddm-greeter"); else if (m_app->session()->path().isEmpty()) service = QStringLiteral("sddm-check"); else if (m_autologin) service = QStringLiteral("sddm-autologin"); result = m_pam->start(service, user); if (!result) m_app->error(m_pam->errorString(), Auth::ERROR_INTERNAL); return result; }
CWE-287
4
set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers) { char *startCur = ciphers; int algCount = 0; static ALG_ID algIds[45]; /*There are 45 listed in the MS headers*/ while(startCur && (0 != *startCur) && (algCount < 45)) { long alg = strtol(startCur, 0, 0); if(!alg) alg = get_alg_id_by_name(startCur); if(alg) algIds[algCount++] = alg; else if(!strncmp(startCur, "USE_STRONG_CRYPTO", sizeof("USE_STRONG_CRYPTO") - 1) || !strncmp(startCur, "SCH_USE_STRONG_CRYPTO", sizeof("SCH_USE_STRONG_CRYPTO") - 1)) schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO; else return CURLE_SSL_CIPHER; startCur = strchr(startCur, ':'); if(startCur) startCur++; } schannel_cred->palgSupportedAlgs = algIds; schannel_cred->cSupportedAlgs = algCount; return CURLE_OK; }
CWE-668
7
TEST_F(SingleAllowMissingInOrListTest, MissingIssToken) { EXPECT_CALL(mock_cb_, onComplete(Status::Ok)); auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, ES256WithoutIssToken}}; context_ = Verifier::createContext(headers, parent_span_, &mock_cb_); verifier_->verify(context_); EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kExampleHeader)); }
CWE-287
4
bool CSecurityTLS::processMsg(CConnection* cc) { rdr::InStream* is = cc->getInStream(); rdr::OutStream* os = cc->getOutStream(); client = cc; initGlobal(); if (!session) { if (!is->checkNoWait(1)) return false; if (is->readU8() == 0) { rdr::U32 result = is->readU32(); CharArray reason; if (result == secResultFailed || result == secResultTooMany) reason.buf = is->readString(); else reason.buf = strDup("Authentication failure (protocol error)"); throw AuthFailureException(reason.buf); } if (gnutls_init(&session, GNUTLS_CLIENT) != GNUTLS_E_SUCCESS) throw AuthFailureException("gnutls_init failed"); if (gnutls_set_default_priority(session) != GNUTLS_E_SUCCESS) throw AuthFailureException("gnutls_set_default_priority failed"); setParam(); } rdr::TLSInStream *tlsis = new rdr::TLSInStream(is, session); rdr::TLSOutStream *tlsos = new rdr::TLSOutStream(os, session); int err; err = gnutls_handshake(session); if (err != GNUTLS_E_SUCCESS) { delete tlsis; delete tlsos; if (!gnutls_error_is_fatal(err)) return false; vlog.error("TLS Handshake failed: %s\n", gnutls_strerror (err)); shutdown(false); throw AuthFailureException("TLS Handshake failed"); } checkSession(); cc->setStreams(fis = tlsis, fos = tlsos); return true; }
CWE-119
26
CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2, value n) { memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n)); return Val_unit; }
CWE-200
10
int Bind(const Node& node, int max_retry) override { receiver_ = zmq_socket(context_, ZMQ_ROUTER); CHECK(receiver_ != NULL) << "create receiver socket failed: " << zmq_strerror(errno); int local = GetEnv("DMLC_LOCAL", 0); std::string addr = local ? "ipc:///tmp/" : "tcp://*:"; int port = node.port; unsigned seed = static_cast<unsigned>(time(NULL)+port); for (int i = 0; i < max_retry+1; ++i) { auto address = addr + std::to_string(port); if (zmq_bind(receiver_, address.c_str()) == 0) break; if (i == max_retry) { port = -1; } else { port = 10000 + rand_r(&seed) % 40000; } } return port; }
CWE-200
10
bool DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len) { if ( ! target_len ) return true; int to_copy = min(*len, target_len - endp->buffer_len); memcpy(endp->buffer + endp->buffer_len, *data, to_copy); *data += to_copy; *len -= to_copy; endp->buffer_len += to_copy; return endp->buffer_len == target_len; }
CWE-119
26
void skip(Protocol_& prot, TType arg_type) { switch (arg_type) { case TType::T_BOOL: { bool boolv; prot.readBool(boolv); return; } case TType::T_BYTE: { int8_t bytev; prot.readByte(bytev); return; } case TType::T_I16: { int16_t i16; prot.readI16(i16); return; } case TType::T_I32: { int32_t i32; prot.readI32(i32); return; } case TType::T_I64: { int64_t i64; prot.readI64(i64); return; } case TType::T_DOUBLE: { double dub; prot.readDouble(dub); return; } case TType::T_FLOAT: { float flt; prot.readFloat(flt); return; } case TType::T_STRING: { std::string str; prot.readBinary(str); return; } case TType::T_STRUCT: { std::string name; int16_t fid; TType ftype; prot.readStructBegin(name); while (true) { prot.readFieldBegin(name, ftype, fid); if (ftype == TType::T_STOP) { break; } apache::thrift::skip(prot, ftype); prot.readFieldEnd(); } prot.readStructEnd(); return; } case TType::T_MAP: { TType keyType; TType valType; uint32_t i, size; prot.readMapBegin(keyType, valType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, keyType); apache::thrift::skip(prot, valType); } prot.readMapEnd(); return; } case TType::T_SET: { TType elemType; uint32_t i, size; prot.readSetBegin(elemType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, elemType); } prot.readSetEnd(); return; } case TType::T_LIST: { TType elemType; uint32_t i, size; prot.readListBegin(elemType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, elemType); } prot.readListEnd(); return; } default: return; } }
CWE-755
21
TEST_P(Http2CodecImplTest, TestLargeRequestHeadersAtLimitAccepted) { uint32_t codec_limit_kb = 64; max_request_headers_kb_ = codec_limit_kb; initialize(); TestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); std::string key = "big"; uint32_t head_room = 77; uint32_t long_string_length = codec_limit_kb * 1024 - request_headers.byteSize() - key.length() - head_room; std::string long_string = std::string(long_string_length, 'q'); request_headers.addCopy(key, long_string); // The amount of data sent to the codec is not equivalent to the size of the // request headers that Envoy computes, as the codec limits based on the // entire http2 frame. The exact head room needed (76) was found through iteration. ASSERT_EQ(request_headers.byteSize() + head_room, codec_limit_kb * 1024); EXPECT_CALL(request_decoder_, decodeHeaders_(_, _)); request_encoder_->encodeHeaders(request_headers, true); }
CWE-400
2
void jslGetTokenString(char *str, size_t len) { if (lex->tk == LEX_ID) { strncpy(str, "ID:", len); strncat(str, jslGetTokenValueAsString(), len); } else if (lex->tk == LEX_STR) { strncpy(str, "String:'", len); strncat(str, jslGetTokenValueAsString(), len); strncat(str, "'", len); } else jslTokenAsString(lex->tk, str, len); }
CWE-119
26
mptctl_replace_fw (unsigned long arg) { struct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg; struct mpt_ioctl_replace_fw karg; MPT_ADAPTER *ioc; int iocnum; int newFwSize; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_replace_fw - " "Unable to read in mpt_ioctl_replace_fw struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_replace_fw() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_replace_fw called.\n", ioc->name)); /* If caching FW, Free the old FW image */ if (ioc->cached_fw == NULL) return 0; mpt_free_fw_memory(ioc); /* Allocate memory for the new FW image */ newFwSize = ALIGN(karg.newImageSize, 4); mpt_alloc_fw_memory(ioc, newFwSize); if (ioc->cached_fw == NULL) return -ENOMEM; /* Copy the data from user memory to kernel space */ if (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_replace_fw - " "Unable to read in mpt_ioctl_replace_fw image " "@ %p\n", ioc->name, __FILE__, __LINE__, uarg); mpt_free_fw_memory(ioc); return -EFAULT; } /* Update IOCFactsReply */ ioc->facts.FWImageSize = newFwSize; return 0; }
CWE-362
18
USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const { USHORT Res; auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset), GetDataLength(), __FUNCTION__); if (ppr.ipStatus != ppresNotIP) { Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize); } else { DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__)); Res = 0; } return Res; }
CWE-20
0
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset) { gint64 offset; int pkt_len; char line[COSINE_LINE_LENGTH]; /* Find the next packet */ offset = cosine_seek_next_packet(wth, err, err_info, line); if (offset < 0) return FALSE; *data_offset = offset; /* Parse the header */ pkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info); if (pkt_len == -1) return FALSE; /* Convert the ASCII hex dump to binary data */ return parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len, wth->frame_buffer, err, err_info); }
CWE-119
26
static int em_fxrstor(struct x86_emulate_ctxt *ctxt) { struct fxregs_state fx_state; int rc; rc = check_fxsr(ctxt); if (rc != X86EMUL_CONTINUE) return rc; rc = segmented_read(ctxt, ctxt->memop.addr.mem, &fx_state, 512); if (rc != X86EMUL_CONTINUE) return rc; if (fx_state.mxcsr >> 16) return emulate_gp(ctxt, 0); ctxt->ops->get_fpu(ctxt); if (ctxt->mode < X86EMUL_MODE_PROT64) rc = fxrstor_fixup(ctxt, &fx_state); if (rc == X86EMUL_CONTINUE) rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state)); ctxt->ops->put_fpu(ctxt); return rc; }
CWE-200
10
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; }
CWE-119
26
static inline ulong encode_twos_comp(long n, int prec) { ulong result; assert(prec >= 2); jas_eprintf("warning: support for signed data is untested\n"); // NOTE: Is this correct? if (n < 0) { result = -n; result = (result ^ 0xffffffffUL) + 1; result &= (1 << prec) - 1; } else { result = n; } return result; }
CWE-20
0
int ecall_restore(const char *input, uint64_t input_len, char **output, uint64_t *output_len) { if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input, input_len)) { asylo::primitives::TrustedPrimitives::BestEffortAbort( "ecall_restore: input found to not be in untrusted memory."); } int result = 0; size_t tmp_output_len; try { result = asylo::Restore(input, static_cast<size_t>(input_len), output, &tmp_output_len); } catch (...) { LOG(FATAL) << "Uncaught exception in enclave"; } if (output_len) { *output_len = static_cast<uint64_t>(tmp_output_len); } return result; }
CWE-119
26
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt( const SaplingEncCiphertext &ciphertext, const uint256 &epk, const uint256 &esk, const uint256 &pk_d, const uint256 &cmu ) { auto pt = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d); if (!pt) { return boost::none; } // Deserialize from the plaintext CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pt.get(); SaplingNotePlaintext ret; ss >> ret; uint256 cmu_expected; if (!librustzcash_sapling_compute_cm( ret.d.data(), pk_d.begin(), ret.value(), ret.rcm.begin(), cmu_expected.begin() )) { return boost::none; } if (cmu_expected != cmu) { return boost::none; } assert(ss.size() == 0); return ret; }
CWE-755
21
void InferenceContext::PreInputInit( const OpDef& op_def, const std::vector<const Tensor*>& input_tensors, const std::vector<ShapeHandle>& input_tensors_as_shapes) { // TODO(mdan): This is also done at graph construction. Run only here instead? const auto ret = full_type::SpecializeType(attrs_, op_def); DCHECK(ret.status().ok()) << "while instantiating types: " << ret.status(); ret_types_ = ret.ValueOrDie(); input_tensors_ = input_tensors; input_tensors_as_shapes_ = input_tensors_as_shapes; construction_status_ = NameRangesForNode(attrs_, op_def, &input_name_map_, &output_name_map_); if (!construction_status_.ok()) return; int num_outputs = 0; for (const auto& e : output_name_map_) { num_outputs = std::max(num_outputs, e.second.second); } outputs_.assign(num_outputs, nullptr); output_handle_shapes_and_types_.resize(num_outputs); }
CWE-754
31
DSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len, RandomNumberGenerator& rng) { const BigInt& q = m_group.get_q(); BigInt i(msg, msg_len, q.bits()); while(i >= q) i -= q; #if defined(BOTAN_HAS_RFC6979_GENERATOR) BOTAN_UNUSED(rng); const BigInt k = generate_rfc6979_nonce(m_x, q, i, m_rfc6979_hash); #else const BigInt k = BigInt::random_integer(rng, 1, q); #endif BigInt s = inverse_mod(k, q); const BigInt r = m_mod_q.reduce(m_group.power_g_p(k)); s = m_mod_q.multiply(s, mul_add(m_x, r, i)); // With overwhelming probability, a bug rather than actual zero r/s if(r.is_zero() || s.is_zero()) throw Internal_Error("Computed zero r/s during DSA signature"); return BigInt::encode_fixed_length_int_pair(r, s, q.bytes()); }
CWE-200
10
error_t tcpAddOption(TcpHeader *segment, uint8_t kind, const void *value, uint8_t length) { uint_t i; size_t paddingSize; TcpOption *option; //Length of the complete option field length += sizeof(TcpOption); //Make sure there is enough space to add the specified option if((segment->dataOffset * 4 + length) > TCP_MAX_HEADER_LENGTH) return ERROR_FAILURE; //Index of the first available byte i = segment->dataOffset * 4 - sizeof(TcpHeader); //Calculate the number of padding bytes paddingSize = (length % 4) ? 4 - (length % 4) : 0; //Write padding bytes while(paddingSize--) segment->options[i++] = TCP_OPTION_NOP; //Point to the current location option = (TcpOption *) (segment->options + i); //Write specified option option->kind = kind; option->length = length; osMemcpy(option->value, value, length - sizeof(TcpOption)); //Adjust index value i += length; //Update TCP header length segment->dataOffset = (sizeof(TcpHeader) + i) / 4; //Option successfully added return NO_ERROR; }
CWE-20
0
mptctl_readtest (unsigned long arg) { struct mpt_ioctl_test __user *uarg = (void __user *) arg; struct mpt_ioctl_test karg; MPT_ADAPTER *ioc; int iocnum; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_readtest - " "Unable to read in mpt_ioctl_test struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_readtest() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_readtest called.\n", ioc->name)); /* Fill in the data and return the structure to the calling * program */ #ifdef MFCNT karg.chip_type = ioc->mfcnt; #else karg.chip_type = ioc->pcidev->device; #endif strncpy (karg.name, ioc->name, MPT_MAX_NAME); karg.name[MPT_MAX_NAME-1]='\0'; strncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH); karg.product[MPT_PRODUCT_LENGTH-1]='\0'; /* Copy the data from kernel memory to user memory */ if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_test))) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_readtest - " "Unable to write out mpt_ioctl_test struct @ %p\n", ioc->name, __FILE__, __LINE__, uarg); return -EFAULT; } return 0; }
CWE-362
18
jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms, int clrspc) { jas_image_t *image; uint_fast32_t rawsize; uint_fast32_t inmem; int cmptno; jas_image_cmptparm_t *cmptparm; if (!(image = jas_image_create0())) { return 0; } 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 *)))) { jas_image_destroy(image); return 0; } /* Initialize in case of failure. */ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) { image->cmpts_[cmptno] = 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); /* Create the individual image components. */ for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { 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))) { jas_image_destroy(image); return 0; } ++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; }
CWE-20
0
void ZlibInStream::removeUnderlying() { ptr = end = start; if (!underlying) return; while (bytesIn > 0) { decompress(true); end = start; // throw away any data } underlying = 0; }
CWE-672
37
error_t coapServerFormatReset(CoapServerContext *context, uint16_t mid) { CoapMessageHeader *header; //Point to the CoAP response header header = (CoapMessageHeader *) context->response.buffer; //Format Reset message header->version = COAP_VERSION_1; header->type = COAP_TYPE_RST; header->tokenLen = 0; header->code = COAP_CODE_EMPTY; //The Reset message message must echo the message ID of the confirmable //message and must be empty (refer to RFC 7252, section 4.2) header->mid = htons(mid); //Set the length of the CoAP message context->response.length = sizeof(CoapMessageHeader); //Sucessful processing return NO_ERROR; }
CWE-20
0
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller) { tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size); PrintOutParsingResult(res, 1, caller); return res; }
CWE-20
0
void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen) { SparseArraySegment<T>* headSeg = (SparseArraySegment<T>*)pArr->head; SparseArraySegment<T>* pnewHeadSeg = (SparseArraySegment<T>*)pnewArr->head; // Fill the newly created sliced array js_memcpy_s(pnewHeadSeg->elements, sizeof(T) * newLen, headSeg->elements + start, sizeof(T) * newLen); pnewHeadSeg->length = newLen; Assert(pnewHeadSeg->length <= pnewHeadSeg->size); // Prototype lookup for missing elements if (!pArr->HasNoMissingValues()) { for (uint32 i = 0; i < newLen; i++) { // array type might be changed in the below call to DirectGetItemAtFull // need recheck array type before checking array item [i + start] if (pArr->IsMissingItem(i + start)) { Var element; pnewArr->SetHasNoMissingValues(false); if (pArr->DirectGetItemAtFull(i + start, &element)) { pnewArr->SetItem(i, element, PropertyOperation_None); } } } } #ifdef DBG else { for (uint32 i = 0; i < newLen; i++) { AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value"); } } #endif }
CWE-200
10
TEST_F(HttpConnectionManagerImplTest, OverlyLongHeadersAcceptedIfConfigured) { max_request_headers_kb_ = 62; setup(false, ""); EXPECT_CALL(*codec_, dispatch(_)).WillOnce(Invoke([&](Buffer::Instance&) -> void { StreamDecoder* decoder = &conn_manager_->newStream(response_encoder_); HeaderMapPtr headers{ new TestHeaderMapImpl{{":authority", "host"}, {":path", "/"}, {":method", "GET"}}}; headers->addCopy(LowerCaseString("Foo"), std::string(60 * 1024, 'a')); EXPECT_CALL(response_encoder_, encodeHeaders(_, _)).Times(0); decoder->decodeHeaders(std::move(headers), true); conn_manager_->newStream(response_encoder_); })); Buffer::OwnedImpl fake_input("1234"); conn_manager_->onData(fake_input, false); // kick off request }
CWE-400
2
DSA_Signature_Operation(const DSA_PrivateKey& dsa, const std::string& emsa) : PK_Ops::Signature_with_EMSA(emsa), m_group(dsa.get_group()), m_x(dsa.get_x()), m_mod_q(dsa.group_q()) { #if defined(BOTAN_HAS_RFC6979_GENERATOR) m_rfc6979_hash = hash_for_emsa(emsa); #endif }
CWE-200
10
GetRunner( const ReferenceHandle& that, Local<Value> key_handle, MaybeLocal<Object> maybe_options, bool inherit ) : context{that.context}, reference{that.reference}, options{maybe_options, inherit ? TransferOptions::Type::DeepReference : TransferOptions::Type::Reference}, inherit{inherit} { that.CheckDisposed(); key = ExternalCopy::CopyIfPrimitive(key_handle); if (!key) { throw RuntimeTypeError("Invalid `key`"); } }
CWE-913
24
void onComplete(const Status& status, ContextImpl& context) const override { auto& completion_state = context.getCompletionState(this); if (completion_state.is_completed_) { return; } // If any of children is OK, return OK if (Status::Ok == status) { completion_state.is_completed_ = true; completeWithStatus(status, context); return; } // Then wait for all children to be done. if (++completion_state.number_completed_children_ == verifiers_.size()) { // Aggregate all children status into a final status. // JwtMissing should be treated differently than other failure status // since it simply means there is not Jwt token for the required provider. // If there is a failure status other than JwtMissing in the children, // it should be used as the final status. Status final_status = Status::JwtMissed; for (const auto& it : verifiers_) { // If a Jwt is extracted from a location not specified by the required provider, // the authenticator returns JwtUnknownIssuer. It should be treated the same as // JwtMissed. Status child_status = context.getCompletionState(it.get()).status_; if (child_status != Status::JwtMissed && child_status != Status::JwtUnknownIssuer) { final_status = child_status; } } if (is_allow_missing_or_failed_) { final_status = Status::Ok; } else if (is_allow_missing_ && final_status == Status::JwtMissed) { final_status = Status::Ok; } completion_state.is_completed_ = true; completeWithStatus(final_status, context); } }
CWE-287
4
int linenoiseHistorySave(const char* filename) { FILE* fp = fopen(filename, "wt"); if (fp == NULL) { return -1; } for (int j = 0; j < historyLen; ++j) { if (history[j][0] != '\0') { fprintf(fp, "%s\n", history[j]); } } fclose(fp); return 0; }
CWE-200
10
int jas_memdump(FILE *out, void *data, size_t len) { size_t i; size_t j; uchar *dp; dp = data; for (i = 0; i < len; i += 16) { fprintf(out, "%04zx:", i); for (j = 0; j < 16; ++j) { if (i + j < len) { fprintf(out, " %02x", dp[i + j]); } } fprintf(out, "\n"); } return 0; }
CWE-20
0
void RemoteDevicePropertiesWidget::setType() { if (Type_SshFs==type->itemData(type->currentIndex()).toInt() && 0==sshPort->value()) { sshPort->setValue(22); } if (Type_Samba==type->itemData(type->currentIndex()).toInt() && 0==smbPort->value()) { smbPort->setValue(445); } }
CWE-20
0
it 'activates user when must_approve_users? is enabled' do SiteSetting.must_approve_users = true invite.invited_by = Fabricate(:admin) user = invite.redeem expect(user.approved?).to eq(true) end
CWE-863
11
def comments_closed? !(allow_comments? && in_feedback_window?) end
CWE-863
11
def package_index valid_http_methods :get required_parameters :project, :repository, :arch, :package # read access permission check if params[:package] == "_repository" prj = DbProject.get_by_name params[:project], use_source=false else pkg = DbPackage.get_by_project_and_name params[:project], params[:package], use_source=false end pass_to_backend end
CWE-20
0
it "updates the record matching selector with change" do session.should_receive(:with, :consistency => :strong). and_yield(session) session.should_receive(:execute).with do |update| update.flags.should eq [] update.selector.should eq query.operation.selector update.update.should eq change end query.update change end
CWE-20
0
it "raises an exception" do expect { session.current_database }.to raise_exception end
CWE-20
0
it "returns the count" do database.stub(command: { "n" => 4 }) query.count.should eq 4 end
CWE-20
0
def self.reminders(options={}) days = options[:days] || 7 project = options[:project] ? Project.find(options[:project]) : nil tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil if options[:version] && target_version_id.blank? raise ActiveRecord::RecordNotFound.new("Couldn't find Version with named #{options[:version]}") end user_ids = options[:users] scope = Issue.open.where("#{Issue.table_name}.assigned_to_id IS NOT NULL" + " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" + " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date ) scope = scope.where(:assigned_to_id => user_ids) if user_ids.present? scope = scope.where(:project_id => project.id) if project scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present? scope = scope.where(:tracker_id => tracker.id) if tracker issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker). group_by(&:assigned_to) issues_by_assignee.keys.each do |assignee| if assignee.is_a?(Group) assignee.users.each do |user| issues_by_assignee[user] ||= [] issues_by_assignee[user] += issues_by_assignee[assignee] end end end issues_by_assignee.each do |assignee, issues| reminder(assignee, issues, days).deliver if assignee.is_a?(User) && assignee.active? end end
CWE-200
10
it 'returns the right response' do get "/session/email-login/adasdad" expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to match( I18n.t('email_login.invalid_token') ) end
CWE-287
4
def socket_for(mode) if options[:retain_socket] @socket ||= cluster.socket_for(mode) else cluster.socket_for(mode) end end
CWE-400
2
def index valid_http_methods :get, :post, :put # for permission check if params[:package] and not ["_repository", "_jobhistory"].include?(params[:package]) pkg = DbPackage.get_by_project_and_name( params[:project], params[:package], use_source=false ) else prj = DbProject.get_by_name params[:project] end pass_to_backend end
CWE-20
0
it "yields all indexes on the collection" do indexes.to_a.should eq \ session[:"system.indexes"].find(ns: "moped_test.users").to_a end
CWE-20
0
def test_update_valid Medium.any_instance.stubs(:valid?).returns(true) put :update, {:id => Medium.first, :medium => {:name => "MyUpdatedMedia"}}, set_session_user assert_redirected_to media_url end
CWE-200
10
it 'fails when local logins via email is disabled' do SiteSetting.enable_local_logins_via_email = false get "/session/email-login/#{email_token.token}" expect(response.status).to eq(404) end
CWE-287
4
it "defaults to an empty selector" do Moped::Query.should_receive(:new). with(collection, {}).and_return(query) collection.find.should eq query end
CWE-400
2
def self.password_reset_via_token(token, password) # check token user = by_reset_token(token) return if !user # reset password user.update!(password: password) # delete token Token.find_by(action: 'PasswordReset', name: token).destroy user end
CWE-863
11
def bulk_unread_topic_ids topic_query = TopicQuery.new(current_user) if inbox = params[:private_message_inbox] filter = private_message_filter(topic_query, inbox) topic_query.options[:limit] = false topic_query .filter_private_messages_unread(current_user, filter) .distinct(false) .pluck(:id) else topics = TopicQuery.unread_filter(topic_query.joined_topic_user, staff: guardian.is_staff?).listable_topics topics = TopicQuery.tracked_filter(topics, current_user.id) if params[:tracked].to_s == "true" if params[:category_id] if params[:include_subcategories] topics = topics.where(<<~SQL, category_id: params[:category_id]) category_id in (select id FROM categories WHERE parent_category_id = :category_id) OR category_id = :category_id SQL else topics = topics.where('category_id = ?', params[:category_id]) end end if params[:tag_name].present? topics = topics.joins(:tags).where("tags.name": params[:tag_name]) end topics.pluck(:id) end end
CWE-863
11
it "should unstage user" do staged_user = Fabricate(:staged, email: '[email protected]', active: true, username: 'staged1', name: 'Stage Name') invite = Fabricate(:invite, email: '[email protected]') user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White') expect(user.id).to eq(staged_user.id) expect(user.username).to eq('walter') expect(user.name).to eq('Walter White') expect(user.staged).to eq(false) expect(user.email).to eq('[email protected]') expect(user.approved).to eq(true) end
CWE-863
11
it 'does not log in with incorrect two factor' do post "/session/email-login/#{email_token.token}", params: { second_factor_token: "0000", second_factor_method: UserSecondFactor.methods[:totp] } expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to include(I18n.t( "login.invalid_second_factor_code" )) end
CWE-287
4
def test_update_valid Subnet.any_instance.stubs(:valid?).returns(true) put :update, {:id => Subnet.first, :subnet => {:network => '192.168.100.10'}}, set_session_user assert_equal '192.168.100.10', Subnet.first.network assert_redirected_to subnets_url end
CWE-200
10
it 'does not log in with incorrect backup code' do post "/session/email-login/#{email_token.token}", params: { second_factor_token: "0000", second_factor_method: UserSecondFactor.methods[:backup_codes] } expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to include(I18n.t( "login.invalid_second_factor_code" )) end
CWE-287
4
def private_message_reset_new topic_query = TopicQuery.new(current_user, limit: false) if params[:topic_ids].present? unless Array === params[:topic_ids] raise Discourse::InvalidParameters.new( "Expecting topic_ids to contain a list of topic ids" ) end topic_scope = topic_query .private_messages_for(current_user, :all) .where("topics.id IN (?)", params[:topic_ids].map(&:to_i)) else params.require(:inbox) inbox = params[:inbox].to_s filter = private_message_filter(topic_query, inbox) topic_scope = topic_query.filter_private_message_new(current_user, filter) end topic_ids = TopicsBulkAction.new( current_user, topic_scope.distinct(false).pluck(:id), type: "dismiss_topics" ).perform! render json: success_json.merge(topic_ids: topic_ids) end
CWE-863
11
it "returns the database from the options" do session.current_database.should eq(database) end
CWE-20
0
it "sets slave_ok on the query flags" do session.stub(socket_for: socket) socket.should_receive(:execute) do |query| query.flags.should include :slave_ok end session.query(query) end
CWE-20
0
def decode_compact_serialized(input, public_key_or_secret, algorithms = nil, allow_blank_payload = false) unless input.count('.') + 1 == NUM_OF_SEGMENTS raise InvalidFormat.new("Invalid JWS Format. JWS should include #{NUM_OF_SEGMENTS} segments.") end header, claims, signature = input.split('.', JWS::NUM_OF_SEGMENTS).collect do |segment| Base64.urlsafe_decode64 segment.to_s end header = JSON.parse(header).with_indifferent_access if allow_blank_payload && claims == '' claims = nil else claims = JSON.parse(claims).with_indifferent_access end jws = new claims jws.header = header jws.signature = signature jws.signature_base_string = input.split('.')[0, JWS::NUM_OF_SEGMENTS - 1].join('.') jws.verify! public_key_or_secret, algorithms unless public_key_or_secret == :skip_verification jws end
CWE-287
4
it 'does not log in with incorrect backup code' do post "/session/email-login/#{email_token.token}", params: { second_factor_token: "0000", second_factor_method: UserSecondFactor.methods[:backup_codes] } expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to include(I18n.t( "login.invalid_second_factor_code" )) end
CWE-287
4
def piped_category_name(category_id) return "-" unless category_id category = Category.find_by(id: category_id) return "#{category_id}" unless category categories = [category.name] while category.parent_category_id && category = category.parent_category categories << category.name end categories.reverse.join("|") end
CWE-200
10
def logout(database) auth.delete(database.to_s) end
CWE-400
2
def login(database, username, password) auth[database.to_s] = [username, password] end
CWE-400
2
it "returns true" do Moped::BSON::ObjectId.new(bytes).should == Moped::BSON::ObjectId.new(bytes) end
CWE-400
2
def one_time_password otp_username = $redis.get "otp_#{params[:token]}" if otp_username && user = User.find_by_username(otp_username) log_on_user(user) $redis.del "otp_#{params[:token]}" return redirect_to path("/") else @error = I18n.t('user_api_key.invalid_token') end render layout: 'no_ember' end
CWE-287
4
it "stores the database" do collection.database.should eq database end
CWE-20
0
def each cursor = Cursor.new(session.with(retain_socket: true), operation) cursor.to_enum.tap do |enum| enum.each do |document| yield document end if block_given? end end
CWE-400
2