text
stringlengths
478
227k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; int strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'URL sanitize: reject URLs containing bad data Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a decoded manner now use the new Curl_urldecode() function to reject URLs with embedded control codes (anything that is or decodes to a byte value less than 32). URLs containing such codes could easily otherwise be used to do harm and allow users to do unintended actions with otherwise innocent tools and applications. Like for example using a URL like pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get a mail and instead this would delete one. This flaw is considered a security vulnerability: CVE-2012-0036 Security advisory at: http://curl.haxx.se/docs/adv_20120124.html Reported by: Dan Fandrich'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void operator()(OpKernelContext* ctx, const CPUDevice& d, int64 num_batches, int64 samples_per_batch, int64 num_elements, const BCastList<4>& bcast, typename TTypes<T>::ConstFlat means, typename TTypes<T>::ConstFlat stddevs, typename TTypes<T>::ConstFlat minvals, typename TTypes<T>::ConstFlat maxvals, const random::PhiloxRandom& gen, typename TTypes<T>::Flat output) { // The randn rejection sampling is used when the mean and at least this many // standard deviations are inside the bounds. // The uniform proposal samplers become less efficient as the bounds are // further from the mean, the reverse is true for the randn sampler. // This number was chosen by empirical benchmarking. If modified, the // benchmarks in parameterized_truncated_normal_op_test should also be // changed. const T kStdDevsInsideBoundsToUseRandnSampler = T(1.3); auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads()); auto do_work = [num_batches, samples_per_batch, &ctx, &bcast, &means, &stddevs, &minvals, &maxvals, &gen, &output, kStdDevsInsideBoundsToUseRandnSampler](int start_output, int limit_output) { // Capturing "gen" by-value would only make a copy for the _shared_ // lambda. Since we want to let each worker have its own copy, we pass // "gen" by reference and explicitly do a copy assignment here. random::PhiloxRandom gen_copy = gen; using Uniform = random::UniformDistribution<random::PhiloxRandom, T>; Uniform dist; using Normal = random::NormalDistribution<random::PhiloxRandom, T>; Normal normal_dist; // Skip takes units of 128 bits. The Uniform::kResultElementCount - 1 // is so rounding doesn't lead to // us using the same state in different workloads. // The sample from each iteration uses 2 random numbers. gen_copy.Skip((start_output * 2 * kMaxIterations + Uniform::kResultElementCount - 1) / Uniform::kResultElementCount); // Vectorized intermediate calculations for uniform rejection sampling. // We always generate at most 4 samples. Eigen::array<T, Uniform::kResultElementCount> z; Eigen::array<T, Uniform::kResultElementCount> g; const bool should_bcast = bcast.IsBroadcastingRequired(); const auto& means_batch_indices = bcast.batch_indices(0); const auto& stddevs_batch_indices = bcast.batch_indices(1); const auto& minvals_batch_indices = bcast.batch_indices(2); const auto& maxvals_batch_indices = bcast.batch_indices(3); auto output_flat = output.data(); // We partition work across batches and then across samples // per batch member, to avoid extra work. for (int64 output_idx = start_output; output_idx < limit_output; // output_idx is incremented with the inner loops below. ) { int64 batch_idx = output_idx / samples_per_batch; // The output layout is [samples_per_batch, num_batches]. Thus // the output address is sample_idx * num_batches + batch_idx. // Below, code will index at output_batch_offset[sample_idx * // num_batches] matching this. T* const output_batch_offset = output_flat + batch_idx; // Generate batch counts from BCast, as it has the right indices to loop // over. T mean, stddev, minval, maxval; if (should_bcast) { mean = means(means_batch_indices[batch_idx]); stddev = stddevs(stddevs_batch_indices[batch_idx]); minval = minvals(minvals_batch_indices[batch_idx]); maxval = maxvals(maxvals_batch_indices[batch_idx]); } else { mean = means(batch_idx); stddev = stddevs(batch_idx); minval = minvals(batch_idx); maxval = maxvals(batch_idx); } // On GPU, this check will just fill samples with NAN if it fails. OP_REQUIRES(ctx, stddev > T(0) && minval < maxval && (Eigen::numext::isfinite(minval) || Eigen::numext::isfinite(maxval)), errors::InvalidArgument("Invalid parameters")); int num_iterations = 0; // If possible, make one-sided bound be the lower bound, or make both // bounds positive. Otherwise, the bounds are on either side of the // mean. if ((Eigen::numext::isinf(minval) && minval < T(0)) || maxval < mean) { // Reverse all calculations. normMin and normMax will be flipped. std::swap(minval, maxval); stddev = -stddev; } // Calculate normalized samples, then convert them. const T normMin = (minval - mean) / stddev; const T normMax = (maxval - mean) / stddev; // Determine the method to use. const T sqrtFactor = Eigen::numext::sqrt((normMin * normMin) + T(4)); const T cutoff = T(2) * Eigen::numext::exp(T(0.5) + (normMin * (normMin - sqrtFactor)) / T(4)) / (normMin + sqrtFactor); const T diff = normMax - normMin; if (((normMin < -kStdDevsInsideBoundsToUseRandnSampler) && (normMax >= T(0.))) || ((normMax > kStdDevsInsideBoundsToUseRandnSampler) && (normMin <= T(0.)))) { // If the bounds are a least 3 standard deviations from the mean // on at least one side then we rejection sample by sampling // from the normal distribution and rejecting samples outside // the bounds. // Under this condition the acceptance rate per iteration should // always be ~ 50%. This sampler is more efficient (and more // numerically stable when one or both bounds is far from the mean). for (int64 sample_idx = output_idx % samples_per_batch; sample_idx < samples_per_batch && output_idx < limit_output;) { const auto randn_sample = normal_dist(&gen_copy); const int size = randn_sample.size(); for (int i = 0; i < size; ++i) { if ((randn_sample[i] >= normMin) && (randn_sample[i] <= normMax)) { output_batch_offset[sample_idx * num_batches] = randn_sample[i] * stddev + mean; ++sample_idx; ++output_idx; if (sample_idx >= samples_per_batch || output_idx >= limit_output) { break; } num_iterations = 0; } else { ++num_iterations; if (num_iterations > kMaxIterations) { // This should never occur because this sampler should // (by the selection criteria above) be used if at least 3 // standard deviations of one side of the distribution // is within the limits (so acceptance probability per // iterations >~ 1/2 per iteration). LOG(ERROR) << "TruncatedNormal randn rejection sampler " << "exceeded maximum iterations for " << "normMin=" << normMin << " normMax=" << normMax << " kMaxIterations=" << kMaxIterations; ctx->SetStatus(errors::Internal( "TruncatedNormal randn rejection sampler failed to accept" " a sample.")); return; } } } } } else if (diff < cutoff) { // Sample from a uniform distribution on [normMin, normMax]. const T plusFactor = (normMin < T(0)) ? T(0) : normMin * normMin; for (int64 sample_idx = output_idx % samples_per_batch; sample_idx < samples_per_batch && output_idx < limit_output;) { const auto rand = dist(&gen_copy); const int size = rand.size(); // NOTE(ringwalt): These loops seem to only generate packed AVX // instructions for float32. for (int i = 0; i < size; i++) { z[i] = rand[i] * diff + normMin; g[i] = (plusFactor - z[i] * z[i]) / T(2.0); } const auto u = dist(&gen_copy); for (int i = 0; i < size; i++) { auto accept = u[i] <= Eigen::numext::exp(g[i]); if (accept || num_iterations + 1 >= kMaxIterations) { // Accept the sample z. // If we run out of iterations, just use the current uniform // sample, but emit a warning. // TODO(jjhunt) For small entropies (relative to the bounds), // this sampler is poor and may take many iterations since // the proposal distribution is the uniform distribution // U(lower_bound, upper_bound). if (!accept) { LOG(ERROR) << "TruncatedNormal uniform rejection sampler " << "exceeded max iterations. Sample may contain " << "outliers."; ctx->SetStatus(errors::Internal( "TruncatedNormal uniform rejection sampler failed to " " accept a sample.")); return; } output_batch_offset[sample_idx * num_batches] = z[i] * stddev + mean; ++sample_idx; ++output_idx; if (sample_idx >= samples_per_batch || output_idx >= limit_output) { break; } num_iterations = 0; } else { num_iterations++; } } } } else { // Sample from an exponential distribution with alpha maximizing // acceptance probability, offset by normMin from the origin. // Accept only if less than normMax. const T alpha = (normMin + Eigen::numext::sqrt((normMin * normMin) + T(4))) / T(2); for (int64 sample_idx = output_idx % samples_per_batch; sample_idx < samples_per_batch && output_idx < limit_output;) { auto rand = dist(&gen_copy); const int size = rand.size(); int i = 0; while (i < size) { const T z = -Eigen::numext::log(rand[i]) / alpha + normMin; i++; const T x = normMin < alpha ? alpha - z : normMin - alpha; const T g = Eigen::numext::exp(-x * x / T(2.0)); const T u = rand[i]; i++; auto accept = (u <= g && z < normMax); if (accept || num_iterations + 1 >= kMaxIterations) { if (!accept) { LOG(ERROR) << "TruncatedNormal exponential distribution " << "rejection sampler exceeds max iterations. " << "Sample may contain outliers."; ctx->SetStatus(errors::Internal( "TruncatedNormal exponential distribution rejection" " sampler failed to accept a sample.")); return; } output_batch_offset[sample_idx * num_batches] = z * stddev + mean; ++sample_idx; ++output_idx; if (sample_idx >= samples_per_batch || output_idx >= limit_output) { break; } num_iterations = 0; } else { num_iterations++; } } } } } }; // The cost of the initial calculations for the batch. const int64 batchInitCost = // normMin, normMax (Eigen::TensorOpCost::AddCost<T>() + Eigen::TensorOpCost::MulCost<T>()) * 2 // sqrtFactor + Eigen::TensorOpCost::AddCost<T>() + Eigen::TensorOpCost::MulCost<T>() + Eigen::internal::functor_traits< Eigen::internal::scalar_sqrt_op<T>>::Cost // cutoff + Eigen::TensorOpCost::MulCost<T>() * 4 + Eigen::internal::functor_traits<Eigen::internal::scalar_exp_op<T>>::Cost // diff + Eigen::TensorOpCost::AddCost<T>(); const int64 uniformSampleCost = random::PhiloxRandom::kElementCost + random::UniformDistribution<random::PhiloxRandom, T>::kElementCost; // The cost of a single uniform sampling round. const int64 uniformRejectionSamplingCost = uniformSampleCost + Eigen::TensorOpCost::MulCost<T>() + Eigen::TensorOpCost::AddCost<T>() + Eigen::TensorOpCost::MulCost<T>() * 2 + Eigen::TensorOpCost::AddCost<T>() + uniformSampleCost + Eigen::internal::functor_traits< Eigen::internal::scalar_exp_op<T>>::Cost + Eigen::TensorOpCost::MulCost<T>() + Eigen::TensorOpCost::AddCost<T>(); // Estimate the cost for an entire batch. // Assume we use uniform sampling, and accept the 2nd sample on average. const int64 batchCost = batchInitCost + uniformRejectionSamplingCost * 2; Shard(worker_threads.num_threads, worker_threads.workers, num_elements, batchCost, do_work); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-197'], 'message': 'Prevent integer truncation from 64 to 32 bits. The `tensorflow::Shard` functions last argument must be a 2 argument function where both arguments are `int64` (`long long`, 64 bits). However, there are usages where code passes in a function where arguments are `int` or `int32` (32 bits). In these cases, it is possible that the integer truncation would later cause a segfault or other unexpected behavior. PiperOrigin-RevId: 332560414 Change-Id: Ief649406babc8d4f60b3e7a9d573cbcc5ce5b767'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int flv_write_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; AVCodecContext *enc = s->streams[pkt->stream_index]->codec; FLVContext *flv = s->priv_data; FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; unsigned ts; int size = pkt->size; uint8_t *data = NULL; int flags = -1, flags_size, ret; if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_VP6A || enc->codec_id == AV_CODEC_ID_VP6 || enc->codec_id == AV_CODEC_ID_AAC) flags_size = 2; else if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4) flags_size = 5; else flags_size = 1; if (flv->delay == AV_NOPTS_VALUE) flv->delay = -pkt->dts; if (pkt->dts < -flv->delay) { av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with respect to DTS\n"); return AVERROR(EINVAL); } ts = pkt->dts + flv->delay; // add delay to force positive dts if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { write_metadata(s, ts); s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; } switch (enc->codec_type) { case AVMEDIA_TYPE_VIDEO: avio_w8(pb, FLV_TAG_TYPE_VIDEO); flags = ff_codec_get_tag(flv_video_codec_ids, enc->codec_id); flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; break; case AVMEDIA_TYPE_AUDIO: flags = get_audio_flags(s, enc); av_assert0(size); avio_w8(pb, FLV_TAG_TYPE_AUDIO); break; case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_DATA: avio_w8(pb, FLV_TAG_TYPE_META); break; default: return AVERROR(EINVAL); } if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4) { /* check if extradata looks like mp4 formatted */ if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) return ret; } else if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } /* check Speex packet duration */ if (enc->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than " "8 frames per packet. Adobe Flash " "Player cannot handle this!\n"); if (sc->last_ts < ts) sc->last_ts = ts; if (size + flags_size >= 1<<24) { av_log(s, AV_LOG_ERROR, "Too large packet with size %u >= %u\n", size + flags_size, 1<<24); return AVERROR(EINVAL); } avio_wb24(pb, size + flags_size); avio_wb24(pb, ts & 0xFFFFFF); avio_w8(pb, (ts >> 24) & 0x7F); // timestamps are 32 bits _signed_ avio_wb24(pb, flv->reserved); if (enc->codec_type == AVMEDIA_TYPE_DATA || enc->codec_type == AVMEDIA_TYPE_SUBTITLE ) { int data_size; int64_t metadata_size_pos = avio_tell(pb); if (enc->codec_id == AV_CODEC_ID_TEXT) { // legacy FFmpeg magic? avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "onTextData"); avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); avio_wb32(pb, 2); put_amf_string(pb, "type"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "Text"); put_amf_string(pb, "text"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, pkt->data); put_amf_string(pb, ""); avio_w8(pb, AMF_END_OF_OBJECT); } else { // just pass the metadata through avio_write(pb, data ? data : pkt->data, size); } /* write total size of tag */ data_size = avio_tell(pb) - metadata_size_pos; avio_seek(pb, metadata_size_pos - 10, SEEK_SET); avio_wb24(pb, data_size); avio_seek(pb, data_size + 10 - 3, SEEK_CUR); avio_wb32(pb, data_size + 11); } else { av_assert1(flags>=0); avio_w8(pb,flags); if (enc->codec_id == AV_CODEC_ID_VP6) avio_w8(pb,0); if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_VP6A) { if (enc->extradata_size) avio_w8(pb, enc->extradata[0]); else avio_w8(pb, ((FFALIGN(enc->width, 16) - enc->width) << 4) | (FFALIGN(enc->height, 16) - enc->height)); } else if (enc->codec_id == AV_CODEC_ID_AAC) avio_w8(pb, 1); // AAC raw else if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4) { avio_w8(pb, 1); // AVC NALU avio_wb24(pb, pkt->pts - pkt->dts); } avio_write(pb, data ? data : pkt->data, size); avio_wb32(pb, size + flags_size + 11); // previous tag size flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration); } av_free(data); return pb->error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'avformat/flvenc: Check audio packet size Fixes: Assertion failure Fixes: assert_flvenc.c:941_1.swf Found-by: #CHEN HONGXU# <HCHEN017@e.ntu.edu.sg> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> (cherry picked from commit 6b67d7f05918f7a1ee8fc6ff21355d7e8736aa10) Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: read_system_page (Bit_Chain *dat, int64_t size_comp, int64_t size_uncomp, int64_t repeat_count) { int i; int error = 0; int64_t pesize; // Pre RS encoded size int64_t block_count; // Number of RS encoded blocks int64_t page_size; long pedata_size; BITCODE_RC *rsdata; // RS encoded data BITCODE_RC *pedata; // Pre RS encoded data BITCODE_RC *data; // The data RS unencoded and uncompressed if (repeat_count < 0 || repeat_count > DBG_MAX_COUNT || (uint64_t)size_comp >= dat->size || (uint64_t)size_uncomp >= dat->size) { LOG_ERROR ("Invalid r2007 system page: " "size_comp: %" PRId64 ", size_uncomp: %" PRId64 ", repeat_count: %" PRId64, size_comp, size_uncomp, repeat_count); return NULL; } // Round to a multiple of 8 pesize = ((size_comp + 7) & ~7) * repeat_count; // Divide pre encoded size by RS k-value (239) block_count = (pesize + 238) / 239; if (block_count <= 0 || block_count > DBG_MAX_COUNT) { LOG_ERROR ("Invalid r2007 system page: size_comp: %" PRId64 ", size_uncomp: %" PRId64, size_comp, size_uncomp); return NULL; } // Multiply with codeword size (255) and round to a multiple of 8 page_size = (block_count * 255 + 7) & ~7; if ((uint64_t)page_size >= DBG_MAX_COUNT || (unsigned long)page_size > dat->size - dat->byte) { LOG_ERROR ("Invalid r2007 system page: page_size: %" PRId64, page_size); return NULL; } assert ((uint64_t)size_comp < dat->size); assert ((uint64_t)size_uncomp < dat->size); assert ((uint64_t)repeat_count < DBG_MAX_COUNT); assert ((uint64_t)page_size < DBG_MAX_COUNT); data = (BITCODE_RC *)calloc (size_uncomp + page_size, 1); LOG_HANDLE ("Alloc system page of size %" PRId64 "\n", size_uncomp + page_size) if (!data) { LOG_ERROR ("Out of memory") return NULL; } rsdata = &data[size_uncomp]; bit_read_fixed (dat, rsdata, page_size); pedata_size = block_count * 239; pedata = decode_rs (rsdata, block_count, 239, page_size); if (!pedata) { free (data); return NULL; } if (size_comp < size_uncomp) error = decompress_r2007 (data, size_uncomp, pedata, MIN (pedata_size, size_comp)); else memcpy (data, pedata, size_uncomp); free (pedata); if (error >= DWG_ERR_CRITICAL) { free (data); return NULL; } return data; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'decode_r2007: fix for invalid section size See GH #350. With fuzzing section->data_size might not fit section_page->uncomp_size.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void rfbProcessClientNormalMessage(rfbClientPtr cl) { int n; rfbClientToServerMsg msg; char *str; READ((char *)&msg, 1) switch (msg.type) { case rfbSetPixelFormat: READ(((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1) cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel; cl->format.depth = msg.spf.format.depth; cl->format.bigEndian = (msg.spf.format.bigEndian ? 1 : 0); cl->format.trueColour = (msg.spf.format.trueColour ? 1 : 0); cl->format.redMax = Swap16IfLE(msg.spf.format.redMax); cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax); cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax); cl->format.redShift = msg.spf.format.redShift; cl->format.greenShift = msg.spf.format.greenShift; cl->format.blueShift = msg.spf.format.blueShift; cl->readyForSetColourMapEntries = TRUE; rfbSetTranslateFunction(cl); return; case rfbFixColourMapEntries: READ(((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1) rfbLog("rfbProcessClientNormalMessage: FixColourMapEntries unsupported\n"); rfbCloseClient(cl); return; case rfbSetEncodings: { int i; CARD32 enc; Bool firstFence = !cl->enableFence; Bool firstCU = !cl->enableCU; Bool firstGII = !cl->enableGII; Bool logTightCompressLevel = FALSE; READ(((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1) msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings); cl->preferredEncoding = -1; cl->useCopyRect = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorPosUpdates = FALSE; cl->enableLastRectEncoding = FALSE; cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->tightSubsampLevel = TIGHT_DEFAULT_SUBSAMP; cl->tightQualityLevel = -1; cl->imageQualityLevel = -1; for (i = 0; i < msg.se.nEncodings; i++) { READ((char *)&enc, 4) enc = Swap32IfLE(enc); switch (enc) { case rfbEncodingCopyRect: cl->useCopyRect = TRUE; break; case rfbEncodingRaw: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using raw encoding for client %s\n", cl->host); } break; case rfbEncodingRRE: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using rre encoding for client %s\n", cl->host); } break; case rfbEncodingCoRRE: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using CoRRE encoding for client %s\n", cl->host); } break; case rfbEncodingHextile: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using hextile encoding for client %s\n", cl->host); } break; case rfbEncodingZlib: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using zlib encoding for client %s\n", cl->host); } break; case rfbEncodingZRLE: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using ZRLE encoding for client %s\n", cl->host); } break; case rfbEncodingZYWRLE: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using ZYWRLE encoding for client %s\n", cl->host); } break; case rfbEncodingTight: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using tight encoding for client %s\n", cl->host); } break; case rfbEncodingXCursor: if (!cl->enableCursorShapeUpdates) { rfbLog("Enabling X-style cursor updates for client %s\n", cl->host); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = FALSE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingRichCursor: if (!cl->enableCursorShapeUpdates) { rfbLog("Enabling full-color cursor updates for client %s\n", cl->host); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = TRUE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingPointerPos: if (!cl->enableCursorPosUpdates) { rfbLog("Enabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = TRUE; cl->cursorWasMoved = TRUE; cl->cursorX = -1; cl->cursorY = -1; } break; case rfbEncodingLastRect: if (!cl->enableLastRectEncoding) { rfbLog("Enabling LastRect protocol extension for client %s\n", cl->host); cl->enableLastRectEncoding = TRUE; } break; case rfbEncodingFence: if (!cl->enableFence) { rfbLog("Enabling Fence protocol extension for client %s\n", cl->host); cl->enableFence = TRUE; } break; case rfbEncodingContinuousUpdates: if (!cl->enableCU) { rfbLog("Enabling Continuous Updates protocol extension for client %s\n", cl->host); cl->enableCU = TRUE; } break; case rfbEncodingNewFBSize: if (!cl->enableDesktopSize) { if (!rfbAuthDisableRemoteResize) { rfbLog("Enabling Desktop Size protocol extension for client %s\n", cl->host); cl->enableDesktopSize = TRUE; } else rfbLog("WARNING: Remote desktop resizing disabled per system policy.\n"); } break; case rfbEncodingExtendedDesktopSize: if (!cl->enableExtDesktopSize) { if (!rfbAuthDisableRemoteResize) { rfbLog("Enabling Extended Desktop Size protocol extension for client %s\n", cl->host); cl->enableExtDesktopSize = TRUE; } else rfbLog("WARNING: Remote desktop resizing disabled per system policy.\n"); } break; case rfbEncodingGII: if (!cl->enableGII) { rfbLog("Enabling GII extension for client %s\n", cl->host); cl->enableGII = TRUE; } break; default: if (enc >= (CARD32)rfbEncodingCompressLevel0 && enc <= (CARD32)rfbEncodingCompressLevel9) { cl->zlibCompressLevel = enc & 0x0F; cl->tightCompressLevel = enc & 0x0F; if (cl->preferredEncoding == rfbEncodingTight) logTightCompressLevel = TRUE; else rfbLog("Using compression level %d for client %s\n", cl->tightCompressLevel, cl->host); if (rfbInterframe == -1) { if (cl->tightCompressLevel >= 5) { if (!InterframeOn(cl)) { rfbCloseClient(cl); return; } } else InterframeOff(cl); } } else if (enc >= (CARD32)rfbEncodingSubsamp1X && enc <= (CARD32)rfbEncodingSubsampGray) { cl->tightSubsampLevel = enc & 0xFF; rfbLog("Using JPEG subsampling %d for client %s\n", cl->tightSubsampLevel, cl->host); } else if (enc >= (CARD32)rfbEncodingQualityLevel0 && enc <= (CARD32)rfbEncodingQualityLevel9) { cl->tightQualityLevel = JPEG_QUAL[enc & 0x0F]; cl->tightSubsampLevel = JPEG_SUBSAMP[enc & 0x0F]; cl->imageQualityLevel = enc & 0x0F; if (cl->preferredEncoding == rfbEncodingTight) rfbLog("Using JPEG subsampling %d, Q%d for client %s\n", cl->tightSubsampLevel, cl->tightQualityLevel, cl->host); else rfbLog("Using image quality level %d for client %s\n", cl->imageQualityLevel, cl->host); } else if (enc >= (CARD32)rfbEncodingFineQualityLevel0 + 1 && enc <= (CARD32)rfbEncodingFineQualityLevel100) { cl->tightQualityLevel = enc & 0xFF; rfbLog("Using JPEG quality %d for client %s\n", cl->tightQualityLevel, cl->host); } else { rfbLog("rfbProcessClientNormalMessage: ignoring unknown encoding %d (%x)\n", (int)enc, (int)enc); } } /* switch (enc) */ } /* for (i = 0; i < msg.se.nEncodings; i++) */ if (cl->preferredEncoding == -1) cl->preferredEncoding = rfbEncodingTight; if (cl->preferredEncoding == rfbEncodingTight && logTightCompressLevel) rfbLog("Using Tight compression level %d for client %s\n", rfbTightCompressLevel(cl), cl->host); if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) { rfbLog("Disabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = FALSE; } if (cl->enableFence && firstFence) { if (!rfbSendFence(cl, rfbFenceFlagRequest, 0, NULL)) return; } if (cl->enableCU && cl->enableFence && firstCU) { if (!rfbSendEndOfCU(cl)) return; } if (cl->enableGII && firstGII) { /* Send GII server version message to all clients */ rfbGIIServerVersionMsg msg; msg.type = rfbGIIServer; /* We always send as big endian to make things easier on the Java viewer. */ msg.endianAndSubType = rfbGIIVersion | rfbGIIBE; msg.length = Swap16IfLE(sz_rfbGIIServerVersionMsg - 4); msg.maximumVersion = msg.minimumVersion = Swap16IfLE(1); if (WriteExact(cl, (char *)&msg, sz_rfbGIIServerVersionMsg) < 0) { rfbLogPerror("rfbProcessClientNormalMessage: write"); rfbCloseClient(cl); return; } } return; } /* rfbSetEncodings */ case rfbFramebufferUpdateRequest: { RegionRec tmpRegion; BoxRec box; READ(((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg - 1) box.x1 = Swap16IfLE(msg.fur.x); box.y1 = Swap16IfLE(msg.fur.y); box.x2 = box.x1 + Swap16IfLE(msg.fur.w); box.y2 = box.y1 + Swap16IfLE(msg.fur.h); SAFE_REGION_INIT(pScreen, &tmpRegion, &box, 0); if (!msg.fur.incremental || !cl->continuousUpdates) REGION_UNION(pScreen, &cl->requestedRegion, &cl->requestedRegion, &tmpRegion); if (!cl->readyForSetColourMapEntries) { /* client hasn't sent a SetPixelFormat so is using server's */ cl->readyForSetColourMapEntries = TRUE; if (!cl->format.trueColour) { if (!rfbSetClientColourMap(cl, 0, 0)) { REGION_UNINIT(pScreen, &tmpRegion); return; } } } if (!msg.fur.incremental) { REGION_UNION(pScreen, &cl->modifiedRegion, &cl->modifiedRegion, &tmpRegion); REGION_SUBTRACT(pScreen, &cl->copyRegion, &cl->copyRegion, &tmpRegion); REGION_UNION(pScreen, &cl->ifRegion, &cl->ifRegion, &tmpRegion); cl->pendingExtDesktopResize = TRUE; } if (FB_UPDATE_PENDING(cl) && (!cl->deferredUpdateScheduled || rfbDeferUpdateTime == 0 || gettime() - cl->deferredUpdateStart >= (double)rfbDeferUpdateTime)) { if (rfbSendFramebufferUpdate(cl)) cl->deferredUpdateScheduled = FALSE; } REGION_UNINIT(pScreen, &tmpRegion); return; } case rfbKeyEvent: cl->rfbKeyEventsRcvd++; READ(((char *)&msg) + 1, sz_rfbKeyEventMsg - 1) if (!rfbViewOnly && !cl->viewOnly) KeyEvent((KeySym)Swap32IfLE(msg.ke.key), msg.ke.down); return; case rfbPointerEvent: cl->rfbPointerEventsRcvd++; READ(((char *)&msg) + 1, sz_rfbPointerEventMsg - 1) if (pointerClient && (pointerClient != cl)) return; if (msg.pe.buttonMask == 0) pointerClient = NULL; else pointerClient = cl; if (!rfbViewOnly && !cl->viewOnly) { cl->cursorX = (int)Swap16IfLE(msg.pe.x); cl->cursorY = (int)Swap16IfLE(msg.pe.y); PtrAddEvent(msg.pe.buttonMask, cl->cursorX, cl->cursorY, cl); } return; case rfbClientCutText: { int ignoredBytes = 0; READ(((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1) msg.cct.length = Swap32IfLE(msg.cct.length); if (msg.cct.length > rfbMaxClipboard) { rfbLog("Truncating %d-byte clipboard update to %d bytes.\n", msg.cct.length, rfbMaxClipboard); ignoredBytes = msg.cct.length - rfbMaxClipboard; msg.cct.length = rfbMaxClipboard; } if (msg.cct.length <= 0) return; str = (char *)malloc(msg.cct.length); if (str == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: rfbClientCutText out of memory"); rfbCloseClient(cl); return; } if ((n = ReadExact(cl, str, msg.cct.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } if (ignoredBytes > 0) { if ((n = SkipExact(cl, ignoredBytes)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } } /* NOTE: We do not accept cut text from a view-only client */ if (!rfbViewOnly && !cl->viewOnly && !rfbAuthDisableCBRecv) { vncClientCutText(str, msg.cct.length); if (rfbSyncCutBuffer) rfbSetXCutText(str, msg.cct.length); } free(str); return; } case rfbEnableContinuousUpdates: { BoxRec box; READ(((char *)&msg) + 1, sz_rfbEnableContinuousUpdatesMsg - 1) if (!cl->enableFence || !cl->enableCU) { rfbLog("Ignoring request to enable continuous updates because the client does not\n"); rfbLog("support the flow control extensions.\n"); return; } box.x1 = Swap16IfLE(msg.ecu.x); box.y1 = Swap16IfLE(msg.ecu.y); box.x2 = box.x1 + Swap16IfLE(msg.ecu.w); box.y2 = box.y1 + Swap16IfLE(msg.ecu.h); SAFE_REGION_INIT(pScreen, &cl->cuRegion, &box, 0); cl->continuousUpdates = msg.ecu.enable; if (cl->continuousUpdates) { REGION_EMPTY(pScreen, &cl->requestedRegion); if (!rfbSendFramebufferUpdate(cl)) return; } else { if (!rfbSendEndOfCU(cl)) return; } rfbLog("Continuous updates %s\n", cl->continuousUpdates ? "enabled" : "disabled"); return; } case rfbFence: { CARD32 flags; char data[64]; READ(((char *)&msg) + 1, sz_rfbFenceMsg - 1) flags = Swap32IfLE(msg.f.flags); READ(data, msg.f.length) if (msg.f.length > sizeof(data)) rfbLog("Ignoring fence. Payload of %d bytes is too large.\n", msg.f.length); else HandleFence(cl, flags, msg.f.length, data); return; } #define EDSERROR(format, args...) { \ if (!strlen(errMsg)) \ snprintf(errMsg, 256, "Desktop resize ERROR: "format"\n", args); \ result = rfbEDSResultInvalid; \ } case rfbSetDesktopSize: { int i; struct xorg_list newScreens; rfbClientPtr cl2; int result = rfbEDSResultSuccess; char errMsg[256] = "\0"; ScreenPtr pScreen = screenInfo.screens[0]; READ(((char *)&msg) + 1, sz_rfbSetDesktopSizeMsg - 1) if (msg.sds.numScreens < 1) EDSERROR("Requested number of screens %d is invalid", msg.sds.numScreens); msg.sds.w = Swap16IfLE(msg.sds.w); msg.sds.h = Swap16IfLE(msg.sds.h); if (msg.sds.w < 1 || msg.sds.h < 1) EDSERROR("Requested framebuffer dimensions %dx%d are invalid", msg.sds.w, msg.sds.h); xorg_list_init(&newScreens); for (i = 0; i < msg.sds.numScreens; i++) { rfbScreenInfo *screen = rfbNewScreen(0, 0, 0, 0, 0, 0); READ((char *)&screen->s, sizeof(rfbScreenDesc)) screen->s.id = Swap32IfLE(screen->s.id); screen->s.x = Swap16IfLE(screen->s.x); screen->s.y = Swap16IfLE(screen->s.y); screen->s.w = Swap16IfLE(screen->s.w); screen->s.h = Swap16IfLE(screen->s.h); screen->s.flags = Swap32IfLE(screen->s.flags); if (screen->s.w < 1 || screen->s.h < 1) EDSERROR("Screen 0x%.8x requested dimensions %dx%d are invalid", (unsigned int)screen->s.id, screen->s.w, screen->s.h); if (screen->s.x >= msg.sds.w || screen->s.y >= msg.sds.h || screen->s.x + screen->s.w > msg.sds.w || screen->s.y + screen->s.h > msg.sds.h) EDSERROR("Screen 0x%.8x requested geometry %dx%d+%d+%d exceeds requested framebuffer dimensions", (unsigned int)screen->s.id, screen->s.w, screen->s.h, screen->s.x, screen->s.y); if (rfbFindScreenID(&newScreens, screen->s.id)) { EDSERROR("Screen 0x%.8x duplicate ID", (unsigned int)screen->s.id); free(screen); } else rfbAddScreen(&newScreens, screen); } if (cl->viewOnly) { rfbLog("NOTICE: Ignoring remote desktop resize request from a view-only client.\n"); result = rfbEDSResultProhibited; } else if (result == rfbEDSResultSuccess) { result = ResizeDesktop(pScreen, cl, msg.sds.w, msg.sds.h, &newScreens); if (result == rfbEDSResultSuccess) return; } else rfbLog(errMsg); rfbRemoveScreens(&newScreens); /* Send back the error only to the requesting client. This loop is necessary because the client may have been shut down as a result of an error in ResizeDesktop(). */ for (cl2 = rfbClientHead; cl2; cl2 = cl2->next) { if (cl2 == cl) { cl2->pendingExtDesktopResize = TRUE; cl2->reason = rfbEDSReasonClient; cl2->result = result; rfbSendFramebufferUpdate(cl2); break; } } return; } case rfbGIIClient: { CARD8 endianAndSubType, littleEndian, subType; READ((char *)&endianAndSubType, 1); littleEndian = (endianAndSubType & rfbGIIBE) ? 0 : 1; subType = endianAndSubType & ~rfbGIIBE; switch (subType) { case rfbGIIVersion: READ((char *)&msg.giicv.length, sz_rfbGIIClientVersionMsg - 2); if (littleEndian != *(const char *)&rfbEndianTest) { msg.giicv.length = Swap16(msg.giicv.length); msg.giicv.version = Swap16(msg.giicv.version); } if (msg.giicv.length != sz_rfbGIIClientVersionMsg - 4 || msg.giicv.version < 1) { rfbLog("ERROR: Malformed GII client version message\n"); rfbCloseClient(cl); return; } rfbLog("Client supports GII version %d\n", msg.giicv.version); break; case rfbGIIDeviceCreate: { int i; rfbDevInfo dev; rfbGIIDeviceCreatedMsg dcmsg; memset(&dev, 0, sizeof(dev)); dcmsg.deviceOrigin = 0; READ((char *)&msg.giidc.length, sz_rfbGIIDeviceCreateMsg - 2); if (littleEndian != *(const char *)&rfbEndianTest) { msg.giidc.length = Swap16(msg.giidc.length); msg.giidc.vendorID = Swap32(msg.giidc.vendorID); msg.giidc.productID = Swap32(msg.giidc.productID); msg.giidc.canGenerate = Swap32(msg.giidc.canGenerate); msg.giidc.numRegisters = Swap32(msg.giidc.numRegisters); msg.giidc.numValuators = Swap32(msg.giidc.numValuators); msg.giidc.numButtons = Swap32(msg.giidc.numButtons); } rfbLog("GII Device Create: %s\n", msg.giidc.deviceName); #ifdef GII_DEBUG rfbLog(" Vendor ID: %d\n", msg.giidc.vendorID); rfbLog(" Product ID: %d\n", msg.giidc.productID); rfbLog(" Event mask: %.8x\n", msg.giidc.canGenerate); rfbLog(" Registers: %d\n", msg.giidc.numRegisters); rfbLog(" Valuators: %d\n", msg.giidc.numValuators); rfbLog(" Buttons: %d\n", msg.giidc.numButtons); #endif if (msg.giidc.length != sz_rfbGIIDeviceCreateMsg - 4 + msg.giidc.numValuators * sz_rfbGIIValuator) { rfbLog("ERROR: Malformed GII device create message\n"); rfbCloseClient(cl); return; } if (msg.giidc.numButtons > MAX_BUTTONS) { rfbLog("GII device create ERROR: %d buttons exceeds max of %d\n", msg.giidc.numButtons, MAX_BUTTONS); SKIP(msg.giidc.numValuators * sz_rfbGIIValuator); goto sendMessage; } if (msg.giidc.numValuators > MAX_VALUATORS) { rfbLog("GII device create ERROR: %d valuators exceeds max of %d\n", msg.giidc.numValuators, MAX_VALUATORS); SKIP(msg.giidc.numValuators * sz_rfbGIIValuator); goto sendMessage; } memcpy(&dev.name, msg.giidc.deviceName, 32); dev.numButtons = msg.giidc.numButtons; dev.numValuators = msg.giidc.numValuators; dev.eventMask = msg.giidc.canGenerate; dev.mode = (dev.eventMask & rfbGIIValuatorAbsoluteMask) ? Absolute : Relative; dev.productID = msg.giidc.productID; if (dev.mode == Relative) { rfbLog("GII device create ERROR: relative valuators not supported (yet)\n"); SKIP(msg.giidc.numValuators * sz_rfbGIIValuator); goto sendMessage; } for (i = 0; i < dev.numValuators; i++) { rfbGIIValuator *v = &dev.valuators[i]; READ((char *)v, sz_rfbGIIValuator); if (littleEndian != *(const char *)&rfbEndianTest) { v->index = Swap32(v->index); v->rangeMin = Swap32((CARD32)v->rangeMin); v->rangeCenter = Swap32((CARD32)v->rangeCenter); v->rangeMax = Swap32((CARD32)v->rangeMax); v->siUnit = Swap32(v->siUnit); v->siAdd = Swap32((CARD32)v->siAdd); v->siMul = Swap32((CARD32)v->siMul); v->siDiv = Swap32((CARD32)v->siDiv); v->siShift = Swap32((CARD32)v->siShift); } #ifdef GII_DEBUG rfbLog(" Valuator: %s (%s)\n", v->longName, v->shortName); rfbLog(" Index: %d\n", v->index); rfbLog(" Range: min = %d, center = %d, max = %d\n", v->rangeMin, v->rangeCenter, v->rangeMax); rfbLog(" SI unit: %d\n", v->siUnit); rfbLog(" SI add: %d\n", v->siAdd); rfbLog(" SI multiply: %d\n", v->siMul); rfbLog(" SI divide: %d\n", v->siDiv); rfbLog(" SI shift: %d\n", v->siShift); #endif } for (i = 0; i < cl->numDevices; i++) { if (!strcmp(dev.name, cl->devices[i].name)) { rfbLog("Device \'%s\' already exists with GII device ID %d\n", dev.name, i + 1); dcmsg.deviceOrigin = Swap32IfLE(i + 1); goto sendMessage; } } if (rfbVirtualTablet || AddExtInputDevice(&dev)) { memcpy(&cl->devices[cl->numDevices], &dev, sizeof(dev)); cl->numDevices++; dcmsg.deviceOrigin = Swap32IfLE(cl->numDevices); } rfbLog("GII device ID = %d\n", cl->numDevices); sendMessage: /* Send back a GII device created message */ dcmsg.type = rfbGIIServer; /* We always send as big endian to make things easier on the Java viewer. */ dcmsg.endianAndSubType = rfbGIIDeviceCreate | rfbGIIBE; dcmsg.length = Swap16IfLE(sz_rfbGIIDeviceCreatedMsg - 4); if (WriteExact(cl, (char *)&dcmsg, sz_rfbGIIDeviceCreatedMsg) < 0) { rfbLogPerror("rfbProcessClientNormalMessage: write"); rfbCloseClient(cl); return; } break; } case rfbGIIDeviceDestroy: READ((char *)&msg.giidd.length, sz_rfbGIIDeviceDestroyMsg - 2); if (littleEndian != *(const char *)&rfbEndianTest) { msg.giidd.length = Swap16(msg.giidd.length); msg.giidd.deviceOrigin = Swap32(msg.giidd.deviceOrigin); } if (msg.giidd.length != sz_rfbGIIDeviceDestroyMsg - 4) { rfbLog("ERROR: Malformed GII device create message\n"); rfbCloseClient(cl); return; } RemoveExtInputDevice(cl, msg.giidd.deviceOrigin - 1); break; case rfbGIIEvent: { CARD16 length; READ((char *)&length, sizeof(CARD16)); if (littleEndian != *(const char *)&rfbEndianTest) length = Swap16(length); while (length > 0) { CARD8 eventSize, eventType; READ((char *)&eventSize, 1); READ((char *)&eventType, 1); switch (eventType) { case rfbGIIButtonPress: case rfbGIIButtonRelease: { rfbGIIButtonEvent b; rfbDevInfo *dev; READ((char *)&b.pad, sz_rfbGIIButtonEvent - 2); if (littleEndian != *(const char *)&rfbEndianTest) { b.deviceOrigin = Swap32(b.deviceOrigin); b.buttonNumber = Swap32(b.buttonNumber); } if (eventSize != sz_rfbGIIButtonEvent || b.deviceOrigin <= 0 || b.buttonNumber < 1) { rfbLog("ERROR: Malformed GII button event\n"); rfbCloseClient(cl); return; } if (eventSize > length) { rfbLog("ERROR: Malformed GII event message\n"); rfbCloseClient(cl); return; } length -= eventSize; if (b.deviceOrigin < 1 || b.deviceOrigin > cl->numDevices) { rfbLog("ERROR: GII button event from non-existent device %d\n", b.deviceOrigin); rfbCloseClient(cl); return; } dev = &cl->devices[b.deviceOrigin - 1]; if ((eventType == rfbGIIButtonPress && (dev->eventMask & rfbGIIButtonPressMask) == 0) || (eventType == rfbGIIButtonRelease && (dev->eventMask & rfbGIIButtonReleaseMask) == 0)) { rfbLog("ERROR: Device %d can't generate GII button events\n", b.deviceOrigin); rfbCloseClient(cl); return; } if (b.buttonNumber > dev->numButtons) { rfbLog("ERROR: GII button %d event for device %d exceeds button count (%d)\n", b.buttonNumber, b.deviceOrigin, dev->numButtons); rfbCloseClient(cl); return; } #ifdef GII_DEBUG rfbLog("Device %d button %d %s\n", b.deviceOrigin, b.buttonNumber, eventType == rfbGIIButtonPress ? "PRESS" : "release"); fflush(stderr); #endif ExtInputAddEvent(dev, eventType == rfbGIIButtonPress ? ButtonPress : ButtonRelease, b.buttonNumber); break; } case rfbGIIValuatorRelative: case rfbGIIValuatorAbsolute: { rfbGIIValuatorEvent v; int i; rfbDevInfo *dev; READ((char *)&v.pad, sz_rfbGIIValuatorEvent - 2); if (littleEndian != *(const char *)&rfbEndianTest) { v.deviceOrigin = Swap32(v.deviceOrigin); v.first = Swap32(v.first); v.count = Swap32(v.count); } if (eventSize != sz_rfbGIIValuatorEvent + sizeof(int) * v.count) { rfbLog("ERROR: Malformed GII valuator event\n"); rfbCloseClient(cl); return; } if (eventSize > length) { rfbLog("ERROR: Malformed GII event message\n"); rfbCloseClient(cl); return; } length -= eventSize; if (v.deviceOrigin < 1 || v.deviceOrigin > cl->numDevices) { rfbLog("ERROR: GII valuator event from non-existent device %d\n", v.deviceOrigin); rfbCloseClient(cl); return; } dev = &cl->devices[v.deviceOrigin - 1]; if ((eventType == rfbGIIValuatorRelative && (dev->eventMask & rfbGIIValuatorRelativeMask) == 0) || (eventType == rfbGIIValuatorAbsolute && (dev->eventMask & rfbGIIValuatorAbsoluteMask) == 0)) { rfbLog("ERROR: Device %d cannot generate GII valuator events\n", v.deviceOrigin); rfbCloseClient(cl); return; } if (v.first + v.count > dev->numValuators) { rfbLog("ERROR: GII valuator event for device %d exceeds valuator count (%d)\n", v.deviceOrigin, dev->numValuators); rfbCloseClient(cl); return; } #ifdef GII_DEBUG rfbLog("Device %d Valuator %s first=%d count=%d:\n", v.deviceOrigin, eventType == rfbGIIValuatorRelative ? "rel" : "ABS", v.first, v.count); #endif for (i = v.first; i < v.first + v.count; i++) { READ((char *)&dev->values[i], sizeof(int)); if (littleEndian != *(const char *)&rfbEndianTest) dev->values[i] = Swap32((CARD32)dev->values[i]); #ifdef GII_DEBUG fprintf(stderr, "v[%d]=%d ", i, dev->values[i]); #endif } #ifdef GII_DEBUG fprintf(stderr, "\n"); #endif if (v.count > 0) { dev->valFirst = v.first; dev->valCount = v.count; dev->mode = eventType == rfbGIIValuatorAbsolute ? Absolute : Relative; ExtInputAddEvent(dev, MotionNotify, 0); } break; } default: rfbLog("ERROR: This server cannot handle GII event type %d\n", eventType); rfbCloseClient(cl); return; } /* switch (eventType) */ } /* while (length > 0) */ if (length != 0) { rfbLog("ERROR: Malformed GII event message\n"); rfbCloseClient(cl); return; } break; } /* rfbGIIEvent */ } /* switch (subType) */ return; } /* rfbGIIClient */ default: rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n", msg.type); rfbLog(" ... closing connection\n"); rfbCloseClient(cl); return; } /* switch (msg.type) */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Server: Fix two issues identified by ASan 1. If the TLSPlain and X509Plain security types were both disabled, then rfbOptPamAuth() would overflow the name field in the secTypes structure when testing the "none" security type, since the name of that security type has less than five characters. This issue was innocuous, since the overflow was fully contained within the secTypes structure, but the ASan error caused Xvnc to abort, which made it difficult to detect other errors. 2. If an ill-behaved RFB client sent the TurboVNC Server a fence message with more than 64 bytes, then the TurboVNC Server would try to read that message and subsequently overflow the stack before it detected that the payload was too large. This could never have occurred with any of the VNC viewers that currently support the RFB flow control extensions (TigerVNC and TurboVNC, namely.) This issue was also innocuous, since the stack overflow affected two variables (newScreens and errMsg) that were never accessed before the function returned.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const TensorShape& input_shape = input.shape(); const int32 input_dims = input_shape.dims(); const Tensor& segment_id = context->input(1); const TensorShape& segment_id_shape = segment_id.shape(); const int32 segment_dims = segment_id_shape.dims(); const Tensor& num_segments_tensor = context->input(2); auto num_segments = num_segments_tensor.scalar<NUM_SEGMENTS_TYPE>()(); OP_REQUIRES(context, segment_dims != 0, errors::InvalidArgument("Segment_id cannot have rank 0")); OP_REQUIRES( context, segment_dims <= input_dims, errors::OutOfRange("Invalid segment_id rank ", segment_dims, " for input with ", input_dims, " dimension(s)")); for (auto i = 0; i < segment_dims; i++) { OP_REQUIRES( context, segment_id_shape.dim_size(i) == input_shape.dim_size(i), errors::InvalidArgument( "Segment dimension is ", segment_id_shape.dim_size(i), " while input dimension is ", input_dims, " in rank ", i)); } // Making output tensor. Tensor* output_tensor = nullptr; TensorShape output_shape = GetOutputShape(input_shape, segment_id_shape, num_segments); OP_REQUIRES_OK(context, context->allocate_output("output", output_shape, &output_tensor)); // Preparating flat tensors. auto output_flat = output_tensor->flat<tstring>(); auto flat_segment_id = segment_id.flat<INDICES_TYPE>(); auto flat_input = input.flat<tstring>(); for (int i = 0; i < flat_segment_id.size(); i++) { OP_REQUIRES( context, ((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)), errors::InvalidArgument( "segment_ids are not allowed to exceed num_segments or" " to have negative values.")); } int64 big_stride; int64 small_stride; std::tie(big_stride, small_stride) = GetStrides<INDICES_TYPE>(input_shape, segment_id_shape); auto relative_offset_set = GetFlattenedRelativeOffsets<INDICES_TYPE>(small_stride, big_stride); for (auto start_offset = 0; start_offset < big_stride; start_offset++) { for (auto i = 0; i < relative_offset_set.size(); i++) { auto output_index = start_offset + flat_segment_id(i) * big_stride; auto offset = start_offset + relative_offset_set[i]; if (output_flat(output_index).length() != 0) output_flat(output_index).append(separator_.c_str()); output_flat(output_index).append(flat_input(offset)); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'Fix overflow CHECK issue with `tf.raw_ops.UnsortedSegmentJoin`. PiperOrigin-RevId: 370766155 Change-Id: I33e7c6626224e1060a8a4ab51ad5d861c6d4c63e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t cm_write(struct file *file, const char __user * user_buf, size_t count, loff_t *ppos) { static char *buf; static u32 max_size; static u32 uncopied_bytes; struct acpi_table_header table; acpi_status status; if (!(*ppos)) { /* parse the table header to get the table length */ if (count <= sizeof(struct acpi_table_header)) return -EINVAL; if (copy_from_user(&table, user_buf, sizeof(struct acpi_table_header))) return -EFAULT; uncopied_bytes = max_size = table.length; buf = kzalloc(max_size, GFP_KERNEL); if (!buf) return -ENOMEM; } if (buf == NULL) return -EINVAL; if ((*ppos > max_size) || (*ppos + count > max_size) || (*ppos + count < count) || (count > uncopied_bytes)) return -EINVAL; if (copy_from_user(buf + (*ppos), user_buf, count)) { kfree(buf); buf = NULL; return -EFAULT; } uncopied_bytes -= count; *ppos += count; if (!uncopied_bytes) { status = acpi_install_method(buf); kfree(buf); buf = NULL; if (ACPI_FAILURE(status)) return -EINVAL; add_taint(TAINT_OVERRIDDEN_ACPI_TABLE); } return count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'ACPI: Split out custom_method functionality into an own driver With /sys/kernel/debug/acpi/custom_method root can write to arbitrary memory and increase his priveleges, even if these are restricted. -> Make this an own debug .config option and warn about the security issue in the config description. -> Still keep acpi/debugfs.c which now only creates an empty /sys/kernel/debug/acpi directory. There might be other users of it later. Signed-off-by: Thomas Renninger <trenn@suse.de> Acked-by: Rafael J. Wysocki <rjw@sisk.pl> Acked-by: rui.zhang@intel.com Signed-off-by: Len Brown <len.brown@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int er_supported(ERContext *s) { if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice || !s->cur_pic.f || s->cur_pic.field_picture || s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO ) return 0; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile The profile field is changed by code inside and outside the decoder, its not a reliable indicator of the internal codec state. Maintaining it consistency with studio_profile is messy. Its easier to just avoid it and use only studio_profile Fixes: assertion failure Fixes: ffmpeg_crash_9.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool parse_notify(struct pool *pool, json_t *val) { char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime, *header; size_t cb1_len, cb2_len, alloc_len; unsigned char *cb1, *cb2; bool clean, ret = false; int merkles, i; json_t *arr; arr = json_array_get(val, 4); if (!arr || !json_is_array(arr)) goto out; merkles = json_array_size(arr); job_id = json_array_string(val, 0); prev_hash = json_array_string(val, 1); coinbase1 = json_array_string(val, 2); coinbase2 = json_array_string(val, 3); bbversion = json_array_string(val, 5); nbit = json_array_string(val, 6); ntime = json_array_string(val, 7); clean = json_is_true(json_array_get(val, 8)); if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) { /* Annoying but we must not leak memory */ if (job_id) free(job_id); if (prev_hash) free(prev_hash); if (coinbase1) free(coinbase1); if (coinbase2) free(coinbase2); if (bbversion) free(bbversion); if (nbit) free(nbit); if (ntime) free(ntime); goto out; } cg_wlock(&pool->data_lock); free(pool->swork.job_id); free(pool->swork.prev_hash); free(pool->swork.bbversion); free(pool->swork.nbit); free(pool->swork.ntime); pool->swork.job_id = job_id; pool->swork.prev_hash = prev_hash; cb1_len = strlen(coinbase1) / 2; cb2_len = strlen(coinbase2) / 2; pool->swork.bbversion = bbversion; pool->swork.nbit = nbit; pool->swork.ntime = ntime; pool->swork.clean = clean; alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len; pool->nonce2_offset = cb1_len + pool->n1_len; for (i = 0; i < pool->swork.merkles; i++) free(pool->swork.merkle_bin[i]); if (merkles) { pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin, sizeof(char *) * merkles + 1); for (i = 0; i < merkles; i++) { char *merkle = json_array_string(arr, i); pool->swork.merkle_bin[i] = (unsigned char *)malloc(32); if (unlikely(!pool->swork.merkle_bin[i])) quit(1, "Failed to malloc pool swork merkle_bin"); hex2bin(pool->swork.merkle_bin[i], merkle, 32); free(merkle); } } pool->swork.merkles = merkles; if (clean) pool->nonce2 = 0; pool->merkle_offset = strlen(pool->swork.bbversion) + strlen(pool->swork.prev_hash); pool->swork.header_len = pool->merkle_offset + /* merkle_hash */ 32 + strlen(pool->swork.ntime) + strlen(pool->swork.nbit) + /* nonce */ 8 + /* workpadding */ 96; pool->merkle_offset /= 2; pool->swork.header_len = pool->swork.header_len * 2 + 1; align_len(&pool->swork.header_len); header = (char *)alloca(pool->swork.header_len); snprintf(header, pool->swork.header_len, "%s%s%s%s%s%s%s", pool->swork.bbversion, pool->swork.prev_hash, blank_merkel, pool->swork.ntime, pool->swork.nbit, "00000000", /* nonce */ workpadding); if (unlikely(!hex2bin(pool->header_bin, header, 128))) quit(1, "Failed to convert header to header_bin in parse_notify"); cb1 = (unsigned char *)calloc(cb1_len, 1); if (unlikely(!cb1)) quithere(1, "Failed to calloc cb1 in parse_notify"); hex2bin(cb1, coinbase1, cb1_len); cb2 = (unsigned char *)calloc(cb2_len, 1); if (unlikely(!cb2)) quithere(1, "Failed to calloc cb2 in parse_notify"); hex2bin(cb2, coinbase2, cb2_len); free(pool->coinbase); align_len(&alloc_len); pool->coinbase = (unsigned char *)calloc(alloc_len, 1); if (unlikely(!pool->coinbase)) quit(1, "Failed to calloc pool coinbase in parse_notify"); memcpy(pool->coinbase, cb1, cb1_len); memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len); memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len); cg_wunlock(&pool->data_lock); if (opt_protocol) { applog(LOG_DEBUG, "job_id: %s", job_id); applog(LOG_DEBUG, "prev_hash: %s", prev_hash); applog(LOG_DEBUG, "coinbase1: %s", coinbase1); applog(LOG_DEBUG, "coinbase2: %s", coinbase2); applog(LOG_DEBUG, "bbversion: %s", bbversion); applog(LOG_DEBUG, "nbit: %s", nbit); applog(LOG_DEBUG, "ntime: %s", ntime); applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no"); } free(coinbase1); free(coinbase2); free(cb1); free(cb2); /* A notify message is the closest stratum gets to a getwork */ pool->getwork_requested++; total_getworks++; ret = true; if (pool == current_pool()) opt_work_update = true; out: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime. Might have introduced a memory leak, don't have time to check. :( Should the other hex2bin()'s be checked? Thanks to Mick Ayzenberg <mick.dejavusecurity.com> for finding this.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static const char* ConvertScalar(PyObject* v, tstring* out) { if (PyBytes_Check(v)) { out->assign(PyBytes_AS_STRING(v), PyBytes_GET_SIZE(v)); return nullptr; } if (PyUnicode_Check(v)) { #if PY_MAJOR_VERSION >= 3 Py_ssize_t size; const char* str = PyUnicode_AsUTF8AndSize(v, &size); if (str == nullptr) return ErrorConvertingUnicodeString; out->assign(str, size); return nullptr; #else PyObject* py_str = PyUnicode_AsUTF8String(v); if (py_str == nullptr) return ErrorConvertingUnicodeString; out->assign(PyBytes_AS_STRING(py_str), PyBytes_GET_SIZE(py_str)); Py_DECREF(py_str); return nullptr; #endif } return ErrorMixedTypes; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix segfault when attempting to convert string to float16. To make sure this gets fixed, add test for converting string to any numeric type. PiperOrigin-RevId: 286650886 Change-Id: I81f770ec2bbd33a863e8057ce198c679912fa8e0'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; if (!name) return ERR_PTR(-ENOENT); mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD); type &= mask; alg = crypto_alg_lookup(name, type, mask); if (!alg) { request_module("%s", name); if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask & CRYPTO_ALG_NEED_FALLBACK)) request_module("%s-all", name); alg = crypto_alg_lookup(name, type, mask); } if (alg) return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg; return crypto_larval_add(name, type, mask); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264', 'CWE-269'], 'message': 'crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <keescook@chromium.org> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPMA_CC_Unmarshal(TPMA_CC *target, BYTE **buffer, INT32 *size) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */ } if (rc == TPM_RC_SUCCESS) { if (*target & TPMA_CC_reserved) { rc = TPM_RC_RESERVED_BITS; } } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal Restore the original value of the memory location where data from a stream was unmarshalled and the unmarshalled value was found to be illegal. The goal is to not keep illegal values in memory. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPMI_RH_LOCKOUT_Unmarshal(TPMI_RH_LOCKOUT *target, BYTE **buffer, INT32 *size) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = TPM_HANDLE_Unmarshal(target, buffer, size); } if (rc == TPM_RC_SUCCESS) { switch (*target) { case TPM_RH_LOCKOUT: break; default: rc = TPM_RC_VALUE; } } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal Restore the original value of the memory location where data from a stream was unmarshalled and the unmarshalled value was found to be illegal. The goal is to not keep illegal values in memory. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPM_CAP_Unmarshal(TPM_CAP *target, BYTE **buffer, INT32 *size) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = UINT32_Unmarshal(target, buffer, size); } if (rc == TPM_RC_SUCCESS) { switch (*target) { case TPM_CAP_ALGS: case TPM_CAP_HANDLES: case TPM_CAP_COMMANDS: case TPM_CAP_PP_COMMANDS: case TPM_CAP_AUDIT_COMMANDS: case TPM_CAP_PCRS: case TPM_CAP_TPM_PROPERTIES: case TPM_CAP_PCR_PROPERTIES: case TPM_CAP_ECC_CURVES: case TPM_CAP_AUTH_POLICIES: case TPM_CAP_ACT: case TPM_CAP_VENDOR_PROPERTY: break; default: rc = TPM_RC_VALUE; } } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal Restore the original value of the memory location where data from a stream was unmarshalled and the unmarshalled value was found to be illegal. The goal is to not keep illegal values in memory. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPMI_RH_HIERARCHY_Unmarshal(TPMI_RH_HIERARCHY *target, BYTE **buffer, INT32 *size, BOOL allowNull) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = TPM_HANDLE_Unmarshal(target, buffer, size); } if (rc == TPM_RC_SUCCESS) { switch (*target) { case TPM_RH_OWNER: case TPM_RH_PLATFORM: case TPM_RH_ENDORSEMENT: break; case TPM_RH_NULL: if (allowNull) { break; } default: rc = TPM_RC_VALUE; } } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal Restore the original value of the memory location where data from a stream was unmarshalled and the unmarshalled value was found to be illegal. The goal is to not keep illegal values in memory. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPM_SU_Unmarshal(TPM_SU *target, BYTE **buffer, INT32 *size) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = UINT16_Unmarshal(target, buffer, size); } if (rc == TPM_RC_SUCCESS) { switch (*target) { case TPM_SU_CLEAR: case TPM_SU_STATE: break; default: rc = TPM_RC_VALUE; } } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal Restore the original value of the memory location where data from a stream was unmarshalled and the unmarshalled value was found to be illegal. The goal is to not keep illegal values in memory. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPMI_ALG_SYM_MODE_Unmarshal(TPMI_ALG_SYM_MODE *target, BYTE **buffer, INT32 *size, BOOL allowNull) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = TPM_ALG_ID_Unmarshal(target, buffer, size); } if (rc == TPM_RC_SUCCESS) { switch (*target) { #if ALG_CTR case TPM_ALG_CTR: #endif #if ALG_OFB case TPM_ALG_OFB: #endif #if ALG_CBC case TPM_ALG_CBC: #endif #if ALG_CFB case TPM_ALG_CFB: #endif #if ALG_ECB case TPM_ALG_ECB: #endif #if ALG_CMAC case TPM_ALG_CMAC: #endif break; case TPM_ALG_NULL: if (allowNull) { break; } default: rc = TPM_RC_MODE; } } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal Restore the original value of the memory location where data from a stream was unmarshalled and the unmarshalled value was found to be illegal. The goal is to not keep illegal values in memory. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPMI_DH_PARENT_Unmarshal(TPMI_DH_PARENT *target, BYTE **buffer, INT32 *size, BOOL allowNull) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = TPM_HANDLE_Unmarshal(target, buffer, size); } if (rc == TPM_RC_SUCCESS) { BOOL isNotTransient = (*target < TRANSIENT_FIRST) || (*target > TRANSIENT_LAST); BOOL isNotPersistent = (*target < PERSISTENT_FIRST) || (*target > PERSISTENT_LAST); BOOL isNotOwner = *target != TPM_RH_OWNER; BOOL isNotPlatform = *target != TPM_RH_PLATFORM; BOOL isNotEndorsement = *target != TPM_RH_ENDORSEMENT; BOOL isNotLegalNull = (*target != TPM_RH_NULL) || !allowNull; if (isNotTransient && isNotPersistent && isNotOwner && isNotPlatform && isNotEndorsement && isNotLegalNull) { rc = TPM_RC_VALUE; } } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal Restore the original value of the memory location where data from a stream was unmarshalled and the unmarshalled value was found to be illegal. The goal is to not keep illegal values in memory. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __init spectre_v2_select_mitigation(void) { enum spectre_v2_mitigation_cmd cmd = spectre_v2_parse_cmdline(); enum spectre_v2_mitigation mode = SPECTRE_V2_NONE; /* * If the CPU is not affected and the command line mode is NONE or AUTO * then nothing to do. */ if (!boot_cpu_has_bug(X86_BUG_SPECTRE_V2) && (cmd == SPECTRE_V2_CMD_NONE || cmd == SPECTRE_V2_CMD_AUTO)) return; switch (cmd) { case SPECTRE_V2_CMD_NONE: return; case SPECTRE_V2_CMD_FORCE: case SPECTRE_V2_CMD_AUTO: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_auto; break; case SPECTRE_V2_CMD_RETPOLINE_AMD: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_amd; break; case SPECTRE_V2_CMD_RETPOLINE_GENERIC: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_generic; break; case SPECTRE_V2_CMD_RETPOLINE: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_auto; break; } pr_err("Spectre mitigation: kernel not compiled with retpoline; no mitigation available!"); return; retpoline_auto: if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD) { retpoline_amd: if (!boot_cpu_has(X86_FEATURE_LFENCE_RDTSC)) { pr_err("Spectre mitigation: LFENCE not serializing, switching to generic retpoline\n"); goto retpoline_generic; } mode = retp_compiler() ? SPECTRE_V2_RETPOLINE_AMD : SPECTRE_V2_RETPOLINE_MINIMAL_AMD; setup_force_cpu_cap(X86_FEATURE_RETPOLINE_AMD); setup_force_cpu_cap(X86_FEATURE_RETPOLINE); } else { retpoline_generic: mode = retp_compiler() ? SPECTRE_V2_RETPOLINE_GENERIC : SPECTRE_V2_RETPOLINE_MINIMAL; setup_force_cpu_cap(X86_FEATURE_RETPOLINE); } spectre_v2_enabled = mode; pr_info("%s\n", spectre_v2_strings[mode]); /* * If neither SMEP nor PTI are available, there is a risk of * hitting userspace addresses in the RSB after a context switch * from a shallow call stack to a deeper one. To prevent this fill * the entire RSB, even when using IBRS. * * Skylake era CPUs have a separate issue with *underflow* of the * RSB, when they will predict 'ret' targets from the generic BTB. * The proper mitigation for this is IBRS. If IBRS is not supported * or deactivated in favour of retpolines the RSB fill on context * switch is required. */ if ((!boot_cpu_has(X86_FEATURE_PTI) && !boot_cpu_has(X86_FEATURE_SMEP)) || is_skylake_era()) { setup_force_cpu_cap(X86_FEATURE_RSB_CTXSW); pr_info("Spectre v2 mitigation: Filling RSB on context switch\n"); } /* Initialize Indirect Branch Prediction Barrier if supported */ if (boot_cpu_has(X86_FEATURE_IBPB)) { setup_force_cpu_cap(X86_FEATURE_USE_IBPB); pr_info("Spectre v2 mitigation: Enabling Indirect Branch Prediction Barrier\n"); } /* * Retpoline means the kernel is safe because it has no indirect * branches. But firmware isn't, so use IBRS to protect that. */ if (boot_cpu_has(X86_FEATURE_IBRS)) { setup_force_cpu_cap(X86_FEATURE_USE_IBRS_FW); pr_info("Enabling Restricted Speculation for firmware calls\n"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'x86/speculation: Protect against userspace-userspace spectreRSB The article "Spectre Returns! Speculation Attacks using the Return Stack Buffer" [1] describes two new (sub-)variants of spectrev2-like attacks, making use solely of the RSB contents even on CPUs that don't fallback to BTB on RSB underflow (Skylake+). Mitigate userspace-userspace attacks by always unconditionally filling RSB on context switch when the generic spectrev2 mitigation has been enabled. [1] https://arxiv.org/pdf/1807.07940.pdf Signed-off-by: Jiri Kosina <jkosina@suse.cz> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Reviewed-by: Josh Poimboeuf <jpoimboe@redhat.com> Acked-by: Tim Chen <tim.c.chen@linux.intel.com> Cc: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Cc: Borislav Petkov <bp@suse.de> Cc: David Woodhouse <dwmw@amazon.co.uk> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: stable@vger.kernel.org Link: https://lkml.kernel.org/r/nycvar.YFH.7.76.1807261308190.997@cbobk.fhfr.pm'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void mbedtls_strerror( int ret, char *buf, size_t buflen ) { size_t len; int use_ret; if( buflen == 0 ) return; memset( buf, 0x00, buflen ); if( ret < 0 ) ret = -ret; if( ret & 0xFF80 ) { use_ret = ret & 0xFF80; // High level error codes // // BEGIN generated code #if defined(MBEDTLS_CIPHER_C) if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "CIPHER - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "CIPHER - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) ) mbedtls_snprintf( buf, buflen, "CIPHER - Input data contains invalid padding and is rejected" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Decryption of block requires a full block" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) ) mbedtls_snprintf( buf, buflen, "CIPHER - The context is invalid, eg because it was free()ed" ); #endif /* MBEDTLS_CIPHER_C */ #if defined(MBEDTLS_DHM_C) if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "DHM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Making of the DHM parameters failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Reading of the public values failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Making of the public value failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Calculation of the DHM secret failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "DHM - The ASN.1 data is not formatted correctly" ); if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Allocation of memory failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "DHM - Read/write of file failed" ); #endif /* MBEDTLS_DHM_C */ #if defined(MBEDTLS_ECP_C) if( use_ret == -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "ECP - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "ECP - The buffer is too small to write to" ); if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "ECP - Requested curve not available" ); if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - The signature is not valid" ); if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - Generation of random value, such as (ephemeral) key, failed" ); if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) ) mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" ); if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) ) mbedtls_snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" ); #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_MD_C) if( use_ret == -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "MD - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_MD_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "MD - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_MD_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "MD - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "MD - Opening or reading of file failed" ); #endif /* MBEDTLS_MD_C */ #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) if( use_ret == -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) ) mbedtls_snprintf( buf, buflen, "PEM - No PEM header or footer found" ); if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_DATA) ) mbedtls_snprintf( buf, buflen, "PEM - PEM string is not as expected" ); if( use_ret == -(MBEDTLS_ERR_PEM_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "PEM - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_ENC_IV) ) mbedtls_snprintf( buf, buflen, "PEM - RSA IV is not in hex-format" ); if( use_ret == -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG) ) mbedtls_snprintf( buf, buflen, "PEM - Unsupported key encryption algorithm" ); if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) ) mbedtls_snprintf( buf, buflen, "PEM - Private key password can't be empty" ); if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PEM - Given private key password does not allow for correct decryption" ); if( use_ret == -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PEM - Unavailable feature, e.g. hashing/encryption combination" ); if( use_ret == -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PEM - Bad input parameters to function" ); #endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */ #if defined(MBEDTLS_PK_C) if( use_ret == -(MBEDTLS_ERR_PK_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "PK - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_PK_TYPE_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" ); if( use_ret == -(MBEDTLS_ERR_PK_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PK - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PK_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "PK - Read/write of file failed" ); if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION) ) mbedtls_snprintf( buf, buflen, "PK - Unsupported key version" ); if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PK - Invalid key tag or value" ); if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG) ) mbedtls_snprintf( buf, buflen, "PK - Key algorithm is unsupported (only RSA and EC are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED) ) mbedtls_snprintf( buf, buflen, "PK - Private key password can't be empty" ); if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - Given private key password does not allow for correct decryption" ); if( use_ret == -(MBEDTLS_ERR_PK_INVALID_PUBKEY) ) mbedtls_snprintf( buf, buflen, "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_INVALID_ALG) ) mbedtls_snprintf( buf, buflen, "PK - The algorithm tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE) ) mbedtls_snprintf( buf, buflen, "PK - Elliptic curve is unsupported (only NIST curves are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" ); if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" ); #endif /* MBEDTLS_PK_C */ #if defined(MBEDTLS_PKCS12_C) if( use_ret == -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Given private key password does not allow for correct decryption" ); #endif /* MBEDTLS_PKCS12_C */ #if defined(MBEDTLS_PKCS5_C) if( use_ret == -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Unexpected ASN.1 data" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Requested encryption or digest alg not available" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Given private key password does not allow for correct decryption" ); #endif /* MBEDTLS_PKCS5_C */ #if defined(MBEDTLS_RSA_C) if( use_ret == -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "RSA - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_RSA_INVALID_PADDING) ) mbedtls_snprintf( buf, buflen, "RSA - Input data contains invalid padding and is rejected" ); if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - Something failed during generation of a key" ); if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - Key failed to pass the library's validity check" ); if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The public key operation failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The private key operation failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The PKCS#1 verification failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE) ) mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" ); if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" ); #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_SSL_TLS_C) if( use_ret == -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "SSL - The requested feature is not available" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "SSL - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_MAC) ) mbedtls_snprintf( buf, buflen, "SSL - Verification of the message MAC failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_RECORD) ) mbedtls_snprintf( buf, buflen, "SSL - An invalid SSL record was received" ); if( use_ret == -(MBEDTLS_ERR_SSL_CONN_EOF) ) mbedtls_snprintf( buf, buflen, "SSL - The connection indicated an EOF" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) ) mbedtls_snprintf( buf, buflen, "SSL - An unknown cipher was received" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) ) mbedtls_snprintf( buf, buflen, "SSL - The server has no ciphersuites in common with the client" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_RNG) ) mbedtls_snprintf( buf, buflen, "SSL - No RNG was provided to the SSL module" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE) ) mbedtls_snprintf( buf, buflen, "SSL - No client certification received from the client, but required by the authentication mode" ); if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) ) mbedtls_snprintf( buf, buflen, "SSL - Our own certificate(s) is/are too large to send in an SSL message" ); if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - The own certificate is not set, but needed by the server" ); if( use_ret == -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - The own private key or pre-shared key is not set, but needed" ); if( use_ret == -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - No CA Chain is set, but required to operate" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) ) mbedtls_snprintf( buf, buflen, "SSL - An unexpected message was received from our peer" ); if( use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) ) { mbedtls_snprintf( buf, buflen, "SSL - A fatal alert message was received from our peer" ); return; } if( use_ret == -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Verification of our peer failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) ) mbedtls_snprintf( buf, buflen, "SSL - The peer notified us that the connection is going to be closed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientHello handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHello handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the Certificate handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateRequest handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerKeyExchange handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHelloDone handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateVerify handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ChangeCipherSpec handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the Finished handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function returned with error" ); if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH) ) mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function skipped / left alone data" ); if( use_ret == -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the compression / decompression failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) ) mbedtls_snprintf( buf, buflen, "SSL - Handshake protocol not within min/max boundaries" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the NewSessionTicket handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) ) mbedtls_snprintf( buf, buflen, "SSL - Session ticket has expired" ); if( use_ret == -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH) ) mbedtls_snprintf( buf, buflen, "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) ) mbedtls_snprintf( buf, buflen, "SSL - Unknown identity received (eg, PSK identity)" ); if( use_ret == -(MBEDTLS_ERR_SSL_INTERNAL_ERROR) ) mbedtls_snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" ); if( use_ret == -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING) ) mbedtls_snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" ); if( use_ret == -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) ) mbedtls_snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" ); if( use_ret == -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - DTLS client must retry for hello verification" ); if( use_ret == -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "SSL - A buffer is too small to receive or write a message" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) ) mbedtls_snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" ); if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) ) mbedtls_snprintf( buf, buflen, "SSL - Connection requires a read call" ); if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) ) mbedtls_snprintf( buf, buflen, "SSL - Connection requires a write call" ); if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) ) mbedtls_snprintf( buf, buflen, "SSL - The operation timed out" ); if( use_ret == -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT) ) mbedtls_snprintf( buf, buflen, "SSL - The client initiated a reconnect from the same port" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) ) mbedtls_snprintf( buf, buflen, "SSL - Record header looks valid but is not expected" ); if( use_ret == -(MBEDTLS_ERR_SSL_NON_FATAL) ) mbedtls_snprintf( buf, buflen, "SSL - The alert message received indicates a non-fatal error" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) ) mbedtls_snprintf( buf, buflen, "SSL - Couldn't set the hash for verifying CertificateVerify" ); #endif /* MBEDTLS_SSL_TLS_C */ #if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) if( use_ret == -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_OID) ) mbedtls_snprintf( buf, buflen, "X509 - Requested OID is unknown" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_VERSION) ) mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR version element is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SERIAL) ) mbedtls_snprintf( buf, buflen, "X509 - The serial tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_ALG) ) mbedtls_snprintf( buf, buflen, "X509 - The algorithm tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_NAME) ) mbedtls_snprintf( buf, buflen, "X509 - The name tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_DATE) ) mbedtls_snprintf( buf, buflen, "X509 - The date tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SIGNATURE) ) mbedtls_snprintf( buf, buflen, "X509 - The signature tag or value invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS) ) mbedtls_snprintf( buf, buflen, "X509 - The extension tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_VERSION) ) mbedtls_snprintf( buf, buflen, "X509 - CRT/CRL/CSR has an unsupported version number" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG) ) mbedtls_snprintf( buf, buflen, "X509 - Signature algorithm (oid) is unsupported" ); if( use_ret == -(MBEDTLS_ERR_X509_SIG_MISMATCH) ) mbedtls_snprintf( buf, buflen, "X509 - Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid)" ); if( use_ret == -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" ); if( use_ret == -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT) ) mbedtls_snprintf( buf, buflen, "X509 - Format not recognized as DER or PEM" ); if( use_ret == -(MBEDTLS_ERR_X509_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "X509 - Input invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "X509 - Allocation of memory failed" ); if( use_ret == -(MBEDTLS_ERR_X509_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "X509 - Read/write of file failed" ); if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "X509 - Destination buffer is too small" ); #endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */ // END generated code if( strlen( buf ) == 0 ) mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret ); } use_ret = ret & ~0xFF80; if( use_ret == 0 ) return; // If high level code is present, make a concatenation between both // error strings. // len = strlen( buf ); if( len > 0 ) { if( buflen - len < 5 ) return; mbedtls_snprintf( buf + len, buflen - len, " : " ); buf += len + 3; buflen -= len + 3; } // Low level error codes // // BEGIN generated code #if defined(MBEDTLS_AES_C) if( use_ret == -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "AES - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" ); #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_ASN1_PARSE_C) if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) ) mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" ); if( use_ret == -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) ) mbedtls_snprintf( buf, buflen, "ASN1 - ASN1 tag was of an unexpected value" ); if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_LENGTH) ) mbedtls_snprintf( buf, buflen, "ASN1 - Error when trying to determine the length or invalid length" ); if( use_ret == -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH) ) mbedtls_snprintf( buf, buflen, "ASN1 - Actual length differs from expected length" ); if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_DATA) ) mbedtls_snprintf( buf, buflen, "ASN1 - Data is invalid. (not used)" ); if( use_ret == -(MBEDTLS_ERR_ASN1_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "ASN1 - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "ASN1 - Buffer too small when writing ASN.1 data structure" ); #endif /* MBEDTLS_ASN1_PARSE_C */ #if defined(MBEDTLS_BASE64_C) if( use_ret == -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "BASE64 - Output buffer too small" ); if( use_ret == -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER) ) mbedtls_snprintf( buf, buflen, "BASE64 - Invalid character in input" ); #endif /* MBEDTLS_BASE64_C */ #if defined(MBEDTLS_BIGNUM_C) if( use_ret == -(MBEDTLS_ERR_MPI_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "BIGNUM - An error occurred while reading from or writing to a file" ); if( use_ret == -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "BIGNUM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_MPI_INVALID_CHARACTER) ) mbedtls_snprintf( buf, buflen, "BIGNUM - There is an invalid character in the digit string" ); if( use_ret == -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The buffer is too small to write to" ); if( use_ret == -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are negative or result in illegal output" ); if( use_ret == -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input argument for division is zero, which is not allowed" ); if( use_ret == -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are not acceptable" ); if( use_ret == -(MBEDTLS_ERR_MPI_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "BIGNUM - Memory allocation failed" ); #endif /* MBEDTLS_BIGNUM_C */ #if defined(MBEDTLS_BLOWFISH_C) if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" ); #endif /* MBEDTLS_BLOWFISH_C */ #if defined(MBEDTLS_CAMELLIA_C) if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" ); #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_CCM_C) if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) ) mbedtls_snprintf( buf, buflen, "CCM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "CCM - Authenticated decryption failed" ); #endif /* MBEDTLS_CCM_C */ #if defined(MBEDTLS_CTR_DRBG_C) if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Too many random requested in single call" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Input too large (Entropy + additional)" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Read/write error in file" ); #endif /* MBEDTLS_CTR_DRBG_C */ #if defined(MBEDTLS_DES_C) if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "DES - The data input has an invalid length" ); #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ENTROPY_C) if( use_ret == -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "ENTROPY - Critical entropy source failure" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No more sources can be added" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No sources have been added to poll" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No strong sources have been added to poll" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "ENTROPY - Read/write error in file" ); #endif /* MBEDTLS_ENTROPY_C */ #if defined(MBEDTLS_GCM_C) if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "GCM - Authenticated decryption failed" ); if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) ) mbedtls_snprintf( buf, buflen, "GCM - Bad input parameters to function" ); #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_HMAC_DRBG_C) if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Too many random requested in single call" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Input too large (Entropy + additional)" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Read/write error in file" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" ); #endif /* MBEDTLS_HMAC_DRBG_C */ #if defined(MBEDTLS_NET_C) if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Failed to open a socket" ); if( use_ret == -(MBEDTLS_ERR_NET_CONNECT_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - The connection to the given server / port failed" ); if( use_ret == -(MBEDTLS_ERR_NET_BIND_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Binding of the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_LISTEN_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Could not listen on the socket" ); if( use_ret == -(MBEDTLS_ERR_NET_ACCEPT_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Could not accept the incoming connection" ); if( use_ret == -(MBEDTLS_ERR_NET_RECV_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Reading information from the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_SEND_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Sending information through the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_CONN_RESET) ) mbedtls_snprintf( buf, buflen, "NET - Connection was reset by peer" ); if( use_ret == -(MBEDTLS_ERR_NET_UNKNOWN_HOST) ) mbedtls_snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" ); if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "NET - Buffer is too small to hold the data" ); if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) ) mbedtls_snprintf( buf, buflen, "NET - The context is invalid, eg because it was free()ed" ); #endif /* MBEDTLS_NET_C */ #if defined(MBEDTLS_OID_C) if( use_ret == -(MBEDTLS_ERR_OID_NOT_FOUND) ) mbedtls_snprintf( buf, buflen, "OID - OID is not found" ); if( use_ret == -(MBEDTLS_ERR_OID_BUF_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "OID - output buffer is too small" ); #endif /* MBEDTLS_OID_C */ #if defined(MBEDTLS_PADLOCK_C) if( use_ret == -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED) ) mbedtls_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" ); #endif /* MBEDTLS_PADLOCK_C */ #if defined(MBEDTLS_THREADING_C) if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "THREADING - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "THREADING - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_THREADING_MUTEX_ERROR) ) mbedtls_snprintf( buf, buflen, "THREADING - Locking / unlocking / free failed with error code" ); #endif /* MBEDTLS_THREADING_C */ #if defined(MBEDTLS_XTEA_C) if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "XTEA - The data input has an invalid length" ); #endif /* MBEDTLS_XTEA_C */ // END generated code if( strlen( buf ) != 0 ) return; mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'Only return VERIFY_FAILED from a single point Everything else is a fatal error. Also improve documentation about that for the vrfy callback.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: njs_object_iterate_reverse(njs_vm_t *vm, njs_iterator_args_t *args, njs_iterator_handler_t handler) { double idx; int64_t i, from, to, length; njs_int_t ret; njs_array_t *array, *keys; njs_value_t *entry, *value, prop, character, string_obj; const u_char *p, *end, *pos; njs_string_prop_t string_prop; njs_object_value_t *object; value = args->value; from = args->from; to = args->to; if (njs_is_array(value)) { array = njs_array(value); from += 1; while (from-- > to) { if (njs_slow_path(!array->object.fast_array)) { goto process_object; } if (njs_fast_path(from < array->length && njs_is_valid(&array->start[from]))) { ret = handler(vm, args, &array->start[from], from); } else { entry = njs_value_arg(&njs_value_invalid); ret = njs_value_property_i64(vm, value, from, &prop); if (njs_slow_path(ret != NJS_DECLINED)) { if (ret == NJS_ERROR) { return NJS_ERROR; } entry = &prop; } ret = handler(vm, args, entry, from); } if (njs_slow_path(ret != NJS_OK)) { if (ret == NJS_DONE) { return NJS_DONE; } return NJS_ERROR; } } return NJS_OK; } if (njs_is_string(value) || njs_is_object_string(value)) { if (njs_is_string(value)) { object = njs_object_value_alloc(vm, NJS_OBJ_TYPE_STRING, 0, value); if (njs_slow_path(object == NULL)) { return NJS_ERROR; } njs_set_object_value(&string_obj, object); args->value = &string_obj; } else { value = njs_object_value(value); } length = njs_string_prop(&string_prop, value); end = string_prop.start + string_prop.size; if ((size_t) length == string_prop.size) { /* Byte or ASCII string. */ p = string_prop.start + from; i = from + 1; while (i-- > to) { /* This cannot fail. */ (void) njs_string_new(vm, &character, p, 1, 1); ret = handler(vm, args, &character, i); if (njs_slow_path(ret != NJS_OK)) { if (ret == NJS_DONE) { return NJS_DONE; } return NJS_ERROR; } p--; } } else { /* UTF-8 string. */ p = njs_string_offset(string_prop.start, end, from); p = njs_utf8_next(p, end); i = from + 1; while (i-- > to) { pos = njs_utf8_prev(p); /* This cannot fail. */ (void) njs_string_new(vm, &character, pos, p - pos , 1); ret = handler(vm, args, &character, i); if (njs_slow_path(ret != NJS_OK)) { if (ret == NJS_DONE) { return NJS_DONE; } return NJS_ERROR; } p = pos; } } return NJS_OK; } if (!njs_is_object(value)) { return NJS_OK; } process_object: if (!njs_fast_object(from - to)) { keys = njs_array_indices(vm, value); if (njs_slow_path(keys == NULL)) { return NJS_ERROR; } i = keys->length; while (i > 0) { idx = njs_string_to_index(&keys->start[--i]); if (idx < to || idx > from) { continue; } ret = njs_iterator_object_handler(vm, handler, args, &keys->start[i], idx); if (njs_slow_path(ret != NJS_OK)) { njs_array_destroy(vm, keys); return ret; } } njs_array_destroy(vm, keys); return NJS_OK; } i = from + 1; while (i-- > to) { ret = njs_iterator_object_handler(vm, handler, args, NULL, i); if (njs_slow_path(ret != NJS_OK)) { return ret; } } return NJS_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'Fixed Array.prototype.lastIndexOf() with unicode string as "this". Previously, when lastIndexOf() was called with unicode string as "this" argument and a negative "fromIndex" argument null-pointer dererence might occur because njs_string_offset() was called with invalid index value whereas njs_string_offset() should always be called with valid index argument. The fix is to verify that from index is valid. This closes #482 issue on Github.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *this_branch = env->cur_state; struct bpf_verifier_state *other_branch; struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; u8 opcode = BPF_OP(insn->code); bool is_jmp32; int pred = -1; int err; /* Only conditional jumps are expected to reach here. */ if (opcode == BPF_JA || opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } src_reg = &regs[insn->src_reg]; } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; if (BPF_SRC(insn->code) == BPF_K) { pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); } else if (src_reg->type == SCALAR_VALUE && is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { pred = is_branch_taken(dst_reg, tnum_subreg(src_reg->var_off).value, opcode, is_jmp32); } else if (src_reg->type == SCALAR_VALUE && !is_jmp32 && tnum_is_const(src_reg->var_off)) { pred = is_branch_taken(dst_reg, src_reg->var_off.value, opcode, is_jmp32); } else if (reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg) && !is_jmp32) { pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); } if (pred >= 0) { /* If we get here with a dst_reg pointer type it is because * above is_branch_taken() special cased the 0 comparison. */ if (!__is_pointer_value(false, dst_reg)) err = mark_chain_precision(env, insn->dst_reg); if (BPF_SRC(insn->code) == BPF_X && !err && !__is_pointer_value(false, src_reg)) err = mark_chain_precision(env, insn->src_reg); if (err) return err; } if (pred == 1) { /* only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else if (pred == 0) { /* only follow fall-through branch, since * that's where the program will go */ return 0; } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); if (!other_branch) return -EFAULT; other_branch_regs = other_branch->frame[other_branch->curframe]->regs; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { struct bpf_reg_state *src_reg = &regs[insn->src_reg]; if (dst_reg->type == SCALAR_VALUE && src_reg->type == SCALAR_VALUE) { if (tnum_is_const(src_reg->var_off) || (is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off)))) reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, src_reg->var_off.value, tnum_subreg(src_reg->var_off).value, opcode, is_jmp32); else if (tnum_is_const(dst_reg->var_off) || (is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off)))) reg_set_min_max_inv(&other_branch_regs[insn->src_reg], src_reg, dst_reg->var_off.value, tnum_subreg(dst_reg->var_off).value, opcode, is_jmp32); else if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE)) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch_regs[insn->src_reg], &other_branch_regs[insn->dst_reg], src_reg, dst_reg, opcode); if (src_reg->id && !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { find_equal_scalars(this_branch, src_reg); find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); } } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, insn->imm, (u32)insn->imm, opcode, is_jmp32); } if (dst_reg->type == SCALAR_VALUE && dst_reg->id && !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { find_equal_scalars(this_branch, dst_reg); find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). * NOTE: these optimizations below are related with pointer comparison * which will never be JMP32. */ if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && reg_type_may_be_null(dst_reg->type)) { /* Mark all identical registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_ptr_or_null_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_ptr_or_null_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level & BPF_LOG_LEVEL) print_verifier_state(env, this_branch->frame[this_branch->curframe]); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-203'], 'message': 'bpf: Fix leakage under speculation on mispredicted branches The verifier only enumerates valid control-flow paths and skips paths that are unreachable in the non-speculative domain. And so it can miss issues under speculative execution on mispredicted branches. For example, a type confusion has been demonstrated with the following crafted program: // r0 = pointer to a map array entry // r6 = pointer to readable stack slot // r9 = scalar controlled by attacker 1: r0 = *(u64 *)(r0) // cache miss 2: if r0 != 0x0 goto line 4 3: r6 = r9 4: if r0 != 0x1 goto line 6 5: r9 = *(u8 *)(r6) 6: // leak r9 Since line 3 runs iff r0 == 0 and line 5 runs iff r0 == 1, the verifier concludes that the pointer dereference on line 5 is safe. But: if the attacker trains both the branches to fall-through, such that the following is speculatively executed ... r6 = r9 r9 = *(u8 *)(r6) // leak r9 ... then the program will dereference an attacker-controlled value and could leak its content under speculative execution via side-channel. This requires to mistrain the branch predictor, which can be rather tricky, because the branches are mutually exclusive. However such training can be done at congruent addresses in user space using different branches that are not mutually exclusive. That is, by training branches in user space ... A: if r0 != 0x0 goto line C B: ... C: if r0 != 0x0 goto line D D: ... ... such that addresses A and C collide to the same CPU branch prediction entries in the PHT (pattern history table) as those of the BPF program's lines 2 and 4, respectively. A non-privileged attacker could simply brute force such collisions in the PHT until observing the attack succeeding. Alternative methods to mistrain the branch predictor are also possible that avoid brute forcing the collisions in the PHT. A reliable attack has been demonstrated, for example, using the following crafted program: // r0 = pointer to a [control] map array entry // r7 = *(u64 *)(r0 + 0), training/attack phase // r8 = *(u64 *)(r0 + 8), oob address // [...] // r0 = pointer to a [data] map array entry 1: if r7 == 0x3 goto line 3 2: r8 = r0 // crafted sequence of conditional jumps to separate the conditional // branch in line 193 from the current execution flow 3: if r0 != 0x0 goto line 5 4: if r0 == 0x0 goto exit 5: if r0 != 0x0 goto line 7 6: if r0 == 0x0 goto exit [...] 187: if r0 != 0x0 goto line 189 188: if r0 == 0x0 goto exit // load any slowly-loaded value (due to cache miss in phase 3) ... 189: r3 = *(u64 *)(r0 + 0x1200) // ... and turn it into known zero for verifier, while preserving slowly- // loaded dependency when executing: 190: r3 &= 1 191: r3 &= 2 // speculatively bypassed phase dependency 192: r7 += r3 193: if r7 == 0x3 goto exit 194: r4 = *(u8 *)(r8 + 0) // leak r4 As can be seen, in training phase (phase != 0x3), the condition in line 1 turns into false and therefore r8 with the oob address is overridden with the valid map value address, which in line 194 we can read out without issues. However, in attack phase, line 2 is skipped, and due to the cache miss in line 189 where the map value is (zeroed and later) added to the phase register, the condition in line 193 takes the fall-through path due to prior branch predictor training, where under speculation, it'll load the byte at oob address r8 (unknown scalar type at that point) which could then be leaked via side-channel. One way to mitigate these is to 'branch off' an unreachable path, meaning, the current verification path keeps following the is_branch_taken() path and we push the other branch to the verification stack. Given this is unreachable from the non-speculative domain, this branch's vstate is explicitly marked as speculative. This is needed for two reasons: i) if this path is solely seen from speculative execution, then we later on still want the dead code elimination to kick in in order to sanitize these instructions with jmp-1s, and ii) to ensure that paths walked in the non-speculative domain are not pruned from earlier walks of paths walked in the speculative domain. Additionally, for robustness, we mark the registers which have been part of the conditional as unknown in the speculative path given there should be no assumptions made on their content. The fix in here mitigates type confusion attacks described earlier due to i) all code paths in the BPF program being explored and ii) existing verifier logic already ensuring that given memory access instruction references one specific data structure. An alternative to this fix that has also been looked at in this scope was to mark aux->alu_state at the jump instruction with a BPF_JMP_TAKEN state as well as direction encoding (always-goto, always-fallthrough, unknown), such that mixing of different always-* directions themselves as well as mixing of always-* with unknown directions would cause a program rejection by the verifier, e.g. programs with constructs like 'if ([...]) { x = 0; } else { x = 1; }' with subsequent 'if (x == 1) { [...] }'. For unprivileged, this would result in only single direction always-* taken paths, and unknown taken paths being allowed, such that the former could be patched from a conditional jump to an unconditional jump (ja). Compared to this approach here, it would have two downsides: i) valid programs that otherwise are not performing any pointer arithmetic, etc, would potentially be rejected/broken, and ii) we are required to turn off path pruning for unprivileged, where both can be avoided in this work through pushing the invalid branch to the verification stack. The issue was originally discovered by Adam and Ofek, and later independently discovered and reported as a result of Benedict and Piotr's research work. Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Adam Morrison <mad@cs.tau.ac.il> Reported-by: Ofek Kirzner <ofekkir@gmail.com> Reported-by: Benedict Schlueter <benedict.schlueter@rub.de> Reported-by: Piotr Krysiuk <piotras@gmail.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Reviewed-by: John Fastabend <john.fastabend@gmail.com> Reviewed-by: Benedict Schlueter <benedict.schlueter@rub.de> Reviewed-by: Piotr Krysiuk <piotras@gmail.com> Acked-by: Alexei Starovoitov <ast@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ifb_setup(struct net_device *dev) { /* Initialize the device structure. */ dev->destructor = free_netdev; dev->netdev_ops = &ifb_netdev_ops; /* Fill in device structure with ethernet-generic values. */ ether_setup(dev); dev->tx_queue_len = TX_Q_LIMIT; dev->features |= IFB_FEATURES; dev->vlan_features |= IFB_FEATURES; dev->flags |= IFF_NOARP; dev->flags &= ~IFF_MULTICAST; dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; random_ether_addr(dev->dev_addr); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <nhorman@tuxdriver.com> CC: Karsten Keil <isdn@linux-pingi.de> CC: "David S. Miller" <davem@davemloft.net> CC: Jay Vosburgh <fubar@us.ibm.com> CC: Andy Gospodarek <andy@greyhouse.net> CC: Patrick McHardy <kaber@trash.net> CC: Krzysztof Halasa <khc@pm.waw.pl> CC: "John W. Linville" <linville@tuxdriver.com> CC: Greg Kroah-Hartman <gregkh@suse.de> CC: Marcel Holtmann <marcel@holtmann.org> CC: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ar6000_create_ap_interface(struct ar6_softc *ar, char *ap_ifname) { struct net_device *dev; struct ar_virtual_interface *arApDev; dev = alloc_etherdev(sizeof(struct ar_virtual_interface)); if (dev == NULL) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: can't alloc etherdev\n")); return A_ERROR; } ether_setup(dev); init_netdev(dev, ap_ifname); if (register_netdev(dev)) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: register_netdev failed\n")); return A_ERROR; } arApDev = netdev_priv(dev); arApDev->arDev = ar; arApDev->arNetDev = dev; arApDev->arStaNetDev = ar->arNetDev; ar->arApDev = arApDev; arApNetDev = dev; /* Copy the MAC address */ memcpy(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <nhorman@tuxdriver.com> CC: Karsten Keil <isdn@linux-pingi.de> CC: "David S. Miller" <davem@davemloft.net> CC: Jay Vosburgh <fubar@us.ibm.com> CC: Andy Gospodarek <andy@greyhouse.net> CC: Patrick McHardy <kaber@trash.net> CC: Krzysztof Halasa <khc@pm.waw.pl> CC: "John W. Linville" <linville@tuxdriver.com> CC: Greg Kroah-Hartman <gregkh@suse.de> CC: Marcel Holtmann <marcel@holtmann.org> CC: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int secure_decrypt(void *data, unsigned int data_length, int is_signed) { at91_aes_key_size_t key_size; unsigned int cmac_key[8], cipher_key[8]; unsigned int iv[AT91_AES_IV_SIZE_WORD]; unsigned int computed_cmac[AT91_AES_BLOCK_SIZE_WORD]; unsigned int fixed_length; const unsigned int *cmac; int rc = -1; /* Init keys */ init_keys(&key_size, cipher_key, cmac_key, iv); /* Init periph */ at91_aes_init(); /* Check signature if required */ if (is_signed) { /* Compute the CMAC */ if (at91_aes_cmac(data_length, data, computed_cmac, key_size, cmac_key)) goto exit; /* Check the CMAC */ fixed_length = at91_aes_roundup(data_length); cmac = (const unsigned int *)((char *)data + fixed_length); if (memcmp(cmac, computed_cmac, AT91_AES_BLOCK_SIZE_BYTE)) goto exit; } /* Decrypt the whole file */ if (at91_aes_cbc(data_length, data, data, 0, key_size, cipher_key, iv)) goto exit; rc = 0; exit: /* Reset periph */ at91_aes_cleanup(); /* Reset keys */ memset(cmac_key, 0, sizeof(cmac_key)); memset(cipher_key, 0, sizeof(cipher_key)); memset(iv, 0, sizeof(iv)); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-203'], 'message': 'driver: secure: use consttime_memequal for memory comparison Do not use memcmp() to compare security critical data, such as cryptographic secrets, because the required CPU time depends on the number of equal bytes. Instead, a function that performs comparisons in constant time is required. Warning: consttime_memequal returns 0 if data are NOT equal, and 1 if they are equal. Signed-off-by: Eugen Hristev <eugen.hristev@microchip.com> Reviewed-by: Nicolas Ferre <nicolas.ferre@microchip.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline void AveragePool(const float* input_data, const Dims<4>& input_dims, int stride_width, int stride_height, int pad_width, int pad_height, int kwidth, int kheight, float output_activation_min, float output_activation_max, float* output_data, const Dims<4>& output_dims) { tflite::PoolParams params; params.stride_height = stride_height; params.stride_width = stride_width; params.filter_height = kheight; params.filter_width = kwidth; params.padding_values.height = pad_height; params.padding_values.width = pad_width; params.float_activation_min = output_activation_min; params.float_activation_max = output_activation_max; AveragePool(params, DimsToShape(input_dims), input_data, DimsToShape(output_dims), output_data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops. PiperOrigin-RevId: 385184660 Change-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline void AveragePool(const PoolParams& params, const RuntimeShape& input_shape, const float* input_data, const RuntimeShape& output_shape, float* output_data) { ruy::profiler::ScopeLabel label("AveragePool"); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int stride_height = params.stride_height; const int stride_width = params.stride_width; // TODO(benoitjacob) make this a proper reference impl without Eigen! const auto in_mat = MapAsMatrixWithLastDimAsRows(input_data, input_shape); auto out_mat = MapAsMatrixWithLastDimAsRows(output_data, output_shape); // TODO(benoitjacob) get rid of the dynamic memory allocation here! Eigen::VectorXf out_count(out_mat.cols()); out_count.setZero(); // Prefill the output to 0. out_mat.setZero(); for (int b = 0; b < batches; ++b) { for (int h = 0; h < input_height; ++h) { for (int w = 0; w < input_width; ++w) { // (h_start, h_end) * (w_start, w_end) is the range that the input // vector projects to. int hpad = h + params.padding_values.height; int wpad = w + params.padding_values.width; int h_start = (hpad < params.filter_height) ? 0 : (hpad - params.filter_height) / stride_height + 1; int h_end = std::min(hpad / stride_height + 1, output_height); int w_start = (wpad < params.filter_width) ? 0 : (wpad - params.filter_width) / stride_width + 1; int w_end = std::min(wpad / stride_width + 1, output_width); // compute elementwise sum for (int ph = h_start; ph < h_end; ++ph) { for (int pw = w_start; pw < w_end; ++pw) { int out_offset = NodeOffset(b, ph, pw, output_height, output_width); out_mat.col(out_offset) += in_mat.col(NodeOffset(b, h, w, input_height, input_width)); out_count(out_offset)++; } } } } } // Divide the output by the actual number of elements being averaged over TFLITE_DCHECK_GT(out_count.minCoeff(), 0); out_mat.array().rowwise() /= out_count.transpose().array(); const int flat_size = output_shape.FlatSize(); for (int i = 0; i < flat_size; ++i) { output_data[i] = ActivationFunctionWithMinMax(output_data[i], params.float_activation_min, params.float_activation_max); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops. PiperOrigin-RevId: 385184660 Change-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static __inline__ int scm_check_creds(struct ucred *creds) { const struct cred *cred = current_cred(); kuid_t uid = make_kuid(cred->user_ns, creds->uid); kgid_t gid = make_kgid(cred->user_ns, creds->gid); if (!uid_valid(uid) || !gid_valid(gid)) return -EINVAL; if ((creds->pid == task_tgid_vnr(current) || nsown_capable(CAP_SYS_ADMIN)) && ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) || uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) && ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) || gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) { return 0; } return -EPERM; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'scm: Require CAP_SYS_ADMIN over the current pidns to spoof pids. Don't allow spoofing pids over unix domain sockets in the corner cases where a user has created a user namespace but has not yet created a pid namespace. Cc: stable@vger.kernel.org Reported-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ecma_find_or_create_literal_string (const lit_utf8_byte_t *chars_p, /**< string to be searched */ lit_utf8_size_t size) /**< size of the string */ { ecma_string_t *string_p = ecma_new_ecma_string_from_utf8 (chars_p, size); if (ECMA_IS_DIRECT_STRING (string_p)) { return ecma_make_string_value (string_p); } jmem_cpointer_t string_list_cp = JERRY_CONTEXT (string_list_first_cp); jmem_cpointer_t *empty_cpointer_p = NULL; while (string_list_cp != JMEM_CP_NULL) { ecma_lit_storage_item_t *string_list_p = JMEM_CP_GET_NON_NULL_POINTER (ecma_lit_storage_item_t, string_list_cp); for (int i = 0; i < ECMA_LIT_STORAGE_VALUE_COUNT; i++) { if (string_list_p->values[i] == JMEM_CP_NULL) { if (empty_cpointer_p == NULL) { empty_cpointer_p = string_list_p->values + i; } } else { ecma_string_t *value_p = JMEM_CP_GET_NON_NULL_POINTER (ecma_string_t, string_list_p->values[i]); if (ecma_compare_ecma_strings (string_p, value_p)) { /* Return with string if found in the list. */ ecma_deref_ecma_string (string_p); return ecma_make_string_value (value_p); } } } string_list_cp = string_list_p->next_cp; } ECMA_SET_STRING_AS_STATIC (string_p); jmem_cpointer_t result; JMEM_CP_SET_NON_NULL_POINTER (result, string_p); if (empty_cpointer_p != NULL) { *empty_cpointer_p = result; return ecma_make_string_value (string_p); } ecma_lit_storage_item_t *new_item_p; new_item_p = (ecma_lit_storage_item_t *) jmem_pools_alloc (sizeof (ecma_lit_storage_item_t)); new_item_p->values[0] = result; for (int i = 1; i < ECMA_LIT_STORAGE_VALUE_COUNT; i++) { new_item_p->values[i] = JMEM_CP_NULL; } new_item_p->next_cp = JERRY_CONTEXT (string_list_first_cp); JMEM_CP_SET_NON_NULL_POINTER (JERRY_CONTEXT (string_list_first_cp), new_item_p); return ecma_make_string_value (string_p); } /* ecma_find_or_create_literal_string */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691) Ascii string length is no longer computed during string allocation. JerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lexer_parse_number (parser_context_t *context_p) /**< context */ { const uint8_t *source_p = context_p->source_p; const uint8_t *source_end_p = context_p->source_end_p; bool can_be_float = false; #if JERRY_BUILTIN_BIGINT bool can_be_bigint = true; #endif /* JERRY_BUILTIN_BIGINT */ size_t length; context_p->token.type = LEXER_LITERAL; context_p->token.extra_value = LEXER_NUMBER_DECIMAL; context_p->token.lit_location.char_p = source_p; context_p->token.lit_location.type = LEXER_NUMBER_LITERAL; context_p->token.lit_location.has_escape = false; if (source_p[0] == LIT_CHAR_0 && source_p + 1 < source_end_p) { #if JERRY_ESNEXT if (source_p[1] == LIT_CHAR_UNDERSCORE) { parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER); } #endif /* JERRY_ESNEXT */ if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_X) { context_p->token.extra_value = LEXER_NUMBER_HEXADECIMAL; source_p += 2; if (source_p >= source_end_p || !lit_char_is_hex_digit (source_p[0])) { parser_raise_error (context_p, PARSER_ERR_INVALID_HEX_DIGIT); } do { source_p++; #if JERRY_ESNEXT if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE) { source_p++; if (source_p == source_end_p || !lit_char_is_hex_digit (source_p[0])) { parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER); } } #endif /* JERRY_ESNEXT */ } while (source_p < source_end_p && lit_char_is_hex_digit (source_p[0])); } #if JERRY_ESNEXT else if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_O) { context_p->token.extra_value = LEXER_NUMBER_OCTAL; source_p += 2; if (source_p >= source_end_p || !lit_char_is_octal_digit (source_p[0])) { parser_raise_error (context_p, PARSER_ERR_INVALID_OCTAL_DIGIT); } lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_7, false); } #endif /* JERRY_ESNEXT */ else if (source_p[1] >= LIT_CHAR_0 && source_p[1] <= LIT_CHAR_9) { context_p->token.extra_value = LEXER_NUMBER_OCTAL; #if JERRY_BUILTIN_BIGINT can_be_bigint = false; #endif /* JERRY_BUILTIN_BIGINT */ if (context_p->status_flags & PARSER_IS_STRICT) { parser_raise_error (context_p, PARSER_ERR_OCTAL_NUMBER_NOT_ALLOWED); } lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_7, true); if (source_p < source_end_p && source_p[0] >= LIT_CHAR_8 && source_p[0] <= LIT_CHAR_9) { #if JERRY_ESNEXT lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, true); context_p->token.extra_value = LEXER_NUMBER_DECIMAL; #else /* !JERRY_ESNEXT */ parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER); #endif /* JERRY_ESNEXT */ } } #if JERRY_ESNEXT else if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_B) { context_p->token.extra_value = LEXER_NUMBER_BINARY; source_p += 2; if (source_p >= source_end_p || !lit_char_is_binary_digit (source_p[0])) { parser_raise_error (context_p, PARSER_ERR_INVALID_BIN_DIGIT); } do { source_p++; if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE) { source_p++; if (source_p == source_end_p || source_p[0] > LIT_CHAR_9 || source_p[0] < LIT_CHAR_0) { parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER); } } } while (source_p < source_end_p && lit_char_is_binary_digit (source_p[0])); } #endif /* JERRY_ESNEXT */ else { can_be_float = true; source_p++; } } else { lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false); can_be_float = true; } if (can_be_float) { if (source_p < source_end_p && source_p[0] == LIT_CHAR_DOT) { source_p++; #if JERRY_BUILTIN_BIGINT can_be_bigint = false; #endif /* JERRY_BUILTIN_BIGINT */ #if JERRY_ESNEXT if (source_p < source_end_p && source_p[0] == LIT_CHAR_UNDERSCORE) { parser_raise_error (context_p, PARSER_ERR_INVALID_UNDERSCORE_IN_NUMBER); } #endif /* JERRY_ESNEXT */ lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false); } if (source_p < source_end_p && LEXER_TO_ASCII_LOWERCASE (source_p[0]) == LIT_CHAR_LOWERCASE_E) { source_p++; #if JERRY_BUILTIN_BIGINT can_be_bigint = false; #endif /* JERRY_BUILTIN_BIGINT */ if (source_p < source_end_p && (source_p[0] == LIT_CHAR_PLUS || source_p[0] == LIT_CHAR_MINUS)) { source_p++; } if (source_p >= source_end_p || source_p[0] < LIT_CHAR_0 || source_p[0] > LIT_CHAR_9) { parser_raise_error (context_p, PARSER_ERR_MISSING_EXPONENT); } lexer_check_numbers (context_p, &source_p, source_end_p, LIT_CHAR_9, false); } } #if JERRY_BUILTIN_BIGINT if (source_p < source_end_p && source_p[0] == LIT_CHAR_LOWERCASE_N) { if (!can_be_bigint) { parser_raise_error (context_p, PARSER_ERR_INVALID_BIGINT); } context_p->token.extra_value = LEXER_NUMBER_BIGINT; source_p++; } #endif /* JERRY_BUILTIN_BIGINT */ length = (size_t) (source_p - context_p->source_p); if (length > PARSER_MAXIMUM_STRING_LENGTH) { parser_raise_error (context_p, PARSER_ERR_NUMBER_TOO_LONG); } context_p->token.lit_location.length = (prop_length_t) length; PARSER_PLUS_EQUAL_LC (context_p->column, length); context_p->source_p = source_p; if (source_p < source_end_p && lexer_parse_identifier (context_p, LEXER_PARSE_CHECK_START_AND_RETURN)) { parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_AFTER_NUMBER); } } /* lexer_parse_number */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691) Ascii string length is no longer computed during string allocation. JerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parser_parse_export_statement (parser_context_t *context_p) /**< context */ { JERRY_ASSERT (context_p->token.type == LEXER_KEYW_EXPORT); JERRY_ASSERT (context_p->module_names_p == NULL); parser_module_check_request_place (context_p); bool consume_last_statement = false; lexer_next_token (context_p); switch (context_p->token.type) { case LEXER_KEYW_DEFAULT: { scanner_location_t location; scanner_get_location (&location, context_p); context_p->status_flags |= PARSER_MODULE_STORE_IDENT; lexer_next_token (context_p); if (context_p->token.type == LEXER_LITERAL && lexer_token_is_async (context_p) && context_p->next_scanner_info_p->source_p == context_p->source_p && context_p->next_scanner_info_p->type == SCANNER_TYPE_FUNCTION) { lexer_next_token (context_p); } if (context_p->token.type == LEXER_KEYW_CLASS) { context_p->status_flags |= PARSER_MODULE_DEFAULT_CLASS_OR_FUNC; parser_parse_class (context_p, true); consume_last_statement = true; } else if (context_p->token.type == LEXER_KEYW_FUNCTION) { context_p->status_flags |= PARSER_MODULE_DEFAULT_CLASS_OR_FUNC; parser_parse_function_statement (context_p); consume_last_statement = true; } else { /* Assignment expression */ scanner_set_location (context_p, &location); /* 15.2.3.5 Use the synthetic name '*default*' as the identifier. */ lexer_construct_literal_object (context_p, &lexer_default_literal, lexer_default_literal.type); context_p->token.lit_location.type = LEXER_IDENT_LITERAL; parser_emit_cbc_literal_from_token (context_p, CBC_PUSH_LITERAL); /* Do not overwrite this identifier. */ context_p->status_flags &= (uint32_t) ~PARSER_MODULE_STORE_IDENT; context_p->module_identifier_lit_p = context_p->lit_object.literal_p; /* Fake an assignment to the default identifier */ context_p->token.type = LEXER_ASSIGN; parser_parse_expression_statement (context_p, PARSE_EXPR_NO_COMMA | PARSE_EXPR_HAS_LITERAL); } ecma_string_t *name_p = ecma_new_ecma_string_from_utf8 (context_p->module_identifier_lit_p->u.char_p, context_p->module_identifier_lit_p->prop.length); ecma_string_t *export_name_p = ecma_get_magic_string (LIT_MAGIC_STRING_DEFAULT); if (parser_module_check_duplicate_export (context_p, export_name_p)) { ecma_deref_ecma_string (name_p); ecma_deref_ecma_string (export_name_p); parser_raise_error (context_p, PARSER_ERR_DUPLICATED_EXPORT_IDENTIFIER); } parser_module_add_names_to_node (context_p, export_name_p, name_p); ecma_deref_ecma_string (name_p); ecma_deref_ecma_string (export_name_p); break; } case LEXER_MULTIPLY: { lexer_next_token (context_p); ecma_module_node_t **target_node_list_p = &(JERRY_CONTEXT (module_current_p)->star_exports_p); if (lexer_token_is_identifier (context_p, "as", 2)) { target_node_list_p = &(JERRY_CONTEXT (module_current_p)->indirect_exports_p); lexer_next_token (context_p); if (context_p->token.type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL) { parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_EXPECTED); } lexer_construct_literal_object (context_p, &context_p->token.lit_location, LEXER_NEW_IDENT_LITERAL); lexer_literal_t *literal_p = PARSER_GET_LITERAL (context_p->lit_object.index); ecma_string_t *export_name_p = ecma_new_ecma_string_from_utf8 (literal_p->u.char_p, literal_p->prop.length); if (parser_module_check_duplicate_export (context_p, export_name_p)) { ecma_deref_ecma_string (export_name_p); parser_raise_error (context_p, PARSER_ERR_DUPLICATED_EXPORT_IDENTIFIER); } ecma_string_t *local_name_p = ecma_get_magic_string (LIT_MAGIC_STRING_ASTERIX_CHAR); parser_module_add_names_to_node (context_p, export_name_p, local_name_p); ecma_deref_ecma_string (export_name_p); lexer_next_token (context_p); } if (!lexer_token_is_identifier (context_p, "from", 4)) { parser_raise_error (context_p, PARSER_ERR_FROM_EXPECTED); } lexer_next_token (context_p); parser_module_handle_module_specifier (context_p, target_node_list_p); return false; } case LEXER_KEYW_VAR: case LEXER_KEYW_LET: case LEXER_KEYW_CONST: { context_p->status_flags |= PARSER_MODULE_STORE_IDENT; parser_parse_var_statement (context_p); break; } case LEXER_KEYW_CLASS: { context_p->status_flags |= PARSER_MODULE_STORE_IDENT; parser_parse_class (context_p, true); consume_last_statement = true; break; } case LEXER_KEYW_FUNCTION: { context_p->status_flags |= PARSER_MODULE_STORE_IDENT; parser_parse_function_statement (context_p); consume_last_statement = true; break; } case LEXER_LEFT_BRACE: { parser_module_parse_export_clause (context_p); if (lexer_token_is_identifier (context_p, "from", 4)) { lexer_next_token (context_p); parser_module_handle_module_specifier (context_p, &(JERRY_CONTEXT (module_current_p)->indirect_exports_p)); return false; } break; } default: { parser_raise_error (context_p, PARSER_ERR_LEFT_BRACE_MULTIPLY_LITERAL_EXPECTED); break; } } context_p->status_flags &= (uint32_t) ~(PARSER_MODULE_DEFAULT_CLASS_OR_FUNC | PARSER_MODULE_STORE_IDENT); parser_module_append_names (context_p, &(JERRY_CONTEXT (module_current_p)->local_exports_p)); return consume_last_statement; } /* parser_parse_export_statement */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691) Ascii string length is no longer computed during string allocation. JerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* context) override { // Only create one, if one does not exist already. Report status for all // other exceptions. If one already exists, it unrefs the new one. // An epsilon value of zero could cause performance issues and is therefore, // disallowed. const Tensor* epsilon_t; OP_REQUIRES_OK(context, context->input(kEpsilonName, &epsilon_t)); float epsilon = epsilon_t->scalar<float>()(); OP_REQUIRES( context, epsilon > 0, errors::InvalidArgument("An epsilon value of zero is not allowed.")); const Tensor* num_streams_t; OP_REQUIRES_OK(context, context->input(kNumStreamsName, &num_streams_t)); int64_t num_streams = num_streams_t->scalar<int64>()(); auto result = new QuantileStreamResource(epsilon, max_elements_, num_streams); auto status = CreateResource(context, HandleFromInput(context, 0), result); if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) { OP_REQUIRES(context, false, status); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-681'], 'message': 'Ensure num_streams >= 0 in tf.raw_ops.BoostedTreesCreateQuantileStreamResource PiperOrigin-RevId: 387452765 Change-Id: I9990c760e177fabca6a3b9b4612ceeaeeba51495'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status AutoParallel::Initialize(const GrapplerItem& item) { num_gpus_ = GetNumAvailableGPUs(); LOG(INFO) << "Number of GPUs: " << num_gpus_; item_ = &item; graph_ = item.graph; LOG(INFO) << "Original graph size: " << graph_.node_size(); if (item.fetch.empty()) { return Status(error::INVALID_ARGUMENT, "No fetch nodes provided."); } if (item.MainVariables().empty()) { return Status(error::INVALID_ARGUMENT, "No variables provided."); } for (const auto& init : item.init_ops) { VLOG(1) << "Init node: " << init; } for (const auto& fetch : item.fetch) { VLOG(1) << "Fetch node: " << fetch; } for (const auto& var : item.MainVariables()) { VLOG(2) << "Variable: " << var->name(); } const std::set<string> apply_gradients_ops = {"ApplyGradientDescent", "ApplyProximalGradientDescent", "ApplyAdadelta", "ApplyAdagrad", "ApplyProximalAdagrad", "ApplyAdagradDA", "ApplyFtrl", "ApplyMomentum", "ApplyAdam", "ApplyRMSProp", "ApplyCenteredRMSProp"}; for (int i = 0; i < graph_.node_size(); i++) { all_nodes_.insert( std::make_pair(graph_.node(i).name(), graph_.mutable_node(i))); if (apply_gradients_ops.find(graph_.node(i).op()) != apply_gradients_ops.end()) { apply_gradients_nodes_.insert(graph_.node(i).name()); VLOG(2) << "Apply gradients node: " << graph_.node(i).name(); } } auto div_const_node = AddNodeDivConst(); all_nodes_.insert(std::make_pair(div_const_node->name(), div_const_node)); std::map<string, int> gradient_pos = {{"ApplyGradientDescent", 2}, {"ApplyProximalGradientDescent", 4}, {"ApplyAdadelta", 6}, {"ApplyAdagrad", 3}, {"ApplyProximalAdagrad", 5}, {"ApplyAdagradDA", 3}, {"ApplyFtrl", 3}, {"ApplyMomentum", 3}, {"ApplyAdam", 9}, {"ApplyRMSProp", 7}, {"ApplyCenteredRMSProp", 8}}; for (const auto& apply_gradient_node_name : apply_gradients_nodes_) { auto apply_gradients_op = all_nodes_[apply_gradient_node_name]->op(); auto apply_gradients_node = all_nodes_[apply_gradient_node_name]; auto div_node = AddNodeDiv( apply_gradient_node_name, apply_gradients_node->input(gradient_pos[apply_gradients_op]), div_const_node->name()); all_nodes_.insert(std::make_pair(div_node->name(), div_node)); *apply_gradients_node->mutable_input(gradient_pos[apply_gradients_op]) = div_node->name(); } LOG(INFO) << "Graph size after adding div nodes: " << all_nodes_.size(); std::vector<const NodeDef*> train_nodes; TF_RETURN_IF_ERROR(ComputeTransitiveFanin(graph_, item.fetch, &train_nodes)); LOG(INFO) << "Number of training nodes: " << train_nodes.size(); const NodeDef* dequeue_node; for (const auto& train_node : train_nodes) { if (IsDequeueOp(*train_node)) { dequeue_node = train_node; break; } } std::vector<const NodeDef*> input_nodes; if (dequeue_node) { LOG(INFO) << "Dequeue node: " << dequeue_node->name(); TF_RETURN_IF_ERROR(ComputeTransitiveFanin(graph_, {dequeue_node->name()}, {}, &input_nodes)); } LOG(INFO) << "Number of input nodes: " << input_nodes.size(); std::set<string> dont_replicate_nodes; for (const auto& variable : item.MainVariables()) { dont_replicate_nodes.insert(variable->name()); } for (const auto& init : item.init_ops) { dont_replicate_nodes.insert(NodeName(init)); } // Don't replicate all input nodes, except the dequeue node. for (const auto& input_node : input_nodes) { if (input_node->name() != dequeue_node->name()) { dont_replicate_nodes.insert(input_node->name()); } } for (const auto& node : train_nodes) { if (dont_replicate_nodes.find(node->name()) == dont_replicate_nodes.end()) { replica_nodes_.insert(node->name()); } } LOG(INFO) << "Number of replica nodes: " << replica_nodes_.size(); for (const auto& node : all_nodes_) { if (replica_nodes_.find(node.first) == replica_nodes_.end()) { shared_nodes_.insert(node.first); } } LOG(INFO) << "Number of shared nodes: " << shared_nodes_.size(); return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-908'], 'message': 'Prevent unitialized variable use in grappler. PiperOrigin-RevId: 399702928 Change-Id: Id7e75451fbff297692dfb687f60ea04b25c96b24'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QInt8() {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-908', 'CWE-787'], 'message': 'Default initialize fixed point Eigen types. In certain cases, tensors are filled with default values of the type. But, for these fixed point types, these values were uninitialized. Thus, we would have uninitialized memory access bugs, some of which were caught by MSAN. PiperOrigin-RevId: 344101137 Change-Id: I14555fda74dca3b5f1582da9008901937e3f14e2'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond) { PurpleXfer *xfer = data; struct im_connection *ic = purple_ic_by_pa(xfer->account); struct prpl_xfer_data *px = xfer->ui_data; PurpleBuddy *buddy; const char *who; buddy = purple_find_buddy(xfer->account, xfer->who); who = buddy ? purple_buddy_get_name(buddy) : xfer->who; /* TODO(wilmer): After spreading some more const goodness in BitlBee, remove the evil cast below. */ px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size); px->ft->data = px; px->ft->accept = prpl_xfer_accept; px->ft->canceled = prpl_xfer_canceled; px->ft->free = prpl_xfer_free; px->ft->write_request = prpl_xfer_write_request; return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'purple: Fix crash on ft requests from unknown contacts Followup to 701ab81 (included in 3.5) which was a partial fix which only improved things for non-libpurple file transfers (that is, just jabber)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: hb_set_union (hb_set_t *set, const hb_set_t *other) { if (unlikely (hb_object_is_immutable (set))) return; set->union_ (*other); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': '[set] Make all operators null-safe again Changed my mind. Also for hb_map_clear(). Part of https://github.com/harfbuzz/harfbuzz/pull/3162'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SYSCALL_DEFINE2(osf_getdomainname, char __user *, name, int, namelen) { unsigned len; int i; if (!access_ok(VERIFY_WRITE, name, namelen)) return -EFAULT; len = namelen; if (namelen > 32) len = 32; down_read(&uts_sem); for (i = 0; i < len; ++i) { __put_user(utsname()->domainname[i], name + i); if (utsname()->domainname[i] == '\0') break; } up_read(&uts_sem); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-264', 'CWE-189'], 'message': 'alpha: fix several security issues Fix several security issues in Alpha-specific syscalls. Untested, but mostly trivial. 1. Signedness issue in osf_getdomainname allows copying out-of-bounds kernel memory to userland. 2. Signedness issue in osf_sysinfo allows copying large amounts of kernel memory to userland. 3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy size, allowing copying large amounts of kernel memory to userland. 4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows privilege escalation via writing return value of sys_wait4 to kernel memory. Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Cc: Richard Henderson <rth@twiddle.net> Cc: Ivan Kokshaysky <ink@jurassic.park.msu.ru> Cc: Matt Turner <mattst88@gmail.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ActiveStreamEncoderFilter::responseDataTooLarge() { if (parent_.state_.encoder_filters_streaming_) { onEncoderFilterAboveWriteBufferHighWatermark(); } else { parent_.filter_manager_callbacks_.onResponseDataTooLarge(); // In this case, sendLocalReply will either send a response directly to the encoder, or // reset the stream. parent_.sendLocalReply( Http::Code::InternalServerError, CodeUtility::toString(Http::Code::InternalServerError), nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().ResponsePayloadTooLarge); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'CVE-2021-43825 Response filter manager crash Signed-off-by: Yan Avlasov <yavlasov@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool WindowsServiceControl::install( const QString& filePath, const QString& displayName ) { m_serviceHandle = CreateService( m_serviceManager, // SCManager database WindowsCoreFunctions::toConstWCharArray( m_name ), // name of service WindowsCoreFunctions::toConstWCharArray( displayName ),// name to display SERVICE_ALL_ACCESS, // desired access SERVICE_WIN32_OWN_PROCESS, // service type SERVICE_AUTO_START, // start type SERVICE_ERROR_NORMAL, // error control type WindowsCoreFunctions::toConstWCharArray( filePath ), // service's binary nullptr, // no load ordering group nullptr, // no tag identifier L"Tcpip\0RpcSs\0\0", // dependencies nullptr, // LocalSystem account nullptr ); // no password if( m_serviceHandle == nullptr ) { const auto error = GetLastError(); if( error == ERROR_SERVICE_EXISTS ) { vCritical() << qUtf8Printable( tr( "The service \"%1\" is already installed." ).arg( m_name ) ); } else { vCritical() << qUtf8Printable( tr( "The service \"%1\" could not be installed." ).arg( m_name ) ); } return false; } SC_ACTION serviceActions; serviceActions.Delay = 10000; serviceActions.Type = SC_ACTION_RESTART; SERVICE_FAILURE_ACTIONS serviceFailureActions; serviceFailureActions.dwResetPeriod = 0; serviceFailureActions.lpRebootMsg = nullptr; serviceFailureActions.lpCommand = nullptr; serviceFailureActions.lpsaActions = &serviceActions; serviceFailureActions.cActions = 1; ChangeServiceConfig2( m_serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, &serviceFailureActions ); // Everything went fine vInfo() << qUtf8Printable( tr( "The service \"%1\" has been installed successfully." ).arg( m_name ) ); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-428', 'CWE-295'], 'message': 'WindowsServiceControl: quote service binary path Fix unquoted service path vulnerability. Closes #657.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg) { __be32 *p; /* * opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4, * owner 4 = 32 */ RESERVE_SPACE(8); WRITE32(OP_OPEN); WRITE32(arg->seqid->sequence->counter); encode_share_access(xdr, arg->open_flags); RESERVE_SPACE(28); WRITE64(arg->clientid); WRITE32(16); WRITEMEM("open id:", 8); WRITE64(arg->id); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void nfs4_close_sync(struct path *path, struct nfs4_state *state, mode_t mode) { __nfs4_close(path, state, mode, 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags) { /* * Protect the call to nfs4_state_set_mode_locked and * serialise the stateid update */ write_seqlock(&state->seqlock); if (deleg_stateid != NULL) { memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data)); set_bit(NFS_DELEGATED_STATE, &state->flags); } if (open_stateid != NULL) nfs_set_open_stateid_locked(state, open_stateid, open_flags); write_sequnlock(&state->seqlock); spin_lock(&state->owner->so_lock); update_open_stateflags(state, open_flags); spin_unlock(&state->owner->so_lock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int wc_SignatureGenerateHash( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* hash_data, word32 hash_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng) { int ret; /* Suppress possible unused arg if all signature types are disabled */ (void)rng; /* Check arguments */ if (hash_data == NULL || hash_len <= 0 || sig == NULL || sig_len == NULL || *sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (needs to be at least max) */ if ((int)*sig_len < wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid hash type/len"); return ret; } ret = 0; /* Create signature using hash as data */ switch (sig_type) { case WC_SIGNATURE_TYPE_ECC: #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN) /* Create signature using provided ECC key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((ecc_key*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_ecc_sign_hash(hash_data, hash_len, sig, sig_len, rng, (ecc_key*)key); } while (ret == WC_PENDING_E); #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) /* Create signature using provided RSA key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((RsaKey*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_RsaSSL_Sign(hash_data, hash_len, sig, *sig_len, (RsaKey*)key, rng); } while (ret == WC_PENDING_E); if (ret >= 0) { *sig_len = ret; ret = 0; /* Success */ } #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_NONE: default: ret = BAD_FUNC_ARG; break; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-327', 'CWE-347'], 'message': 'Change signature generation to verify by default'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmGlobalEntry *ptr = NULL; int buflen = bin->buf->length; if (sec->payload_data + 32 > buflen) { return NULL; } if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) { return ret; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) { goto beach; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) { goto beach; } if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } r_list_append (ret, ptr); r++; } return ret; beach: free (ptr); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix crash in fuzzed wasm r2_hoobr_consume_init_expr'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void FrameFactory::rebuildAggregateFrames(ID3v2::Tag *tag) const { if(tag->header()->majorVersion() < 4 && tag->frameList("TDRC").size() == 1 && tag->frameList("TDAT").size() == 1) { TextIdentificationFrame *tdrc = static_cast<TextIdentificationFrame *>(tag->frameList("TDRC").front()); UnknownFrame *tdat = static_cast<UnknownFrame *>(tag->frameList("TDAT").front()); if(tdrc->fieldList().size() == 1 && tdrc->fieldList().front().size() == 4 && tdat->data().size() >= 5) { String date(tdat->data().mid(1), String::Type(tdat->data()[0])); if(date.length() == 4) { tdrc->setText(tdrc->toString() + '-' + date.substr(2, 2) + '-' + date.substr(0, 2)); if(tag->frameList("TIME").size() == 1) { UnknownFrame *timeframe = static_cast<UnknownFrame *>(tag->frameList("TIME").front()); if(timeframe->data().size() >= 5) { String time(timeframe->data().mid(1), String::Type(timeframe->data()[0])); if(time.length() == 4) { tdrc->setText(tdrc->toString() + 'T' + time.substr(0, 2) + ':' + time.substr(2, 2)); } } } } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-434', 'CWE-352'], 'message': 'Don't assume TDRC is an instance of TextIdentificationFrame (#831) If TDRC is encrypted, FrameFactory::createFrame() returns UnknownFrame which causes problems in rebuildAggregateFrames() when it is assumed that TDRC is a TextIdentificationFrame'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: LIBOPENMPT_MODPLUG_API unsigned int ModPlug_SampleName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_sample_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-295'], 'message': '[Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team) git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CreateForeignServer(CreateForeignServerStmt *stmt) { Relation rel; Datum srvoptions; Datum values[Natts_pg_foreign_server]; bool nulls[Natts_pg_foreign_server]; HeapTuple tuple; Oid srvId; Oid ownerId; AclResult aclresult; ObjectAddress myself; ObjectAddress referenced; ForeignDataWrapper *fdw; rel = table_open(ForeignServerRelationId, RowExclusiveLock); /* For now the owner cannot be specified on create. Use effective user ID. */ ownerId = GetUserId(); /* * Check that there is no other foreign server by this name. Do nothing if * IF NOT EXISTS was enforced. */ if (GetForeignServerByName(stmt->servername, true) != NULL) { if (stmt->if_not_exists) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("server \"%s\" already exists, skipping", stmt->servername))); table_close(rel, RowExclusiveLock); return InvalidObjectAddress; } else ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("server \"%s\" already exists", stmt->servername))); } /* * Check that the FDW exists and that we have USAGE on it. Also get the * actual FDW for option validation etc. */ fdw = GetForeignDataWrapperByName(stmt->fdwname, false); aclresult = pg_foreign_data_wrapper_aclcheck(fdw->fdwid, ownerId, ACL_USAGE); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, OBJECT_FDW, fdw->fdwname); /* * Insert tuple into pg_foreign_server. */ memset(values, 0, sizeof(values)); memset(nulls, false, sizeof(nulls)); srvId = GetNewOidWithIndex(rel, ForeignServerOidIndexId, Anum_pg_foreign_server_oid); values[Anum_pg_foreign_server_oid - 1] = ObjectIdGetDatum(srvId); values[Anum_pg_foreign_server_srvname - 1] = DirectFunctionCall1(namein, CStringGetDatum(stmt->servername)); values[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId); values[Anum_pg_foreign_server_srvfdw - 1] = ObjectIdGetDatum(fdw->fdwid); /* Add server type if supplied */ if (stmt->servertype) values[Anum_pg_foreign_server_srvtype - 1] = CStringGetTextDatum(stmt->servertype); else nulls[Anum_pg_foreign_server_srvtype - 1] = true; /* Add server version if supplied */ if (stmt->version) values[Anum_pg_foreign_server_srvversion - 1] = CStringGetTextDatum(stmt->version); else nulls[Anum_pg_foreign_server_srvversion - 1] = true; /* Start with a blank acl */ nulls[Anum_pg_foreign_server_srvacl - 1] = true; /* Add server options */ srvoptions = transformGenericOptions(ForeignServerRelationId, PointerGetDatum(NULL), stmt->options, fdw->fdwvalidator); if (PointerIsValid(DatumGetPointer(srvoptions))) values[Anum_pg_foreign_server_srvoptions - 1] = srvoptions; else nulls[Anum_pg_foreign_server_srvoptions - 1] = true; tuple = heap_form_tuple(rel->rd_att, values, nulls); CatalogTupleInsert(rel, tuple); heap_freetuple(tuple); /* record dependencies */ myself.classId = ForeignServerRelationId; myself.objectId = srvId; myself.objectSubId = 0; referenced.classId = ForeignDataWrapperRelationId; referenced.objectId = fdw->fdwid; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); recordDependencyOnOwner(ForeignServerRelationId, srvId, ownerId); /* dependency on extension */ recordDependencyOnCurrentExtension(&myself, false); /* Post creation hook for new foreign server */ InvokeObjectPostCreateHook(ForeignServerRelationId, srvId, 0); table_close(rel, RowExclusiveLock); return myself; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension. Previously, if an extension script did CREATE OR REPLACE and there was an existing object not belonging to the extension, it would overwrite the object and adopt it into the extension. This is problematic, first because the overwrite is probably unintentional, and second because we didn't change the object's ownership. Thus a hostile user could create an object in advance of an expected CREATE EXTENSION command, and would then have ownership rights on an extension object, which could be modified for trojan-horse-type attacks. Hence, forbid CREATE OR REPLACE of an existing object unless it already belongs to the extension. (Note that we've always forbidden replacing an object that belongs to some other extension; only the behavior for previously-free-standing objects changes here.) For the same reason, also fail CREATE IF NOT EXISTS when there is an existing object that doesn't belong to the extension. Our thanks to Sven Klemm for reporting this problem. Security: CVE-2022-2625'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: aperture_report(gerbv_aperture_t *apertures[], int aperture_num, double x, double y, gerbv_image_t *img, gerbv_project_t *prj) { gerbv_aperture_type_t type = apertures[aperture_num]->type; double *params = apertures[aperture_num]->parameter; gerbv_simplified_amacro_t *sim = apertures[aperture_num]->simplified; double *simpars = sim->parameter; g_message (_(" Aperture used: D%d"), aperture_num); g_message (_(" Aperture type: %s"), (type == GERBV_APTYPE_MACRO)? _(gerbv_aperture_type_name(sim->type)): _(gerbv_aperture_type_name(type))); switch (type) { case GERBV_APTYPE_CIRCLE: g_message (_(" Diameter: %g %s"), screen_units(params[0]), screen_units_str()); break; case GERBV_APTYPE_RECTANGLE: case GERBV_APTYPE_OVAL: g_message (_(" Dimensions: %gx%g %s"), screen_units(params[0]), screen_units(params[1]), screen_units_str()); break; case GERBV_APTYPE_MACRO: { switch (sim->type) { case GERBV_APTYPE_MACRO_CIRCLE: g_message (_(" Diameter: %g %s"), screen_units(simpars[CIRCLE_DIAMETER]), screen_units_str()); x += simpars[CIRCLE_CENTER_X]; y += simpars[CIRCLE_CENTER_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); break; case GERBV_APTYPE_MACRO_OUTLINE: g_message (_(" Number of points: %g"), simpars[OUTLINE_NUMBER_OF_POINTS]); x += simpars[OUTLINE_FIRST_X]; y += simpars[OUTLINE_FIRST_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Start: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); g_message (_(" Rotation: %g deg"), simpars[OUTLINE_ROTATION_IDX(simpars)]); break; case GERBV_APTYPE_MACRO_POLYGON: g_message (_(" Number of points: %g"), simpars[POLYGON_NUMBER_OF_POINTS]); g_message (_(" Diameter: %g %s"), screen_units(simpars[POLYGON_DIAMETER]), screen_units_str()); x += simpars[POLYGON_CENTER_X]; y += simpars[POLYGON_CENTER_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); g_message (_(" Rotation: %g deg"), simpars[POLYGON_ROTATION]); break; case GERBV_APTYPE_MACRO_MOIRE: g_message (_(" Outside diameter: %g %s"), screen_units(simpars[MOIRE_OUTSIDE_DIAMETER]), screen_units_str()); g_message (_(" Ring thickness: %g %s"), screen_units(simpars[MOIRE_CIRCLE_THICKNESS]), screen_units_str()); g_message (_(" Gap width: %g %s"), screen_units(simpars[MOIRE_GAP_WIDTH]), screen_units_str()); g_message (_(" Number of rings: %g"), simpars[MOIRE_NUMBER_OF_CIRCLES]); g_message (_(" Crosshair thickness: %g %s"), screen_units( simpars[MOIRE_CROSSHAIR_THICKNESS]), screen_units_str()); g_message (_(" Crosshair length: %g %s"), screen_units(simpars[MOIRE_CROSSHAIR_LENGTH]), screen_units_str()); x += simpars[MOIRE_CENTER_X]; y += simpars[MOIRE_CENTER_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); g_message (_(" Rotation: %g deg"), simpars[MOIRE_ROTATION]); break; case GERBV_APTYPE_MACRO_THERMAL: g_message (_(" Outside diameter: %g %s"), screen_units(simpars[THERMAL_OUTSIDE_DIAMETER]), screen_units_str()); g_message (_(" Inside diameter: %g %s"), screen_units(simpars[THERMAL_INSIDE_DIAMETER]), screen_units_str()); g_message (_(" Crosshair thickness: %g %s"), screen_units( simpars[THERMAL_CROSSHAIR_THICKNESS]), screen_units_str()); x += simpars[THERMAL_CENTER_X]; y += simpars[THERMAL_CENTER_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); g_message (_(" Rotation: %g deg"), simpars[THERMAL_ROTATION]); break; case GERBV_APTYPE_MACRO_LINE20: g_message (_(" Width: %g %s"), screen_units(simpars[LINE20_WIDTH]), screen_units_str()); x += simpars[LINE20_START_X]; y += simpars[LINE20_START_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Start: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); x += simpars[LINE20_END_X]; y += simpars[LINE20_END_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Stop: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); g_message (_(" Rotation: %g deg"), simpars[LINE20_ROTATION]); break; case GERBV_APTYPE_MACRO_LINE21: g_message (_(" Width: %g %s"), screen_units(simpars[LINE21_WIDTH]), screen_units_str()); g_message (_(" Height: %g %s"), screen_units(simpars[LINE21_HEIGHT]), screen_units_str()); x += simpars[LINE21_CENTER_X]; y += simpars[LINE21_CENTER_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); g_message (_(" Rotation: %g deg"), simpars[LINE21_ROTATION]); break; case GERBV_APTYPE_MACRO_LINE22: g_message (_(" Width: %g %s"), screen_units(simpars[LINE22_WIDTH]), screen_units_str()); g_message (_(" Height: %g %s"), screen_units(simpars[LINE22_HEIGHT]), screen_units_str()); x += simpars[LINE22_LOWER_LEFT_X]; y += simpars[LINE22_LOWER_LEFT_Y]; gerbv_transform_coord_for_image(&x, &y, img, prj); g_message (_(" Lower left: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()); g_message (_(" Rotation: %g deg"), simpars[LINE22_ROTATION]); break; default: break; } break; } default: break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Remove local alias to parameter array Normalizing access to `gerbv_simplified_amacro_t::parameter` as a step to fix CVE-2021-40402'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bit_write_MC (Bit_Chain *dat, BITCODE_MC val) { int i, j; int negative = 0; unsigned char byte[5]; BITCODE_UMC mask = 0x0000007f; BITCODE_UMC value = (BITCODE_UMC)val; if (val < 0) { negative = 1; value = (BITCODE_UMC)-val; } for (i = 4, j = 0; i >= 0; i--, j += 7) { byte[i] = (unsigned char)((value & mask) >> j); byte[i] |= 0x80; mask = mask << 7; } for (i = 0; i < 4; i++) if (byte[i] & 0x7f) break; if (byte[i] & 0x40) i--; byte[i] &= 0x7f; if (negative) byte[i] |= 0x40; for (j = 4; j >= i; j--) bit_write_RC (dat, byte[j]); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'encode: protect from stack under-flow From GH #178 fuzzing'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int snd_ctl_tlv_ioctl(struct snd_ctl_file *file, struct snd_ctl_tlv __user *_tlv, int op_flag) { struct snd_card *card = file->card; struct snd_ctl_tlv tlv; struct snd_kcontrol *kctl; struct snd_kcontrol_volatile *vd; unsigned int len; int err = 0; if (copy_from_user(&tlv, _tlv, sizeof(tlv))) return -EFAULT; if (tlv.length < sizeof(unsigned int) * 2) return -EINVAL; down_read(&card->controls_rwsem); kctl = snd_ctl_find_numid(card, tlv.numid); if (kctl == NULL) { err = -ENOENT; goto __kctl_end; } if (kctl->tlv.p == NULL) { err = -ENXIO; goto __kctl_end; } vd = &kctl->vd[tlv.numid - kctl->id.numid]; if ((op_flag == 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_READ) == 0) || (op_flag > 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE) == 0) || (op_flag < 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND) == 0)) { err = -ENXIO; goto __kctl_end; } if (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) { if (vd->owner != NULL && vd->owner != file) { err = -EPERM; goto __kctl_end; } err = kctl->tlv.c(kctl, op_flag, tlv.length, _tlv->tlv); if (err > 0) { up_read(&card->controls_rwsem); snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_TLV, &kctl->id); return 0; } } else { if (op_flag) { err = -ENXIO; goto __kctl_end; } len = kctl->tlv.p[1] + 2 * sizeof(unsigned int); if (tlv.length < len) { err = -ENOMEM; goto __kctl_end; } if (copy_to_user(_tlv->tlv, kctl->tlv.p, len)) err = -EFAULT; } __kctl_end: up_read(&card->controls_rwsem); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-415'], 'message': 'ALSA: control: Don't access controls outside of protected regions A control that is visible on the card->controls list can be freed at any time. This means we must not access any of its memory while not holding the controls_rw_lock. Otherwise we risk a use after free access. Signed-off-by: Lars-Peter Clausen <lars@metafoo.de> Acked-by: Jaroslav Kysela <perex@perex.cz> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadSCREENSHOTImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=(Image *) NULL; #if defined(MAGICKCORE_WINGDI32_DELEGATE) { BITMAPINFO bmi; DISPLAY_DEVICE device; HBITMAP bitmap, bitmapOld; HDC bitmapDC, hDC; Image *screen; int i; MagickBooleanType status; register Quantum *q; register ssize_t x; RGBTRIPLE *p; ssize_t y; assert(image_info != (const ImageInfo *) NULL); i=0; device.cb = sizeof(device); image=(Image *) NULL; while(EnumDisplayDevices(NULL,i,&device,0) && ++i) { if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE) continue; hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL); if (hDC == (HDC) NULL) ThrowReaderException(CoderError,"UnableToCreateDC"); screen=AcquireImage(image_info,exception); screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES); screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES); screen->storage_class=DirectClass; status=SetImageExtent(screen,screen->columns,screen->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image == (Image *) NULL) image=screen; else AppendImageToList(&image,screen); bitmapDC=CreateCompatibleDC(hDC); if (bitmapDC == (HDC) NULL) { DeleteDC(hDC); ThrowReaderException(CoderError,"UnableToCreateDC"); } (void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO)); bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth=(LONG) screen->columns; bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows; bmi.bmiHeader.biPlanes=1; bmi.bmiHeader.biBitCount=24; bmi.bmiHeader.biCompression=BI_RGB; bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0); if (bitmap == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap); if (bitmapOld == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0, SRCCOPY); (void) SelectObject(bitmapDC,bitmapOld); for (y=0; y < (ssize_t) screen->rows; y++) { q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) screen->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(p->rgbtRed),q); SetPixelGreen(image,ScaleCharToQuantum(p->rgbtGreen),q); SetPixelBlue(image,ScaleCharToQuantum(p->rgbtBlue),q); SetPixelAlpha(image,OpaqueAlpha,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(screen,exception) == MagickFalse) break; } DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); } } #elif defined(MAGICKCORE_X11_DELEGATE) { const char *option; XImportInfo ximage_info; XGetImportInfo(&ximage_info); option=GetImageOption(image_info,"x:screen"); if (option != (const char *) NULL) ximage_info.screen=IsStringTrue(option); option=GetImageOption(image_info,"x:silent"); if (option != (const char *) NULL) ximage_info.silent=IsStringTrue(option); image=XImportImage(image_info,&ximage_info,exception); } #endif return(image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'Fixed potential memory leak.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ip6_append_data_mtu(int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (skb == NULL) { /* first fragment, reserve header_len */ *mtu = *mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = dst_mtu(rt->dst.path); } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'ipv6: ip6_append_data_mtu did not care about pmtudisc and frag_size If the socket had an IPV6_MTU value set, ip6_append_data_mtu lost track of this when appending the second frame on a corked socket. This results in the following splat: [37598.993962] ------------[ cut here ]------------ [37598.994008] kernel BUG at net/core/skbuff.c:2064! [37598.994008] invalid opcode: 0000 [#1] SMP [37598.994008] Modules linked in: tcp_lp uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_core videodev media vfat fat usb_storage fuse ebtable_nat xt_CHECKSUM bridge stp llc ipt_MASQUERADE nf_conntrack_netbios_ns nf_conntrack_broadcast ip6table_mangle ip6t_REJECT nf_conntrack_ipv6 nf_defrag_ipv6 iptable_nat +nf_nat_ipv4 nf_nat iptable_mangle nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ebtable_filter ebtables ip6table_filter ip6_tables be2iscsi iscsi_boot_sysfs bnx2i cnic uio cxgb4i cxgb4 cxgb3i cxgb3 mdio libcxgbi ib_iser rdma_cm ib_addr iw_cm ib_cm ib_sa ib_mad ib_core iscsi_tcp libiscsi_tcp libiscsi +scsi_transport_iscsi rfcomm bnep iTCO_wdt iTCO_vendor_support snd_hda_codec_conexant arc4 iwldvm mac80211 snd_hda_intel acpi_cpufreq mperf coretemp snd_hda_codec microcode cdc_wdm cdc_acm [37598.994008] snd_hwdep cdc_ether snd_seq snd_seq_device usbnet mii joydev btusb snd_pcm bluetooth i2c_i801 e1000e lpc_ich mfd_core ptp iwlwifi pps_core snd_page_alloc mei cfg80211 snd_timer thinkpad_acpi snd tpm_tis soundcore rfkill tpm tpm_bios vhost_net tun macvtap macvlan kvm_intel kvm uinput binfmt_misc +dm_crypt i915 i2c_algo_bit drm_kms_helper drm i2c_core wmi video [37598.994008] CPU 0 [37598.994008] Pid: 27320, comm: t2 Not tainted 3.9.6-200.fc18.x86_64 #1 LENOVO 27744PG/27744PG [37598.994008] RIP: 0010:[<ffffffff815443a5>] [<ffffffff815443a5>] skb_copy_and_csum_bits+0x325/0x330 [37598.994008] RSP: 0018:ffff88003670da18 EFLAGS: 00010202 [37598.994008] RAX: ffff88018105c018 RBX: 0000000000000004 RCX: 00000000000006c0 [37598.994008] RDX: ffff88018105a6c0 RSI: ffff88018105a000 RDI: ffff8801e1b0aa00 [37598.994008] RBP: ffff88003670da78 R08: 0000000000000000 R09: ffff88018105c040 [37598.994008] R10: ffff8801e1b0aa00 R11: 0000000000000000 R12: 000000000000fff8 [37598.994008] R13: 00000000000004fc R14: 00000000ffff0504 R15: 0000000000000000 [37598.994008] FS: 00007f28eea59740(0000) GS:ffff88023bc00000(0000) knlGS:0000000000000000 [37598.994008] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b [37598.994008] CR2: 0000003d935789e0 CR3: 00000000365cb000 CR4: 00000000000407f0 [37598.994008] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 [37598.994008] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 [37598.994008] Process t2 (pid: 27320, threadinfo ffff88003670c000, task ffff88022c162ee0) [37598.994008] Stack: [37598.994008] ffff88022e098a00 ffff88020f973fc0 0000000000000008 00000000000004c8 [37598.994008] ffff88020f973fc0 00000000000004c4 ffff88003670da78 ffff8801e1b0a200 [37598.994008] 0000000000000018 00000000000004c8 ffff88020f973fc0 00000000000004c4 [37598.994008] Call Trace: [37598.994008] [<ffffffff815fc21f>] ip6_append_data+0xccf/0xfe0 [37598.994008] [<ffffffff8158d9f0>] ? ip_copy_metadata+0x1a0/0x1a0 [37598.994008] [<ffffffff81661f66>] ? _raw_spin_lock_bh+0x16/0x40 [37598.994008] [<ffffffff8161548d>] udpv6_sendmsg+0x1ed/0xc10 [37598.994008] [<ffffffff812a2845>] ? sock_has_perm+0x75/0x90 [37598.994008] [<ffffffff815c3693>] inet_sendmsg+0x63/0xb0 [37598.994008] [<ffffffff812a2973>] ? selinux_socket_sendmsg+0x23/0x30 [37598.994008] [<ffffffff8153a450>] sock_sendmsg+0xb0/0xe0 [37598.994008] [<ffffffff810135d1>] ? __switch_to+0x181/0x4a0 [37598.994008] [<ffffffff8153d97d>] sys_sendto+0x12d/0x180 [37598.994008] [<ffffffff810dfb64>] ? __audit_syscall_entry+0x94/0xf0 [37598.994008] [<ffffffff81020ed1>] ? syscall_trace_enter+0x231/0x240 [37598.994008] [<ffffffff8166a7e7>] tracesys+0xdd/0xe2 [37598.994008] Code: fe 07 00 00 48 c7 c7 04 28 a6 81 89 45 a0 4c 89 4d b8 44 89 5d a8 e8 1b ac b1 ff 44 8b 5d a8 4c 8b 4d b8 8b 45 a0 e9 cf fe ff ff <0f> 0b 66 0f 1f 84 00 00 00 00 00 66 66 66 66 90 55 48 89 e5 48 [37598.994008] RIP [<ffffffff815443a5>] skb_copy_and_csum_bits+0x325/0x330 [37598.994008] RSP <ffff88003670da18> [37599.007323] ---[ end trace d69f6a17f8ac8eee ]--- While there, also check if path mtu discovery is activated for this socket. The logic was adapted from ip6_append_data when first writing on the corked socket. This bug was introduced with commit 0c1833797a5a6ec23ea9261d979aa18078720b74 ("ipv6: fix incorrect ipsec fragment"). v2: a) Replace IPV6_PMTU_DISC_DO with IPV6_PMTUDISC_PROBE. b) Don't pass ipv6_pinfo to ip6_append_data_mtu (suggestion by Gao feng, thanks!). c) Change mtu to unsigned int, else we get a warning about non-matching types because of the min()-macro type-check. Acked-by: Gao feng <gaofeng@cn.fujitsu.com> Cc: YOSHIFUJI Hideaki <yoshfuji@linux-ipv6.org> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __net_exit sctp_net_exit(struct net *net) { /* Free the local address list */ sctp_free_addr_wq(net); sctp_free_local_addr_list(net); /* Free the control endpoint. */ inet_ctl_sock_destroy(net->sctp.ctl_sock); sctp_dbg_objcnt_exit(net); sctp_proc_exit(net); cleanup_sctp_mibs(net); sctp_sysctl_net_unregister(net); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'sctp: fix race on protocol/netns initialization Consider sctp module is unloaded and is being requested because an user is creating a sctp socket. During initialization, sctp will add the new protocol type and then initialize pernet subsys: status = sctp_v4_protosw_init(); if (status) goto err_protosw_init; status = sctp_v6_protosw_init(); if (status) goto err_v6_protosw_init; status = register_pernet_subsys(&sctp_net_ops); The problem is that after those calls to sctp_v{4,6}_protosw_init(), it is possible for userspace to create SCTP sockets like if the module is already fully loaded. If that happens, one of the possible effects is that we will have readers for net->sctp.local_addr_list list earlier than expected and sctp_net_init() does not take precautions while dealing with that list, leading to a potential panic but not limited to that, as sctp_sock_init() will copy a bunch of blank/partially initialized values from net->sctp. The race happens like this: CPU 0 | CPU 1 socket() | __sock_create | socket() inet_create | __sock_create list_for_each_entry_rcu( | answer, &inetsw[sock->type], | list) { | inet_create /* no hits */ | if (unlikely(err)) { | ... | request_module() | /* socket creation is blocked | * the module is fully loaded | */ | sctp_init | sctp_v4_protosw_init | inet_register_protosw | list_add_rcu(&p->list, | last_perm); | | list_for_each_entry_rcu( | answer, &inetsw[sock->type], sctp_v6_protosw_init | list) { | /* hit, so assumes protocol | * is already loaded | */ | /* socket creation continues | * before netns is initialized | */ register_pernet_subsys | Simply inverting the initialization order between register_pernet_subsys() and sctp_v4_protosw_init() is not possible because register_pernet_subsys() will create a control sctp socket, so the protocol must be already visible by then. Deferring the socket creation to a work-queue is not good specially because we loose the ability to handle its errors. So, as suggested by Vlad, the fix is to split netns initialization in two moments: defaults and control socket, so that the defaults are already loaded by when we register the protocol, while control socket initialization is kept at the same moment it is today. Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace") Signed-off-by: Vlad Yasevich <vyasevich@gmail.com> Signed-off-by: Marcelo Ricardo Leitner <marcelo.leitner@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* context) override { // Read the `rt_nested_splits` input & convert to Eigen tensors. OpInputList rt_nested_splits_in; OP_REQUIRES_OK( context, context->input_list("rt_nested_splits", &rt_nested_splits_in)); const int rt_nested_splits_len = rt_nested_splits_in.size(); DCHECK_GT(rt_nested_splits_len, 0); // Enforced by REGISTER_OP. std::vector<ConstFlatSplits> rt_nested_splits; rt_nested_splits.reserve(rt_nested_splits_len); for (int i = 0; i < rt_nested_splits_len; ++i) { rt_nested_splits.push_back(rt_nested_splits_in[i].flat<SPLITS_TYPE>()); } // Read the `rt_dense_values` input. const Tensor& rt_dense_values_in = context->input(rt_nested_splits_len); OP_REQUIRES_OK(context, ValidateInputs(rt_nested_splits, rt_dense_values_in)); // Assemble each value in `sparse_indices` using three parts: // - `index_prefix` is the index in dimensions up through the last ragged // dimension. // - `index_middle` is the index in the last ragged dimension. // - `index_suffix` is the index in the dense value dimensions. std::vector<int64> index_prefix(rt_nested_splits_len); std::vector<std::vector<int64>> index_suffixes = MakeIndexSuffixes(rt_dense_values_in.shape()); // Allocate the `sparse_indices` output tensor. const int64_t nvals = (rt_nested_splits.back()(rt_nested_splits.back().size() - 1) * index_suffixes.size()); const int64_t indices_len = rt_nested_splits_len + rt_dense_values_in.dims(); Tensor* sparse_indices_out = nullptr; OP_REQUIRES_OK( context, context->allocate_output(0, TensorShape({nvals, indices_len}), &sparse_indices_out)); auto sparse_indices = sparse_indices_out->tensor<int64, 2>(); // pos[i] is the current position in rt_nested_splits[i]. final_pos is a // reference to make it easier to refer to pos[-1]. std::vector<int64> pos(rt_nested_splits_len); int64& final_pos = pos[rt_nested_splits_len - 1]; // Each iteration through the loop, we increment pos[-1], and add indices // for all the values corresponding to // rt_nested_splits[-1][pos[-1]:pos[-1]+1]. int next_index = 0; int max_final_pos = rt_nested_splits.back().size() - 1; for (; final_pos < max_final_pos; ++final_pos) { // Update `pos` to skip over completed elements (i.e., elements where // we have already generated indices for all contained values). for (int dim = rt_nested_splits_len - 2; dim >= 0; --dim) { while (IsCompleted(pos, dim, rt_nested_splits)) { pos[dim] += 1; } } // Update index_prefix. for (int dim = 0; dim < index_prefix.size(); ++dim) { int start = dim > 0 ? rt_nested_splits[dim - 1](pos[dim - 1]) : 0; index_prefix[dim] = pos[dim] - start; } // Get length of the final-ragged-dimension slice. const auto& final_splits = rt_nested_splits[rt_nested_splits_len - 1]; int64_t slice_len = final_splits(final_pos + 1) - final_splits(final_pos); // Add sparse_indices for this slice. for (int64_t i = 0; i < slice_len; ++i) { for (const auto& index_suffix : index_suffixes) { int dim = 0; for (int64_t index : index_prefix) { // index_prefix sparse_indices(next_index, dim++) = index; } sparse_indices(next_index, dim++) = i; // index_middle for (int64_t index : index_suffix) { // index_suffix sparse_indices(next_index, dim++) = index; } DCHECK_EQ(dim, indices_len); ++next_index; } } } DCHECK_EQ(next_index, nvals); // Output the `sparse_values` Tensor. if (rt_dense_values_in.dims() == 1) { context->set_output(1, rt_dense_values_in); } else { Tensor sparse_values_out(rt_dense_values_in.dtype()); bool shapes_match = sparse_values_out.CopyFrom( rt_dense_values_in, {rt_dense_values_in.NumElements()}); DCHECK(shapes_match); context->set_output(1, sparse_values_out); } // Output the `sparse_dense_shape` Tensor. int64_t ndims = rt_nested_splits_len + rt_dense_values_in.dims(); Tensor* sparse_dense_shape_out = nullptr; OP_REQUIRES_OK(context, context->allocate_output(2, TensorShape({ndims}), &sparse_dense_shape_out)); auto sparse_dense_shape = sparse_dense_shape_out->vec<int64>(); sparse_dense_shape(0) = rt_nested_splits_in[0].dim_size(0) - 1; for (int dim = 0; dim < rt_nested_splits_len; ++dim) { const auto& splits = rt_nested_splits[dim]; SPLITS_TYPE max_width = 0; for (int i = 1; i < splits.size(); ++i) { max_width = std::max(max_width, splits(i) - splits(i - 1)); } sparse_dense_shape(dim + 1) = max_width; } for (int dim = 1; dim < rt_dense_values_in.dims(); ++dim) { sparse_dense_shape(dim + rt_nested_splits_len) = rt_dense_values_in.dim_size(dim); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Add missing validation to `RaggedTensorToSparse`. There needs to be a check that the splits allow for valid ragged tensors. PiperOrigin-RevId: 387712169 Change-Id: I2499175324b82b65d159a260c7f83b98ceb5cc7d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field) { pb_field_iter_t old_field = *field; pb_size_t old_tag = *(pb_size_t*)field->pSize; /* Previous which_ value */ pb_size_t new_tag = field->tag; /* New which_ value */ if (old_tag == 0) return true; /* Ok, no old data in union */ if (old_tag == new_tag) return true; /* Ok, old data is of same type => merge */ /* Release old data. The find can fail if the message struct contains * invalid data. */ if (!pb_field_iter_find(&old_field, old_tag)) PB_RETURN_ERROR(stream, "invalid union tag"); pb_release_single_field(&old_field); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-763'], 'message': 'Fix invalid free() with oneof (#647) Nanopb would call free() or realloc() on an invalid (attacker controlled) pointer value when all the following conditions are true: - PB_ENABLE_MALLOC is defined at the compile time - Message definition contains an oneof field, and the oneof contains at least one pointer type field and at least one non-pointer type field. - Data being decoded first contains a non-pointer value for the oneof field, and later contains an overwriting pointer value. Depending on message layout, the bug may not be exploitable in all cases, but it is known to be exploitable at least with string and bytes fields. Actual security impact will also depend on the heap implementation used.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err flac_dmx_process(GF_Filter *filter) { GF_FLACDmxCtx *ctx = gf_filter_get_udta(filter); GF_FilterPacket *pck, *dst_pck; u8 *output; u8 *start; Bool final_flush=GF_FALSE; u32 pck_size, remain, prev_pck_size; u64 cts = GF_FILTER_NO_TS; FLACHeader hdr; //always reparse duration if (!ctx->duration.num) flac_dmx_check_dur(filter, ctx); if (ctx->opid && !ctx->is_playing) return GF_OK; pck = gf_filter_pid_get_packet(ctx->ipid); if (!pck) { if (gf_filter_pid_is_eos(ctx->ipid)) { if (!ctx->flac_buffer_size) { if (ctx->opid) gf_filter_pid_set_eos(ctx->opid); if (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck); ctx->src_pck = NULL; return GF_EOS; } final_flush = GF_TRUE; } else { return GF_OK; } } prev_pck_size = ctx->flac_buffer_size; if (pck && !ctx->resume_from) { u8 *data = (u8 *) gf_filter_pck_get_data(pck, &pck_size); if (ctx->byte_offset != GF_FILTER_NO_BO) { u64 byte_offset = gf_filter_pck_get_byte_offset(pck); if (!ctx->flac_buffer_size) { ctx->byte_offset = byte_offset; } else if (ctx->byte_offset + ctx->flac_buffer_size != byte_offset) { ctx->byte_offset = GF_FILTER_NO_BO; if ((byte_offset != GF_FILTER_NO_BO) && (byte_offset>ctx->flac_buffer_size) ) { ctx->byte_offset = byte_offset - ctx->flac_buffer_size; } } } if (ctx->flac_buffer_size + pck_size > ctx->flac_buffer_alloc) { ctx->flac_buffer_alloc = ctx->flac_buffer_size + pck_size; ctx->flac_buffer = gf_realloc(ctx->flac_buffer, ctx->flac_buffer_alloc); } memcpy(ctx->flac_buffer + ctx->flac_buffer_size, data, pck_size); ctx->flac_buffer_size += pck_size; } //input pid sets some timescale - we flushed pending data , update cts if (ctx->timescale && pck) { cts = gf_filter_pck_get_cts(pck); } if (cts == GF_FILTER_NO_TS) { //avoids updating cts prev_pck_size = 0; } remain = ctx->flac_buffer_size; start = ctx->flac_buffer; if (ctx->resume_from) { start += ctx->resume_from - 1; remain -= ctx->resume_from - 1; ctx->resume_from = 0; } while (remain>2) { u32 next_frame=0, nb_samp; u32 cur_size = remain-2; u8 *cur_buf = start+2; u8 *hdr_start = NULL; if (final_flush) { next_frame = remain; } else { while (cur_size) { //wait till we have a frame header hdr_start = memchr(cur_buf, 0xFF, cur_size); if (!hdr_start) break; next_frame = (u32) (hdr_start-start); if (next_frame == remain) break; if ((hdr_start[1]&0xFC) == 0xF8) { if (flac_parse_header(ctx, hdr_start, (u32) remain - next_frame, &hdr)) break; } cur_buf = hdr_start+1; cur_size = (u32) (cur_buf - start); assert(cur_size<=remain); cur_size = remain - cur_size; hdr_start = NULL; } if (!hdr_start) break; if (next_frame == remain) break; } if (!ctx->initialized) { u32 size = next_frame; u32 dsi_end = 0; //we have a header gf_bs_reassign_buffer(ctx->bs, ctx->flac_buffer, size); u32 magic = gf_bs_read_u32(ctx->bs); if (magic != GF_4CC('f','L','a','C')) { } while (gf_bs_available(ctx->bs)) { Bool last = gf_bs_read_int(ctx->bs, 1); u32 type = gf_bs_read_int(ctx->bs, 7); u32 len = gf_bs_read_int(ctx->bs, 24); if (type==0) { u16 min_block_size = gf_bs_read_u16(ctx->bs); u16 max_block_size = gf_bs_read_u16(ctx->bs); /*u32 min_frame_size = */gf_bs_read_u24(ctx->bs); /*u32 max_frame_size = */gf_bs_read_u24(ctx->bs); ctx->sample_rate = gf_bs_read_int(ctx->bs, 20); ctx->nb_channels = 1 + gf_bs_read_int(ctx->bs, 3); ctx->bits_per_sample = 1 + gf_bs_read_int(ctx->bs, 5); if (min_block_size==max_block_size) ctx->block_size = min_block_size; else ctx->block_size = 0; ctx->duration.num = gf_bs_read_long_int(ctx->bs, 36); ctx->duration.den = ctx->sample_rate; //ignore the rest gf_bs_skip_bytes(ctx->bs, 16); dsi_end = (u32) gf_bs_get_position(ctx->bs); } else { //ignore the rest for now //TODO: expose metadata, pictures and co gf_bs_skip_bytes(ctx->bs, len); } if (last) break; } flac_dmx_check_pid(filter, ctx, ctx->flac_buffer+4, dsi_end-4); remain -= size; start += size; ctx->initialized = GF_TRUE; if (!ctx->is_playing) break; continue; } //we have a next frame, check we are synchronize if ((start[0] != 0xFF) && ((start[1]&0xFC) != 0xF8)) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[FLACDmx] invalid frame, droping %d bytes and resyncing\n", next_frame)); start += next_frame; remain -= next_frame; continue; } flac_parse_header(ctx,start, next_frame, &hdr); if (hdr.sample_rate != ctx->sample_rate) { ctx->sample_rate = hdr.sample_rate; gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAMPLE_RATE, & PROP_UINT(ctx->sample_rate)); } nb_samp = hdr.block_size; if (ctx->in_seek) { u64 nb_samples_at_seek = (u64) (ctx->start_range * ctx->sample_rate); if (ctx->cts + nb_samp >= nb_samples_at_seek) { //u32 samples_to_discard = (ctx->cts + nb_samp ) - nb_samples_at_seek; ctx->in_seek = GF_FALSE; } } if (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) { ctx->cts = cts; cts = GF_FILTER_NO_TS; } if (!ctx->in_seek) { dst_pck = gf_filter_pck_new_alloc(ctx->opid, next_frame, &output); memcpy(output, start, next_frame); gf_filter_pck_set_cts(dst_pck, ctx->cts); if (!ctx->timescale || (ctx->timescale==ctx->sample_rate) ) gf_filter_pck_set_duration(dst_pck, nb_samp); else { gf_filter_pck_set_duration(dst_pck, (nb_samp * ctx->timescale) / ctx->sample_rate); } gf_filter_pck_set_sap(dst_pck, GF_FILTER_SAP_1); gf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE); if (ctx->byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, ctx->byte_offset); } gf_filter_pck_send(dst_pck); } flac_dmx_update_cts(ctx, nb_samp); assert (start[0] == 0xFF); assert((start[1]&0xFC) == 0xF8); start += next_frame; assert(remain >= next_frame); remain -= next_frame; } if (!pck) { ctx->flac_buffer_size = 0; return flac_dmx_process(filter); } else { if (remain < ctx->flac_buffer_size) { memmove(ctx->flac_buffer, start, remain); } ctx->flac_buffer_size = remain; gf_filter_pid_drop_packet(ctx->ipid); } return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'fixed 1718'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void free_huge_page(struct page *page) { /* * Can't pass hstate in here because it is called from the * compound page destructor. */ struct hstate *h = page_hstate(page); int nid = page_to_nid(page); struct address_space *mapping; mapping = (struct address_space *) page_private(page); set_page_private(page, 0); page->mapping = NULL; BUG_ON(page_count(page)); BUG_ON(page_mapcount(page)); INIT_LIST_HEAD(&page->lru); spin_lock(&hugetlb_lock); if (h->surplus_huge_pages_node[nid] && huge_page_order(h) < MAX_ORDER) { update_and_free_page(h, page); h->surplus_huge_pages--; h->surplus_huge_pages_node[nid]--; } else { enqueue_huge_page(h, page); } spin_unlock(&hugetlb_lock); if (mapping) hugetlb_put_quota(mapping, 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'hugepages: fix use after free bug in "quota" handling hugetlbfs_{get,put}_quota() are badly named. They don't interact with the general quota handling code, and they don't much resemble its behaviour. Rather than being about maintaining limits on on-disk block usage by particular users, they are instead about maintaining limits on in-memory page usage (including anonymous MAP_PRIVATE copied-on-write pages) associated with a particular hugetlbfs filesystem instance. Worse, they work by having callbacks to the hugetlbfs filesystem code from the low-level page handling code, in particular from free_huge_page(). This is a layering violation of itself, but more importantly, if the kernel does a get_user_pages() on hugepages (which can happen from KVM amongst others), then the free_huge_page() can be delayed until after the associated inode has already been freed. If an unmount occurs at the wrong time, even the hugetlbfs superblock where the "quota" limits are stored may have been freed. Andrew Barry proposed a patch to fix this by having hugepages, instead of storing a pointer to their address_space and reaching the superblock from there, had the hugepages store pointers directly to the superblock, bumping the reference count as appropriate to avoid it being freed. Andrew Morton rejected that version, however, on the grounds that it made the existing layering violation worse. This is a reworked version of Andrew's patch, which removes the extra, and some of the existing, layering violation. It works by introducing the concept of a hugepage "subpool" at the lower hugepage mm layer - that is a finite logical pool of hugepages to allocate from. hugetlbfs now creates a subpool for each filesystem instance with a page limit set, and a pointer to the subpool gets added to each allocated hugepage, instead of the address_space pointer used now. The subpool has its own lifetime and is only freed once all pages in it _and_ all other references to it (i.e. superblocks) are gone. subpools are optional - a NULL subpool pointer is taken by the code to mean that no subpool limits are in effect. Previous discussion of this bug found in: "Fix refcounting in hugetlbfs quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or http://marc.info/?l=linux-mm&m=126928970510627&w=1 v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to alloc_huge_page() - since it already takes the vma, it is not necessary. Signed-off-by: Andrew Barry <abarry@cray.com> Signed-off-by: David Gibson <david@gibson.dropbear.id.au> Cc: Hugh Dickins <hughd@google.com> Cc: Mel Gorman <mgorman@suse.de> Cc: Minchan Kim <minchan.kim@gmail.com> Cc: Hillf Danton <dhillf@gmail.com> Cc: Paul Mackerras <paulus@samba.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'avcodec/mpeg4videodec: Check for bitstream end in read_quant_matrix_ext() Fixes: out of array read Fixes: asff-crash-0e53d0dc491dfdd507530b66562812fbd4c36678 Found-by: Paul Ch <paulcher@icloud.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int read_header_tga(gdIOCtx *ctx, oTga *tga) { unsigned char header[18]; if (gdGetBuf(header, sizeof(header), ctx) < 18) { gd_error("fail to read header"); return -1; } tga->identsize = header[0]; tga->colormaptype = header[1]; tga->imagetype = header[2]; tga->colormapstart = header[3] + (header[4] << 8); tga->colormaplength = header[5] + (header[6] << 8); tga->colormapbits = header[7]; tga->xstart = header[8] + (header[9] << 8); tga->ystart = header[10] + (header[11] << 8); tga->width = header[12] + (header[13] << 8); tga->height = header[14] + (header[15] << 8); tga->bits = header[16]; tga->alphabits = header[17] & 0x0f; tga->fliph = (header[17] & 0x10) ? 1 : 0; tga->flipv = (header[17] & 0x20) ? 0 : 1; #if DEBUG printf("format bps: %i\n", tga->bits); printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv); printf("alpha: %i\n", tga->alphabits); printf("wxh: %i %i\n", tga->width, tga->height); #endif if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0) || (tga->bits == TGA_BPP_32 && tga->alphabits == 8))) { gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n", tga->bits, tga->alphabits); return -1; } tga->ident = NULL; if (tga->identsize > 0) { tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char)); if(tga->ident == NULL) { return -1; } gdGetBuf(tga->ident, tga->identsize, ctx); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix read out-of-bands in reading tga header file'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: agoo_con_create(agooErr err, int sock, uint64_t id, agooBind b) { agooCon c; if (NULL == (c = (agooCon)AGOO_CALLOC(1, sizeof(struct _agooCon)))) { AGOO_ERR_MEM(err, "Connection"); } else { c->sock = sock; c->id = id; c->timeout = dtime() + CON_TIMEOUT; c->bind = b; c->loop = NULL; pthread_mutex_init(&c->res_lock, 0); } return c; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-444', 'CWE-61'], 'message': 'Remote addr (#99) * REMOTE_ADDR added * Ready for merge'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int read_header_tga(gdIOCtx *ctx, oTga *tga) { unsigned char header[18]; if (gdGetBuf(header, sizeof(header), ctx) < 18) { gd_error("fail to read header"); return -1; } tga->identsize = header[0]; tga->colormaptype = header[1]; tga->imagetype = header[2]; tga->colormapstart = header[3] + (header[4] << 8); tga->colormaplength = header[5] + (header[6] << 8); tga->colormapbits = header[7]; tga->xstart = header[8] + (header[9] << 8); tga->ystart = header[10] + (header[11] << 8); tga->width = header[12] + (header[13] << 8); tga->height = header[14] + (header[15] << 8); tga->bits = header[16]; tga->alphabits = header[17] & 0x0f; tga->fliph = (header[17] & 0x10) ? 1 : 0; tga->flipv = (header[17] & 0x20) ? 0 : 1; #if DEBUG printf("format bps: %i\n", tga->bits); printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv); printf("alpha: %i\n", tga->alphabits); printf("wxh: %i %i\n", tga->width, tga->height); #endif switch(tga->bits) { case 8: case 16: case 24: case 32: break; default: gd_error("bps %i not supported", tga->bits); return -1; break; } tga->ident = NULL; if (tga->identsize > 0) { tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char)); if(tga->ident == NULL) { return -1; } gdGetBuf(tga->ident, tga->identsize, ctx); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Unsupported TGA bpp/alphabit combinations should error gracefully Currently, only 24bpp without alphabits and 32bpp with 8 alphabits are really supported. All other combinations will be rejected with a warning.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void PM_io_parser<PMDEC>::read() { if ( !check_sep("Plane_map_2") ) CGAL_error_msg("PM_io_parser::read: no embedded_PM header."); if ( !(check_sep("vertices") && (in >> vn)) ) CGAL_error_msg("PM_io_parser::read: wrong node line."); if ( !(check_sep("halfedges") && (in >> en) && (en%2==0)) ) CGAL_error_msg("PM_io_parser::read: wrong edge line."); if ( !(check_sep("faces") && (in >> fn)) ) CGAL_error_msg("PM_io_parser::read: wrong face line."); Vertex_of.resize(vn); Halfedge_of.resize(en); Face_of.resize(fn); for(i=0; i<vn; i++) Vertex_of[i] = this->new_vertex(); for(i=0; i<en; i++) if (i%2==0) Halfedge_of[i] = this->new_halfedge_pair_without_vertices(); else Halfedge_of[i] = twin(Halfedge_of[i-1]); for(i=0; i<fn; i++) Face_of[i] = this->new_face(); for(i=0; i<vn; i++) { if (!read_vertex(Vertex_of[i])) CGAL_error_msg("PM_io_parser::read: error in node line"); } for(i=0; i<en; i++) { if (!read_hedge(Halfedge_of[i])) CGAL_error_msg("PM_io_parser::read: error in halfedge\ line"); } for(i=0; i<fn; i++) { if (!read_face(Face_of[i])) CGAL_error_msg("PM_io_parser::read: error in face line"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'Fix Nef_2 and Nef_S2 IO'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool read_ujpg( void ) { using namespace IOUtil; using namespace Sirikata; // colldata.start_decoder_worker_thread(std::bind(&simple_decoder, &colldata, str_in)); unsigned char ujpg_mrk[ 64 ]; // this is where we will enable seccomp, before reading user data write_byte_bill(Billing::HEADER, true, 24); // for the fixed header str_out->call_size_callback(max_file_size); uint32_t compressed_header_size = 0; if (ReadFull(str_in, ujpg_mrk, 4) != 4) { custom_exit(ExitCode::SHORT_READ); } write_byte_bill(Billing::HEADER, true, 4); compressed_header_size = LEtoUint32(ujpg_mrk); if (compressed_header_size > 128 * 1024 * 1024 || max_file_size > 128 * 1024 * 1024) { always_assert(false && "Only support images < 128 megs"); return false; // bool too big } bool pending_header_reads = false; if (header_reader == NULL) { std::vector<uint8_t, JpegAllocator<uint8_t> > compressed_header_buffer(compressed_header_size); IOUtil::ReadFull(str_in, compressed_header_buffer.data(), compressed_header_buffer.size()); header_reader = new MemReadWriter((JpegAllocator<uint8_t>())); { if (ujgversion == 1) { JpegAllocator<uint8_t> no_free_allocator; #if !defined(USE_STANDARD_MEMORY_ALLOCATORS) && !defined(_WIN32) && !defined(EMSCRIPTEN) no_free_allocator.setup_memory_subsystem(32 * 1024 * 1024, 16, &mem_init_nop, &MemMgrAllocatorMalloc, &mem_nop, &mem_realloc_nop, &MemMgrAllocatorMsize); #endif std::pair<std::vector<uint8_t, Sirikata::JpegAllocator<uint8_t> >, JpegError> uncompressed_header_buffer( ZlibDecoderDecompressionReader::Decompress(compressed_header_buffer.data(), compressed_header_buffer.size(), no_free_allocator, max_file_size + 2048)); if (uncompressed_header_buffer.second) { always_assert(false && "Data not properly zlib coded"); return false; } zlib_hdrs = compressed_header_buffer.size(); header_reader->SwapIn(uncompressed_header_buffer.first, 0); } else { std::pair<std::vector<uint8_t, Sirikata::JpegAllocator<uint8_t> >, JpegError> uncompressed_header_buffer( Sirikata::BrotliCodec::Decompress(compressed_header_buffer.data(), compressed_header_buffer.size(), JpegAllocator<uint8_t>(), max_file_size * 2 + 128 * 1024 * 1024)); if (uncompressed_header_buffer.second) { always_assert(false && "Data not properly zlib coded"); return false; } zlib_hdrs = compressed_header_buffer.size(); header_reader->SwapIn(uncompressed_header_buffer.first, 0); } } write_byte_bill(Billing::HEADER, true, compressed_header_buffer.size()); } else { always_assert(compressed_header_size == 0 && "Special concatenation requires 0 size header"); } grbs = sizeof(EOI); grbgdata = EOI; // if we don't have any garbage, assume FFD9 EOI // read header from file ReadFull(header_reader, ujpg_mrk, 3 ) ; // check marker if ( memcmp( ujpg_mrk, "HDR", 3 ) == 0 ) { // read size of header, alloc memory ReadFull(header_reader, ujpg_mrk, 4 ); hdrs = LEtoUint32(ujpg_mrk); hdrdata = (unsigned char*) aligned_alloc(hdrs); memset(hdrdata, 0, hdrs); if ( hdrdata == NULL ) { fprintf( stderr, MEM_ERRMSG ); errorlevel.store(2); return false; } // read hdrdata ReadFull(header_reader, hdrdata, hdrs ); } else { fprintf( stderr, "HDR marker not found" ); errorlevel.store(2); return false; } bool memory_optimized_image = (filetype != UJG) && !g_allow_progressive; // parse header for image-info if ( !setup_imginfo_jpg(memory_optimized_image) ) return false; // beginning here: recovery information (needed for exact JPEG recovery) // read padbit information from file ReadFull(header_reader, ujpg_mrk, 3 ); // check marker if ( memcmp( ujpg_mrk, "P0D", 3 ) == 0 ) { // This is a more nuanced pad byte that can have different values per bit header_reader->Read( reinterpret_cast<unsigned char*>(&padbit), 1 ); } else if ( memcmp( ujpg_mrk, "PAD", 3 ) == 0 ) { // this is a single pad bit that is implied to have all the same values header_reader->Read( reinterpret_cast<unsigned char*>(&padbit), 1 ); if (!(padbit == 0 || padbit == 1 ||padbit == -1)) { while (write(2, "Legacy Padbit must be 0, 1 or -1\n", strlen("Legacy Padbit must be 0, 1 or -1\n")) < 0 && errno == EINTR) { } custom_exit(ExitCode::STREAM_INCONSISTENT); } if (padbit == 1) { padbit = 0x7f; // all 6 bits set } } else { fprintf( stderr, "PAD marker not found" ); errorlevel.store(2); return false; } std::vector<ThreadHandoff> thread_handoff; // read further recovery information if any while ( ReadFull(header_reader, ujpg_mrk, 3 ) == 3 ) { // check marker if ( memcmp( ujpg_mrk, "CRS", 3 ) == 0 ) { rst_cnt_set = true; ReadFull(header_reader, ujpg_mrk, 4); rst_cnt.resize(LEtoUint32(ujpg_mrk)); for (size_t i = 0; i < rst_cnt.size(); ++i) { ReadFull(header_reader, ujpg_mrk, 4); rst_cnt.at(i) = LEtoUint32(ujpg_mrk); } } else if ( memcmp( ujpg_mrk, "HHX", 2 ) == 0 ) { // only look at first two bytes size_t to_alloc = ThreadHandoff::get_remaining_data_size_from_two_bytes(ujpg_mrk + 1) + 2; if(to_alloc) { std::vector<unsigned char> data(to_alloc); data[0] = ujpg_mrk[1]; data[1] = ujpg_mrk[2]; ReadFull(header_reader, &data[2], to_alloc - 2); thread_handoff = ThreadHandoff::deserialize(&data[0], to_alloc); } } else if ( memcmp( ujpg_mrk, "FRS", 3 ) == 0 ) { // read number of false set RST markers per scan from file ReadFull(header_reader, ujpg_mrk, 4); scnc = LEtoUint32(ujpg_mrk); rst_err.insert(rst_err.end(), scnc - rst_err.size(), 0); // read data ReadFull(header_reader, rst_err.data(), scnc ); } else if ( memcmp( ujpg_mrk, "GRB", 3 ) == 0 ) { // read garbage (data after end of JPG) from file ReadFull(header_reader, ujpg_mrk, 4); grbs = LEtoUint32(ujpg_mrk); grbgdata = aligned_alloc(grbs); memset(grbgdata, 0, sizeof(grbs)); if ( grbgdata == NULL ) { fprintf( stderr, MEM_ERRMSG ); errorlevel.store(2); return false; } // read garbage data ReadFull(header_reader, grbgdata, grbs ); } else if ( memcmp( ujpg_mrk, "PGR", 3 ) == 0 || memcmp( ujpg_mrk, "PGE", 3 ) == 0 ) { // read prefix garbage (data before beginning of JPG) from file if (ujpg_mrk[2] == 'E') { // embedded jpeg: full header required embedded_jpeg = true; } ReadFull(header_reader, ujpg_mrk, 4); prefix_grbs = LEtoUint32(ujpg_mrk); prefix_grbgdata = aligned_alloc(prefix_grbs); memset(prefix_grbgdata, 0, sizeof(prefix_grbs)); if ( prefix_grbgdata == NULL ) { fprintf( stderr, MEM_ERRMSG ); errorlevel.store(2); return false; } // read garbage data ReadFull(header_reader, prefix_grbgdata, prefix_grbs ); } else if ( memcmp( ujpg_mrk, "SIZ", 3 ) == 0 ) { // full size of the original file ReadFull(header_reader, ujpg_mrk, 4); max_file_size = LEtoUint32(ujpg_mrk); } else if ( memcmp( ujpg_mrk, "EEE", 3) == 0) { ReadFull(header_reader, ujpg_mrk, 28); max_cmp = LEtoUint32(ujpg_mrk); max_bpos = LEtoUint32(ujpg_mrk + 4); max_sah = LEtoUint32(ujpg_mrk + 8); max_dpos[0] = LEtoUint32(ujpg_mrk + 12); max_dpos[1] = LEtoUint32(ujpg_mrk + 16); max_dpos[2] = LEtoUint32(ujpg_mrk + 20); max_dpos[3] = LEtoUint32(ujpg_mrk + 24); early_eof_encountered = true; colldata.set_truncation_bounds(max_cmp, max_bpos, max_dpos, max_sah); } else { if (memcmp(ujpg_mrk, "CNT", 3) == 0 ) { pending_header_reads = true; break; } else if (memcmp(ujpg_mrk, "CMP", 3) == 0 ) { break; } else { fprintf( stderr, "unknown data found" ); errorlevel.store(2); } return false; } } if (!pending_header_reads) { delete header_reader; header_reader = NULL; } write_byte_bill(Billing::HEADER, false, 2 + hdrs + prefix_grbs + grbs); ReadFull(str_in, ujpg_mrk, 3 ) ; write_byte_bill(Billing::HEADER, true, 3); write_byte_bill(Billing::DELIMITERS, true, 4 * NUM_THREADS); // trailing vpx_encode bits write_byte_bill(Billing::HEADER, true, 4); //trailing size if (memcmp(ujpg_mrk, "CMP", 3) != 0) { always_assert(false && "CMP must be present (uncompressed) in the file or CNT continue marker"); return false; // not a JPG } colldata.signal_worker_should_begin(); g_decoder->initialize(str_in, thread_handoff); colldata.start_decoder(g_decoder); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-190'], 'message': 'fix #111'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int somfy_iohc_decode(r_device *decoder, bitbuffer_t *bitbuffer) { uint8_t const preamble_pattern[] = {0x57, 0xfd, 0x99}; uint8_t b[19 + 15]; // 19 byte + up 15 byte payload if (bitbuffer->num_rows != 1) return DECODE_ABORT_EARLY; int offset = bitbuffer_search(bitbuffer, 0, 0, preamble_pattern, 24) + 24; if (offset >= bitbuffer->bits_per_row[0] - 19 * 10) return DECODE_ABORT_EARLY; int num_bits = bitbuffer->bits_per_row[0] - offset; int len = extract_bytes_uart(bitbuffer->bb[0], offset, num_bits, b); if (len < 19) return DECODE_ABORT_LENGTH; if ((b[0] & 0xf0) != 0xf0) return DECODE_ABORT_EARLY; int msg_len = b[0] & 0xf; // should be 6 or 8 if (len < 19 + msg_len) return DECODE_ABORT_LENGTH; // calculate and verify checksum if (crc16lsb(b, len, 0x8408, 0x0000) != 0) // unreflected poly 0x1021 return DECODE_FAIL_MIC; bitrow_printf(b, len * 8, "%s: offset %d, num_bits %d, len %d, msg_len %d\n", __func__, offset, num_bits, len, msg_len); int msg_type = (b[0]); int dst_id = ((unsigned)b[4] << 24) | (b[3] << 16) | (b[2] << 8) | (b[1]); // assume Little-Endian int src_id = ((unsigned)b[8] << 24) | (b[7] << 16) | (b[6] << 8) | (b[5]); // assume Little-Endian int counter = (b[len - 10] << 8) | (b[len - 9]); char msg_str[15 * 2 + 1]; bitrow_snprint(&b[9], msg_len * 8, msg_str, 15 * 2 + 1); char mac_str[13]; bitrow_snprint(&b[len - 8], 6 * 8, mac_str, 13); /* clang-format off */ data_t *data = data_make( "model", "", DATA_STRING, "Somfy-IOHC", "id", "", DATA_FORMAT, "%08x", DATA_INT, src_id, "dst_id", "Dest ID", DATA_FORMAT, "%08x", DATA_INT, dst_id, "msg_type", "Msg type", DATA_FORMAT, "%02x", DATA_INT, msg_type, "msg", "Message", DATA_STRING, msg_str, "counter", "Counter", DATA_INT, counter, "mac", "MAC", DATA_STRING, mac_str, "mic", "Integrity", DATA_STRING, "CRC", NULL); /* clang-format on */ decoder_output_data(decoder, data); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-193'], 'message': 'minor: Fix overflow in Clipsal-CMR113 and Somfy-IOHC reported by aug5t7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field) { #ifndef PB_ENABLE_MALLOC PB_UNUSED(wire_type); PB_UNUSED(field); PB_RETURN_ERROR(stream, "no malloc support"); #else switch (PB_HTYPE(field->type)) { case PB_HTYPE_REQUIRED: case PB_HTYPE_OPTIONAL: case PB_HTYPE_ONEOF: if (!check_wire_type(wire_type, field)) PB_RETURN_ERROR(stream, "wrong wire type"); if (PB_LTYPE_IS_SUBMSG(field->type) && *(void**)field->pField != NULL) { /* Duplicate field, have to release the old allocation first. */ /* FIXME: Does this work correctly for oneofs? */ pb_release_single_field(field); } if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF) { *(pb_size_t*)field->pSize = field->tag; } if (PB_LTYPE(field->type) == PB_LTYPE_STRING || PB_LTYPE(field->type) == PB_LTYPE_BYTES) { /* pb_dec_string and pb_dec_bytes handle allocation themselves */ field->pData = field->pField; return decode_basic_field(stream, field); } else { if (!allocate_field(stream, field->pField, field->data_size, 1)) return false; field->pData = *(void**)field->pField; initialize_pointer_field(field->pData, field); return decode_basic_field(stream, field); } case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array, multiple items come in at once. */ bool status = true; pb_size_t *size = (pb_size_t*)field->pSize; size_t allocated_size = *size; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left) { if ((size_t)*size + 1 > allocated_size) { /* Allocate more storage. This tries to guess the * number of remaining entries. Round the division * upwards. */ allocated_size += (substream.bytes_left - 1) / field->data_size + 1; if (!allocate_field(&substream, field->pField, field->data_size, allocated_size)) { status = false; break; } } /* Decode the array entry */ field->pData = *(char**)field->pField + field->data_size * (*size); initialize_pointer_field(field->pData, field); if (!decode_basic_field(&substream, field)) { status = false; break; } if (*size == PB_SIZE_MAX) { #ifndef PB_NO_ERRMSG stream->errmsg = "too many array entries"; #endif status = false; break; } (*size)++; } if (!pb_close_string_substream(stream, &substream)) return false; return status; } else { /* Normal repeated field, i.e. only one item at a time. */ pb_size_t *size = (pb_size_t*)field->pSize; if (*size == PB_SIZE_MAX) PB_RETURN_ERROR(stream, "too many array entries"); if (!check_wire_type(wire_type, field)) PB_RETURN_ERROR(stream, "wrong wire type"); (*size)++; if (!allocate_field(stream, field->pField, field->data_size, *size)) return false; field->pData = *(char**)field->pField + field->data_size * (*size - 1); initialize_pointer_field(field->pData, field); return decode_basic_field(stream, field); } default: PB_RETURN_ERROR(stream, "invalid field type"); } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int xpm_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { XPMDecContext *x = avctx->priv_data; AVFrame *p=data; const uint8_t *end, *ptr = avpkt->data; int ncolors, cpp, ret, i, j; int64_t size; uint32_t *dst; avctx->pix_fmt = AV_PIX_FMT_BGRA; end = avpkt->data + avpkt->size; while (memcmp(ptr, "/* XPM */", 9) && ptr < end - 9) ptr++; if (ptr >= end) { av_log(avctx, AV_LOG_ERROR, "missing signature\n"); return AVERROR_INVALIDDATA; } ptr += mod_strcspn(ptr, "\""); if (sscanf(ptr, "\"%u %u %u %u\",", &avctx->width, &avctx->height, &ncolors, &cpp) != 4) { av_log(avctx, AV_LOG_ERROR, "missing image parameters\n"); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0) return ret; if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; if (cpp <= 0 || cpp >= 5) { av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of chars per pixel: %d\n", cpp); return AVERROR_INVALIDDATA; } size = 1; for (i = 0; i < cpp; i++) size *= 94; if (ncolors <= 0 || ncolors > size) { av_log(avctx, AV_LOG_ERROR, "invalid number of colors: %d\n", ncolors); return AVERROR_INVALIDDATA; } size *= 4; av_fast_padded_malloc(&x->pixels, &x->pixels_size, size); if (!x->pixels) return AVERROR(ENOMEM); ptr += mod_strcspn(ptr, ",") + 1; for (i = 0; i < ncolors; i++) { const uint8_t *index; int len; ptr += mod_strcspn(ptr, "\"") + 1; if (ptr + cpp > end) return AVERROR_INVALIDDATA; index = ptr; ptr += cpp; ptr = strstr(ptr, "c "); if (ptr) { ptr += 2; } else { return AVERROR_INVALIDDATA; } len = strcspn(ptr, "\" "); if ((ret = ascii2index(index, cpp)) < 0) return ret; x->pixels[ret] = color_string_to_rgba(ptr, len); ptr += mod_strcspn(ptr, ",") + 1; } for (i = 0; i < avctx->height; i++) { dst = (uint32_t *)(p->data[0] + i * p->linesize[0]); ptr += mod_strcspn(ptr, "\"") + 1; for (j = 0; j < avctx->width; j++) { if (ptr + cpp > end) return AVERROR_INVALIDDATA; if ((ret = ascii2index(ptr, cpp)) < 0) return ret; *dst++ = x->pixels[ret]; ptr += cpp; } ptr += mod_strcspn(ptr, ",") + 1; } p->key_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avcodec/xpmdec: Fix multiple pointer/memory issues Most of these were found through code review in response to fixing 1466/clusterfuzz-testcase-minimized-5961584419536896 There is thus no testcase for most of this. The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool FromkLinuxSockAddr(const struct klinux_sockaddr *input, socklen_t input_len, struct sockaddr *output, socklen_t *output_len, void (*abort_handler)(const char *)) { if (!input || !output || !output_len || input_len == 0) { output = nullptr; return false; } int16_t klinux_family = input->klinux_sa_family; if (klinux_family == kLinux_AF_UNIX) { struct klinux_sockaddr_un *klinux_sockaddr_un_in = const_cast<struct klinux_sockaddr_un *>( reinterpret_cast<const struct klinux_sockaddr_un *>(input)); struct sockaddr_un sockaddr_un_out; sockaddr_un_out.sun_family = AF_UNIX; InitializeToZeroArray(sockaddr_un_out.sun_path); ReinterpretCopyArray( sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path, std::min(sizeof(sockaddr_un_out.sun_path), sizeof(klinux_sockaddr_un_in->klinux_sun_path))); CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len); } else if (klinux_family == kLinux_AF_INET) { struct klinux_sockaddr_in *klinux_sockaddr_in_in = const_cast<struct klinux_sockaddr_in *>( reinterpret_cast<const struct klinux_sockaddr_in *>(input)); struct sockaddr_in sockaddr_in_out; sockaddr_in_out.sin_family = AF_INET; sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port; InitializeToZeroSingle(&sockaddr_in_out.sin_addr); ReinterpretCopySingle(&sockaddr_in_out.sin_addr, &klinux_sockaddr_in_in->klinux_sin_addr); InitializeToZeroArray(sockaddr_in_out.sin_zero); ReinterpretCopyArray(sockaddr_in_out.sin_zero, klinux_sockaddr_in_in->klinux_sin_zero); CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len); } else if (klinux_family == kLinux_AF_INET6) { struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in = const_cast<struct klinux_sockaddr_in6 *>( reinterpret_cast<const struct klinux_sockaddr_in6 *>(input)); struct sockaddr_in6 sockaddr_in6_out; sockaddr_in6_out.sin6_family = AF_INET6; sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port; sockaddr_in6_out.sin6_flowinfo = klinux_sockaddr_in6_in->klinux_sin6_flowinfo; sockaddr_in6_out.sin6_scope_id = klinux_sockaddr_in6_in->klinux_sin6_scope_id; InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr); ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr, &klinux_sockaddr_in6_in->klinux_sin6_addr); CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output, output_len); } else if (klinux_family == kLinux_AF_UNSPEC) { output = nullptr; *output_len = 0; } else { if (abort_handler != nullptr) { std::string message = absl::StrCat( "Type conversion error - Unsupported AF family: ", klinux_family); abort_handler(message.c_str()); } else { abort(); } } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Check input length in FromLinuxSockAddr PiperOrigin-RevId: 333785506 Change-Id: I1d68fb8954665eebc1018d80ff995cbe9e7ed6a9'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf, size_t size) { GetBitContext gb; AC3HeaderInfo *hdr; int err; if (!*phdr) *phdr = av_mallocz(sizeof(AC3HeaderInfo)); if (!*phdr) return AVERROR(ENOMEM); hdr = *phdr; init_get_bits8(&gb, buf, size); err = ff_ac3_parse_header(&gb, hdr); if (err < 0) return AVERROR_INVALIDDATA; return get_bits_count(&gb); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'avcodec/ac3_parser: Check init_get_bits8() for failure Fixes: null pointer dereference Fixes: ffmpeg_crash_6.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Reviewed-by: Paul B Mahol <onemda@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const Tensor& input_min_range = ctx->input(1); const Tensor& input_max_range = ctx->input(2); int num_slices = 1; if (axis_ > -1) { num_slices = input.dim_size(axis_); } const TensorShape& minmax_shape = ctx->input(1).shape(); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor* output_min_tensor = nullptr; Tensor* output_max_tensor = nullptr; if (num_slices == 1) { OP_REQUIRES_OK(ctx, ctx->allocate_output(1, {}, &output_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_output(2, {}, &output_max_tensor)); const float min_range = input_min_range.template flat<float>()(0); const float max_range = input_max_range.template flat<float>()(0); QuantizeTensor(ctx, input, min_range, max_range, output, output_min_tensor, output_max_tensor); return; } OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST, errors::Unimplemented("MIN_FIRST mode is not implemented for " "Quantize with axis != -1.")); OP_REQUIRES_OK(ctx, ctx->allocate_output(1, minmax_shape, &output_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_output(2, minmax_shape, &output_max_tensor)); auto input_tensor = input.template flat_inner_outer_dims<float, 3>(axis_ - 1); int64_t pre_dim = 1, post_dim = 1; for (int i = 0; i < axis_; ++i) { pre_dim *= output->dim_size(i); } for (int i = axis_ + 1; i < output->dims(); ++i) { post_dim *= output->dim_size(i); } auto output_tensor = output->template bit_casted_shaped<T, 3>( {pre_dim, num_slices, post_dim}); auto min_ranges = input_min_range.template vec<float>(); auto max_ranges = input_max_range.template vec<float>(); for (int i = 0; i < num_slices; ++i) { QuantizeSlice(ctx->eigen_device<Device>(), ctx, input_tensor.template chip<1>(i), min_ranges(i), max_ranges(i), output_tensor.template chip<1>(i), &output_min_tensor->flat<float>()(i), &output_max_tensor->flat<float>()(i)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Secure tf.raw_ops.QuantizeV2 Validate size and shape of min_range and max_range Ensure axis is within input dims limits PiperOrigin-RevId: 387232799 Change-Id: I36975281f7b5758e9e31a8dcc73fe610ef456318'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) { int i; ut8 *directory_base; struct minidump_directory *entry; directory_base = obj->b->buf + obj->hdr->stream_directory_rva; sdb_num_set (obj->kv, "mdmp_directory.offset", obj->hdr->stream_directory_rva, 0); sdb_set (obj->kv, "mdmp_directory.format", "[4]E? " "(mdmp_stream_type)StreamType " "(mdmp_location_descriptor)Location", 0); /* Parse each entry in the directory */ for (i = 0; i < (int)obj->hdr->number_of_streams; i++) { entry = (struct minidump_directory *)(directory_base + (i * sizeof (struct minidump_directory))); r_bin_mdmp_init_directory_entry (obj, entry); } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10464 - oobread crash in mdmp (#10683)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps) { mutex_lock(&kvm->arch.vpit->pit_state.lock); memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state)); kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0); mutex_unlock(&kvm->arch.vpit->pit_state.lock); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'KVM: x86: Reload pit counters for all channels when restoring state Currently if userspace restores the pit counters with a count of 0 on channels 1 or 2 and the guest attempts to read the count on those channels, then KVM will perform a mod of 0 and crash. This will ensure that 0 values are converted to 65536 as per the spec. This is CVE-2015-7513. Signed-off-by: Andy Honig <ahonig@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: STATIC U8 * S_reghopmaybe3(U8* s, SSize_t off, const U8* lim) { PERL_ARGS_ASSERT_REGHOPMAYBE3; if (off >= 0) { while (off-- && s < lim) { /* XXX could check well-formedness here */ s += UTF8SKIP(s); } if (off >= 0) return NULL; } else { while (off++ && s > lim) { s--; if (UTF8_IS_CONTINUED(*s)) { while (s > lim && UTF8_IS_CONTINUATION(*s)) s--; } /* XXX could check well-formedness here */ } if (off <= 0) return NULL; } return s; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'PATCH [perl #123562] Regexp-matching "hangs" The regex engine got into an infinite loop because of the malformation. It is trying to back-up over a sequence of UTF-8 continuation bytes. But the character just before the sequence should be a start byte. If not, there is a malformation. I added a test to croak if that isn't the case so that it doesn't just infinitely loop. I did this also in the similar areas of regexec.c. Comments long ago added to the code suggested that we check for malformations in the vicinity of the new tests. But that was never done. These new tests should be good enough to prevent looping, anyway.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_F(QuantizedConv2DTest, Small) { const int stride = 1; 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 = 3; const int image_batch_count = 1; // The image data should always be able to represent zero, to allow a fast // implementation of border padding, so we set the min value to 0. const float image_min = 0.0f; const float image_max = 12.0f; // The image matrix is: // | 1 | 2 | 3 | 4 | // | 5 | 6 | 7 | 8 | // | 9 | 10 | 11 | 12 | Tensor image_float(DT_FLOAT, {image_batch_count, image_height, image_width, depth}); test::FillValues<float>(&image_float, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); Tensor image_quantized = FloatTensorToQuantized<quint8>(image_float, image_min, image_max); // The filter matrix is: // | 1 | 4 | 7 | // | 2 | 5 | 8 | // | 3 | 6 | 9 | const int filter_size = 3; const int filter_count = 1; const float filter_min = 1.0f; const float filter_max = 9.0f; Tensor filter_float(DT_FLOAT, {filter_size, filter_size, depth, filter_count}); test::FillValues<float>(&filter_float, {1, 4, 7, 2, 5, 8, 3, 6, 9}); Tensor filter_quantized = FloatTensorToQuantized<quint8>(filter_float, filter_min, filter_max); AddInputFromArray<quint8>(image_quantized.shape(), image_quantized.flat<quint8>()); AddInputFromArray<quint8>(filter_quantized.shape(), filter_quantized.flat<quint8>()); AddInputFromArray<float>(TensorShape({1}), {image_min}); AddInputFromArray<float>(TensorShape({1}), {image_max}); AddInputFromArray<float>(TensorShape({1}), {filter_min}); AddInputFromArray<float>(TensorShape({1}), {filter_max}); TF_ASSERT_OK(RunOpKernel()); // We're sliding the 3x3 filter across the 3x4 image, with accesses outside // the input set to zero because we're using the 'SAME' padding mode. // The calculations behind the expected output are: // (1*0)+(4*0)+(7*0)+(2*0)+(5*1)+(8*2)+(3*0)+(6*5)+(9*6)=105 // (1*0)+(4*0)+(7*0)+(2*1)+(5*2)+(8*3)+(3*5)+(6*6)+(9*7)=150 // (1*0)+(4*0)+(7*0)+(2*2)+(5*3)+(8*4)+(3*6)+(6*7)+(9*8)=183 // (1*0)+(4*0)+(7*0)+(2*3)+(5*4)+(8*0)+(3*7)+(6*8)+(9*0)=95 // (1*0)+(4*1)+(7*2)+(2*0)+(5*5)+(8*6)+(3*0)+(6*9)+(9*10)=235 // (1*1)+(4*2)+(7*3)+(2*5)+(5*6)+(8*7)+(3*9)+(6*10)+(9*11)=312 // (1*2)+(4*3)+(7*4)+(2*6)+(5*7)+(8*8)+(3*10)+(6*11)+(9*12)=357 // (1*3)+(4*4)+(7*0)+(2*7)+(5*8)+(8*0)+(3*11)+(6*12)+(9*0)=178 // (1*0)+(4*5)+(7*6)+(2*0)+(5*9)+(8*10)+(3*0)+(6*0)+(9*0)=187 // (1*5)+(4*6)+(7*7)+(2*9)+(5*10)+(8*11)+(3*0)+(6*0)+(9*0)=234 // (1*6)+(4*7)+(7*8)+(2*10)+(5*11)+(8*12)+(3*0)+(6*0)+(9*0)=261 // (1*7)+(4*11)+(7*0)+(2*8)+(5*12)+(8*0)+(3*0)+(6*0)+(9*0)=121 // This means we should end up with this matrix: // | 105 | 150 | 183 | 95 | // | 235 | 312 | 357 | 178 | // | 187 | 234 | 261 | 121 | const int expected_width = image_width; const int expected_height = image_height * filter_count; Tensor expected_float( DT_FLOAT, TensorShape({image_batch_count, expected_height, expected_width, filter_count})); test::FillValues<float>(&expected_float, {105, 150, 183, 95, 235, 312, 357, 178, 187, 234, 261, 121}); const Tensor& output_quantized = *GetOutput(0); const float output_min = GetOutput(1)->flat<float>()(0); const float output_max = GetOutput(2)->flat<float>()(0); Tensor output_float = QuantizedTensorToFloat<qint32>(output_quantized, output_min, output_max); test::ExpectTensorNear<float>(expected_float, output_float, 1.0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix undefined behavior in QuantizedConv2D Added more input validation and tests. Prior to this, we could get `nullptr` exceptions when attempting to access 0th elements of 0-sized inputs, leading to security vulnerability bugs. Also needed to modify `quantized_conv_ops_test.cc` for consistency. Previously the CPU kernel did technically support passing tensors of rank larger than 0 for min/max values. However, the XLA kernels do not. PiperOrigin-RevId: 445518507'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool Sampler::operator==(const Sampler &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->magFilter == other.magFilter && this->minFilter == other.minFilter && this->name == other.name && this->wrapS == other.wrapS && this->wrapT == other.wrapT; //this->wrapR == other.wrapR } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Do not expand file path since its not necessary for glTF asset path(URI) and for security reason(`wordexp`).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_fill_flex_info(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_group_desc *gdp = NULL; ext4_group_t flex_group_count; ext4_group_t flex_group; int groups_per_flex = 0; size_t size; int i; sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { sbi->s_log_groups_per_flex = 0; return 1; } /* We allocate both existing and potentially added groups */ flex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) + ((le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) + 1) << EXT4_DESC_PER_BLOCK_BITS(sb))) / groups_per_flex; size = flex_group_count * sizeof(struct flex_groups); sbi->s_flex_groups = ext4_kvzalloc(size, GFP_KERNEL); if (sbi->s_flex_groups == NULL) { ext4_msg(sb, KERN_ERR, "not enough memory for %u flex groups", flex_group_count); goto failed; } for (i = 0; i < sbi->s_groups_count; i++) { gdp = ext4_get_group_desc(sb, i, NULL); flex_group = ext4_flex_group(sbi, i); atomic_add(ext4_free_inodes_count(sb, gdp), &sbi->s_flex_groups[flex_group].free_inodes); atomic_add(ext4_free_group_clusters(sb, gdp), &sbi->s_flex_groups[flex_group].free_clusters); atomic_add(ext4_used_dirs_count(sb, gdp), &sbi->s_flex_groups[flex_group].used_dirs); } return 1; failed: return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ext4: fix undefined behavior in ext4_fill_flex_info() Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by zero when trying to mount a corrupted file system") fixes CVE-2009-4307 by performing a sanity check on s_log_groups_per_flex, since it can be set to a bogus value by an attacker. sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { ... } This patch fixes two potential issues in the previous commit. 1) The sanity check might only work on architectures like PowerPC. On x86, 5 bits are used for the shifting amount. That means, given a large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36 is essentially 1 << 4 = 16, rather than 0. This will bypass the check, leaving s_log_groups_per_flex and groups_per_flex inconsistent. 2) The sanity check relies on undefined behavior, i.e., oversized shift. A standard-confirming C compiler could rewrite the check in unexpected ways. Consider the following equivalent form, assuming groups_per_flex is unsigned for simplicity. groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex == 0 || groups_per_flex == 1) { We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will completely optimize away the check groups_per_flex == 0, leaving the patched code as vulnerable as the original. GCC keeps the check, but there is no guarantee that future versions will do the same. Signed-off-by: Xi Wang <xi.wang@gmail.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> Cc: stable@vger.kernel.org'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int regcomp(regex_t *preg, const char *pattern, int cflags) { conopt_t globopts; globopts.nested_negative_tags = !(cflags & (REG_NFA | REG_REGLESS)); globopts.FFlag = true; globopts.backward = cflags & REG_BACKWARD; globopts.stadfa = cflags & REG_STADFA; Msg msg; Opt opts(globopts, msg); opts.set_subhistories((cflags & REG_SUBHIST) != 0); opts.set_autotags((cflags & REG_AUTOTAGS) != 0); opts.set_posix_syntax(true); opts.set_posix_semantics((cflags & REG_LEFTMOST) == 0); const opt_t *opt = opts.snapshot(); preg->flags = cflags; const AST *a = parse(pattern); preg->rmgr = new RangeMgr; ASTRule ar(a, new SemAct(NOWHERE)); std::vector<ASTRule> arv; arv.push_back(ar); RESpec re(arv, opt, msg, *preg->rmgr); find_fixed_tags(re); insert_default_tags(re); nfa_t *nfa = new nfa_t(re); nfa_t *nfa0 = NULL; if (cflags & REG_BACKWARD) { conopt_t globopts0; globopts0.FFlag = true; Opt opts0(globopts0, msg); const opt_t *opt0 = opts0.snapshot(); RESpec re0(arv, opt0, msg, *preg->rmgr); nfa0 = new nfa_t(re0); delete opt0; } dfa_t *dfa = NULL; rldfa_t *rldfa = NULL; if (cflags & REG_NFA) { if ((cflags & REG_TRIE) && (cflags & REG_LEFTMOST)) { preg->simctx = new lzsimctx_t(*nfa, nfa0, preg->re_nsub, cflags); } else if (cflags & REG_TRIE) { preg->simctx = new pzsimctx_t(*nfa, nfa0, preg->re_nsub, cflags); } else if (cflags & REG_LEFTMOST) { preg->simctx = new lsimctx_t(*nfa, nfa0, preg->re_nsub, cflags); } else if (cflags & REG_KUKLEWICZ) { preg->simctx = new ksimctx_t(*nfa, nfa0, preg->re_nsub, cflags); } else { preg->simctx = new psimctx_t(*nfa, nfa0, preg->re_nsub, cflags); } } else { preg->char2class = new size_t[256]; split_charset(re); for (uint32_t i = 1, j = 0; i < re.charset.size(); ++i) { for (; j < re.charset[i]; ++j) { preg->char2class[j] = i - 1; } } dfa = new dfa_t(*nfa, Rule::NONE, Rule::NONE); if (cflags & REG_REGLESS) { DASSERT((cflags & REG_STADFA) == 0); rldfa = new rldfa_t(*nfa, *dfa, opt, cflags); opt = NULL; // transfer options ownership to RLDFA } else { determinization(*nfa, *dfa, opt, msg, ""); cutoff_dead_rules(*dfa, opt, "", msg); insert_fallback_tags(opt, *dfa); compact_and_optimize_tags(opt, *dfa); } if (cflags & REG_TSTRING) { // T-string does not need intermediate storage for tag values. } else if (cflags & REG_SUBHIST) { const size_t nlists = (cflags & REG_REGLESS) ? dfa->tags.size() : static_cast<size_t>(dfa->maxtagver + 1); preg->regtrie = new regoff_trie_t(nlists); } else { preg->regs = new regoff_t[dfa->maxtagver + 1]; } } preg->nfa = nfa; preg->dfa = dfa; preg->rldfa = rldfa; DASSERT(nfa->rules.size() == 1); preg->re_nsub = nfa->rules[0].ncap + 1; preg->re_ntag = nfa->tags.size(); if (cflags & REG_TSTRING) { // T-string is stored in RE (reallocated on each regtstring() call if // needed), and the user gets an immutable view of it (const ref). tstring_t &ts = preg->tstring; ts.capacity = 256; ts.string = new tchar_t[ts.capacity]; ts.length = 0; } else if (cflags & REG_SUBHIST) { // Allocated on every call to regparse() and returned to the user. } else { // Allocated by the user. } delete opt; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Limit maximum allowed NFA and DFA size. Instead of failing with an out of memory exception or crashing with a stack overflow, emit an error message and exit. This is a partial fix for bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc", where re2c hit stack overflow on a counted repetition regexp with high upper bound. The patch adds the following limits: 1. the number of NFA states 2. NFA depth (maximum length of a non-looping path from start to end) 3. the number of DFA states 3. total DFA size (sum total of all NFA substates in all DFA states) There are tests for the first three limits, but not for the DFA size as all examples that trigger this behavior take a long time to finish (a few seconds), which increases test run time almost twice.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: exo_open_launch_desktop_file (const gchar *arg) { #ifdef HAVE_GIO_UNIX GFile *gfile; gchar *contents; gsize length; gboolean result; GKeyFile *key_file; GDesktopAppInfo *appinfo; /* try to open a file from the arguments */ gfile = g_file_new_for_commandline_arg (arg); if (G_UNLIKELY (gfile == NULL)) return FALSE; /* load the contents of the file */ result = g_file_load_contents (gfile, NULL, &contents, &length, NULL, NULL); g_object_unref (G_OBJECT (gfile)); if (G_UNLIKELY (!result || length == 0)) return FALSE; /* create the key file */ key_file = g_key_file_new (); result = g_key_file_load_from_data (key_file, contents, length, G_KEY_FILE_NONE, NULL); g_free (contents); if (G_UNLIKELY (!result)) { g_key_file_free (key_file); return FALSE; } /* create the appinfo */ appinfo = g_desktop_app_info_new_from_keyfile (key_file); g_key_file_free (key_file); if (G_UNLIKELY (appinfo == NULL)) return FALSE; /* try to launch a (non-hidden) desktop file */ if (G_LIKELY (!g_desktop_app_info_get_is_hidden (appinfo))) result = g_app_info_launch (G_APP_INFO (appinfo), NULL, NULL, NULL); else result = FALSE; g_object_unref (G_OBJECT (appinfo)); #ifndef NDEBUG g_debug ("launching desktop file %s", result ? "succeeded" : "failed"); #endif return result; #else /* !HAVE_GIO_UNIX */ g_critical (_("Launching desktop files is not supported when %s is compiled " "without GIO-Unix features."), g_get_prgname ()); return FALSE; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'exo-open : Only execute local .desktop files Issue #85 (Backported cc047717) CVE-2022-32278 This patch prevents executing possibly malicious .desktop files from online sources (ftp://, http:// etc.). Original patch authored by Alexander Schwinn <alexxcons@xfce.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void process_EXIF (unsigned char * ExifSection, int length) { int FirstOffset; Clear_EXIF(); if (ShowTags){ printf("Exif header %u bytes long\n",length); } { // Check the EXIF header component static uchar ExifHeader[] = "Exif\0\0"; if (memcmp(ExifSection+2, ExifHeader,6)){ ErrNonfatal("Incorrect Exif header",0,0); return; } } if (memcmp(ExifSection+8,"II",2) == 0){ if (ShowTags) printf("Exif section in Intel order\n"); MotorolaOrder = 0; }else{ if (memcmp(ExifSection+8,"MM",2) == 0){ if (ShowTags) printf("Exif section in Motorola order\n"); MotorolaOrder = 1; }else{ ErrNonfatal("Invalid Exif alignment marker.",0,0); return; } } // Check the next value for correctness. if (Get16u(ExifSection+10) != 0x2a){ ErrNonfatal("Invalid Exif start (1)",0,0); return; } FirstOffset = (int)Get32u(ExifSection+12); if (FirstOffset < 8 || FirstOffset > 16){ if (FirstOffset < 16 || FirstOffset > length-16 || length < 16){ ErrNonfatal("invalid offset for first Exif IFD value",0,0); return; } // Usually set to 8, but other values valid too. ErrNonfatal("Suspicious offset of first Exif IFD value",0,0); } DirWithThumbnailPtrs = NULL; // First directory starts 16 bytes in. All offset are relative to 8 bytes in. ProcessExifDir(ExifSection+8+FirstOffset, ExifSection+8, length-8, 0); ImageInfo.ThumbnailAtEnd = ImageInfo.ThumbnailOffset >= ImageInfo.LargestExifOffset ? TRUE : FALSE; if (DumpExifMap){ int a,b; printf("Map: %05d- End of exif\n",length-8); for (a=0;a<length-8;a+= 10){ printf("Map: %05d ",a); for (b=0;b<10;b++) printf(" %02x",*(ExifSection+8+a+b)); printf("\n"); } } // Compute the CCD width, in millimeters. if (FocalplaneXRes != 0 && ExifImageWidth != 0){ // Note: With some cameras, its not possible to compute this correctly because // they don't adjust the indicated focal plane resolution units when using less // than maximum resolution, so the CCDWidth value comes out too small. Nothing // that Jhad can do about it - its a camera problem. ImageInfo.CCDWidth = (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes); if (ImageInfo.FocalLength && ImageInfo.FocalLength35mmEquiv == 0){ // Compute 35 mm equivalent focal length based on sensor geometry if we haven't // already got it explicitly from a tag. ImageInfo.FocalLength35mmEquiv = (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*36 + 0.5); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Make pointer range checks more consistent. Also twiddle the unused floating point print code (not used in real exif files), but fuzz testing hits it. New code is equivalent but doesn't cause bus error (don't understand why, but this is all a very bogus thing anyway, just trying to avoid fuzz testing hits.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int nft_parse_register_load(const struct nlattr *attr, u8 *sreg, u32 len) { u32 reg; int err; reg = nft_parse_register(attr); err = nft_validate_register_load(reg, len); if (err < 0) return err; *sreg = reg; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: nf_tables: validate registers coming from userspace. Bail out in case userspace uses unsupported registers. Fixes: 49499c3e6e18 ("netfilter: nf_tables: switch registers to 32 bit addressing") Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int unshare_userns(unsigned long unshare_flags, struct cred **new_cred) { struct cred *cred; if (!(unshare_flags & CLONE_NEWUSER)) return 0; cred = prepare_creds(); if (!cred) return -ENOMEM; *new_cred = cred; return create_user_ns(cred); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'userns: unshare_userns(&cred) should not populate cred on failure unshare_userns(new_cred) does *new_cred = prepare_creds() before create_user_ns() which can fail. However, the caller expects that it doesn't need to take care of new_cred if unshare_userns() fails. We could change the single caller, sys_unshare(), but I think it would be more clean to avoid the side effects on failure, so with this patch unshare_userns() does put_cred() itself and initializes *new_cred only if create_user_ns() succeeeds. Cc: stable@vger.kernel.org Signed-off-by: Oleg Nesterov <oleg@redhat.com> Reviewed-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock_iocb *siocb = kiocb_to_siocb(kiocb); struct sock *sk = sock->sk; struct netlink_sock *nlk = nlk_sk(sk); struct sockaddr_nl *addr = msg->msg_name; u32 dst_pid; u32 dst_group; struct sk_buff *skb; int err; struct scm_cookie scm; if (msg->msg_flags&MSG_OOB) return -EOPNOTSUPP; if (NULL == siocb->scm) siocb->scm = &scm; err = scm_send(sock, msg, siocb->scm, true); if (err < 0) return err; if (msg->msg_namelen) { err = -EINVAL; if (addr->nl_family != AF_NETLINK) goto out; dst_pid = addr->nl_pid; dst_group = ffs(addr->nl_groups); err = -EPERM; if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND)) goto out; } else { dst_pid = nlk->dst_pid; dst_group = nlk->dst_group; } if (!nlk->pid) { err = netlink_autobind(sock); if (err) goto out; } err = -EMSGSIZE; if (len > sk->sk_sndbuf - 32) goto out; err = -ENOBUFS; skb = alloc_skb(len, GFP_KERNEL); if (skb == NULL) goto out; NETLINK_CB(skb).pid = nlk->pid; NETLINK_CB(skb).dst_group = dst_group; memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred)); err = -EFAULT; if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) { kfree_skb(skb); goto out; } err = security_netlink_send(sk, skb); if (err) { kfree_skb(skb); goto out; } if (dst_group) { atomic_inc(&skb->users); netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL); } err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT); out: scm_destroy(siocb->scm); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'netlink: fix possible spoofing from non-root processes Non-root user-space processes can send Netlink messages to other processes that are well-known for being subscribed to Netlink asynchronous notifications. This allows ilegitimate non-root process to send forged messages to Netlink subscribers. The userspace process usually verifies the legitimate origin in two ways: a) Socket credentials. If UID != 0, then the message comes from some ilegitimate process and the message needs to be dropped. b) Netlink portID. In general, portID == 0 means that the origin of the messages comes from the kernel. Thus, discarding any message not coming from the kernel. However, ctnetlink sets the portID in event messages that has been triggered by some user-space process, eg. conntrack utility. So other processes subscribed to ctnetlink events, eg. conntrackd, know that the event was triggered by some user-space action. Neither of the two ways to discard ilegitimate messages coming from non-root processes can help for ctnetlink. This patch adds capability validation in case that dst_pid is set in netlink_sendmsg(). This approach is aggressive since existing applications using any Netlink bus to deliver messages between two user-space processes will break. Note that the exception is NETLINK_USERSOCK, since it is reserved for netlink-to-netlink userspace communication. Still, if anyone wants that his Netlink bus allows netlink-to-netlink userspace, then they can set NL_NONROOT_SEND. However, by default, I don't think it makes sense to allow to use NETLINK_ROUTE to communicate two processes that are sending no matter what information that is not related to link/neighbouring/routing. They should be using NETLINK_USERSOCK instead for that. Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt( const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk, const uint256 &cmu ) { auto pt = AttemptSaplingEncDecryption(ciphertext, ivk, epk); if (!pt) { return boost::none; } // Deserialize from the plaintext CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pt.get(); SaplingNotePlaintext ret; ss >> ret; assert(ss.size() == 0); uint256 pk_d; if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) { return boost::none; } 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; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-755', 'CWE-787'], 'message': 'Ignore exceptions when deserializing note plaintexts'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, COUNTER iteration, bool cached, int datalink) { uint32_t pkt_len = pkthdr->caplen; u_char *packet = *pktdata; ipv4_hdr_t *ip_hdr = NULL; ipv6_hdr_t *ip6_hdr = NULL; uint32_t src_ip, dst_ip; uint32_t src_ip_orig, dst_ip_orig; uint32_t _U_ vlan_offset; uint16_t ether_type; uint32_t l2offset; uint32_t l2len; int res; res = get_l2len_protocol(packet, pkt_len, datalink, &ether_type, &l2len, &l2offset, &vlan_offset); if (res < 0) return res; packet += l2offset; l2len -= l2offset; pkt_len -= l2offset; assert(l2len > 0); switch (ether_type) { case ETHERTYPE_IP: if (pkt_len < (bpf_u_int32)(l2len + sizeof(ipv4_hdr_t))) { dbgx(1, "IP packet too short for Unique IP feature: %u", pkthdr->caplen); return -1; } ip_hdr = (ipv4_hdr_t *)(packet + l2len); src_ip_orig = src_ip = ntohl(ip_hdr->ip_src.s_addr); dst_ip_orig = dst_ip = ntohl(ip_hdr->ip_dst.s_addr); break; case ETHERTYPE_IP6: if (pkt_len < (bpf_u_int32)(l2len + sizeof(ipv6_hdr_t))) { dbgx(1, "IP6 packet too short for Unique IP feature: %u", pkthdr->caplen); return -1; } ip6_hdr = (ipv6_hdr_t *)(packet + l2len); src_ip_orig = src_ip = ntohl(ip6_hdr->ip_src.__u6_addr.__u6_addr32[3]); dst_ip_orig = dst_ip = ntohl(ip6_hdr->ip_dst.__u6_addr.__u6_addr32[3]); break; default: return -1; /* non-IP or packet too short */ } dbgx(2, "Layer 3 protocol type is: 0x%04x", ether_type); /* swap src/dst IP's in a manner that does not affect CRC */ if ((!cached && dst_ip > src_ip) || (cached && (dst_ip - iteration) > (src_ip - 1 - iteration))) { if (cached) { --src_ip; ++dst_ip; } else { src_ip -= iteration; dst_ip += iteration; } /* CRC compensations for wrap conditions */ if (src_ip > src_ip_orig && dst_ip > dst_ip_orig) { dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): before(1) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); --src_ip; dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): after(1) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); } else if (dst_ip < dst_ip_orig && src_ip < src_ip_orig) { dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): before(2) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); ++dst_ip; dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): after(2) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); } } else { if (cached) { ++src_ip; --dst_ip; } else { src_ip += iteration; dst_ip -= iteration; } /* CRC compensations for wrap conditions */ if (dst_ip > dst_ip_orig && src_ip > src_ip_orig) { dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): before(1) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip); --dst_ip; dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): after(1) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip); } else if (src_ip < src_ip_orig && dst_ip < dst_ip_orig) { dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): before(2) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip); ++src_ip; dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): after(2) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip); } } dbgx(1, "(" COUNTER_SPEC "): final src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); switch (ether_type) { case ETHERTYPE_IP: ip_hdr->ip_src.s_addr = htonl(src_ip); ip_hdr->ip_dst.s_addr = htonl(dst_ip); break; case ETHERTYPE_IP6: ip6_hdr->ip_src.__u6_addr.__u6_addr32[3] = htonl(src_ip); ip6_hdr->ip_dst.__u6_addr.__u6_addr32[3] = htonl(dst_ip); break; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Bug #677 - fixes for tcpprep tree'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPML_TAGGED_POLICY_Unmarshal(TPML_TAGGED_POLICY *target, BYTE **buffer, INT32 *size) { TPM_RC rc = TPM_RC_SUCCESS; UINT32 i; if (rc == TPM_RC_SUCCESS) { rc = UINT32_Unmarshal(&target->count, buffer, size); } if (rc == TPM_RC_SUCCESS) { if (target->count > MAX_TAGGED_POLICIES) { rc = TPM_RC_SIZE; } } for (i = 0 ; (rc == TPM_RC_SUCCESS) && (i < target->count) ; i++) { rc = TPMS_TAGGED_POLICY_Unmarshal(&target->policies[i], buffer, size); } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size Reset the buffer size indicator in a TPM2B type of buffer after it failed the test for the maximum buffer size it allows. This prevents having bad buffer sizes in memory that can come to haunt us when writing the volatile state for example. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPM2B_Unmarshal(TPM2B *target, UINT16 targetSize, BYTE **buffer, INT32 *size) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = UINT16_Unmarshal(&target->size, buffer, size); } if (rc == TPM_RC_SUCCESS) { if (target->size > targetSize) { rc = TPM_RC_SIZE; } } if (rc == TPM_RC_SUCCESS) { rc = Array_Unmarshal(target->buffer, target->size, buffer, size); } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size Reset the buffer size indicator in a TPM2B type of buffer after it failed the test for the maximum buffer size it allows. This prevents having bad buffer sizes in memory that can come to haunt us when writing the volatile state for example. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ quantum_info=(QuantumInfo *) NULL; clone_info=(ImageInfo *) NULL; if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image)) goto MATLAB_KO; filepos += MATLAB_HDR.ObjectSize + 4 + 4; clone_info=CloneImageInfo(image_info); image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double)); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); END_OF_READING: if (clone_info) clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/553'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start) { int res, bytes, i, indexes, index_bytes, ids; long long *index, start, end; struct squashfs_xattr_table id_table; TRACE("read_xattrs_from_disk\n"); if(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK) return SQUASHFS_INVALID_BLK; /* * Read xattr id table, containing start of xattr metadata and the * number of xattrs in the file system */ res = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table), &id_table); if(res == 0) return 0; SQUASHFS_INSWAP_XATTR_TABLE(&id_table); if(flag) { /* * id_table.xattr_table_start stores the start of the compressed xattr * * metadata blocks. This by definition is also the end of the previous * filesystem table - the id lookup table. */ *table_start = id_table.xattr_table_start; return id_table.xattr_ids; } /* * Allocate and read the index to the xattr id table metadata * blocks */ ids = id_table.xattr_ids; xattr_table_start = id_table.xattr_table_start; index_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids); indexes = SQUASHFS_XATTR_BLOCKS(ids); index = malloc(index_bytes); if(index == NULL) MEM_ERROR(); res = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table), index_bytes, index); if(res ==0) goto failed1; SQUASHFS_INSWAP_LONG_LONGS(index, indexes); /* * Allocate enough space for the uncompressed xattr id table, and * read and decompress it */ bytes = SQUASHFS_XATTR_BYTES(ids); xattr_ids = malloc(bytes); if(xattr_ids == NULL) MEM_ERROR(); for(i = 0; i < indexes; i++) { int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE : bytes & (SQUASHFS_METADATA_SIZE - 1); int length = read_block(fd, index[i], NULL, expected, ((unsigned char *) xattr_ids) + (i * SQUASHFS_METADATA_SIZE)); TRACE("Read xattr id table block %d, from 0x%llx, length " "%d\n", i, index[i], length); if(length == 0) { ERROR("Failed to read xattr id table block %d, " "from 0x%llx, length %d\n", i, index[i], length); goto failed2; } } /* * Read and decompress the xattr metadata * * Note the first xattr id table metadata block is immediately after * the last xattr metadata block, so we can use index[0] to work out * the end of the xattr metadata */ start = xattr_table_start; end = index[0]; for(i = 0; start < end; i++) { int length; xattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE); if(xattrs == NULL) MEM_ERROR(); /* store mapping from location of compressed block in fs -> * location of uncompressed block in memory */ save_xattr_block(start, i * SQUASHFS_METADATA_SIZE); length = read_block(fd, start, &start, 0, ((unsigned char *) xattrs) + (i * SQUASHFS_METADATA_SIZE)); TRACE("Read xattr block %d, length %d\n", i, length); if(length == 0) { ERROR("Failed to read xattr block %d\n", i); goto failed3; } /* * If this is not the last metadata block in the xattr metadata * then it should be SQUASHFS_METADATA_SIZE in size. * Note, we can't use expected in read_block() above for this * because we don't know if this is the last block until * after reading. */ if(start != end && length != SQUASHFS_METADATA_SIZE) { ERROR("Xattr block %d should be %d bytes in length, " "it is %d bytes\n", i, SQUASHFS_METADATA_SIZE, length); goto failed3; } } /* swap if necessary the xattr id entries */ for(i = 0; i < ids; i++) SQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]); free(index); return ids; failed3: free(xattrs); failed2: free(xattr_ids); failed1: free(index); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6 Add more filesystem table sanity checks to Unsquashfs-4 and also properly fix CVE-2015-4645 and CVE-2015-4646. The CVEs were raised due to Unsquashfs having variable oveflow and stack overflow in a number of vulnerable functions. The suggested patch only "fixed" one such function and fixed it badly, and so it was buggy and introduced extra bugs! The suggested patch was not only buggy, but, it used the essentially wrong approach too. It was "fixing" the symptom but not the cause. The symptom is wrong values causing overflow, the cause is filesystem corruption. This corruption should be detected and the filesystem rejected *before* trying to allocate memory. This patch applies the following fixes: 1. The filesystem super-block tables are checked, and the values must match across the filesystem. This will trap corrupted filesystems created by Mksquashfs. 2. The maximum (theorectical) size the filesystem tables could grow to, were analysed, and some variables were increased from int to long long. This analysis has been added as comments. 3. Stack allocation was removed, and a shared buffer (which is checked and increased as necessary) is used to read the table indexes. Signed-off-by: Phillip Lougher <phillip@squashfs.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) { packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL, packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0, packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL, packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0, packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL, packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0, packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL, packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL, packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL, packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0, packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-787'], 'message': 'Fixed use after free caused by dangling pointer * This fix also improved RCE Injection detection Signed-off-by: Toni Uhlig <matzeton@googlemail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int logi_dj_ll_raw_request(struct hid_device *hid, unsigned char reportnum, __u8 *buf, size_t count, unsigned char report_type, int reqtype) { struct dj_device *djdev = hid->driver_data; struct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev; u8 *out_buf; int ret; if (buf[0] != REPORT_TYPE_LEDS) return -EINVAL; out_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC); if (!out_buf) return -ENOMEM; if (count < DJREPORT_SHORT_LENGTH - 2) count = DJREPORT_SHORT_LENGTH - 2; out_buf[0] = REPORT_ID_DJ_SHORT; out_buf[1] = djdev->device_index; memcpy(out_buf + 2, buf, count); ret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf, DJREPORT_SHORT_LENGTH, report_type, reqtype); kfree(out_buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'HID: logitech: fix bounds checking on LED report size The check on report size for REPORT_TYPE_LEDS in logi_dj_ll_raw_request() is wrong; the current check doesn't make any sense -- the report allocated by HID core in hid_hw_raw_request() can be much larger than DJREPORT_SHORT_LENGTH, and currently logi_dj_ll_raw_request() doesn't handle this properly at all. Fix the check by actually trimming down the report size properly if it is too large. Cc: stable@vger.kernel.org Reported-by: Ben Hawkes <hawkes@google.com> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sasl_handle_login(struct sasl_session *const restrict p, struct user *const u, struct myuser *mu) { bool was_killed = false; // Find the account if necessary if (! mu) { if (! *p->authzeid) { (void) slog(LG_INFO, "%s: session for '%s' without an authzeid (BUG)", MOWGLI_FUNC_NAME, u->nick); (void) notice(saslsvs->nick, u->nick, LOGIN_CANCELLED_STR); return false; } if (! (mu = myuser_find_uid(p->authzeid))) { if (*p->authzid) (void) notice(saslsvs->nick, u->nick, "Account %s dropped; login cancelled", p->authzid); else (void) notice(saslsvs->nick, u->nick, "Account dropped; login cancelled"); return false; } } // If the user is already logged in, and not to the same account, log them out first if (u->myuser && u->myuser != mu) { if (is_soper(u->myuser)) (void) logcommand_user(saslsvs, u, CMDLOG_ADMIN, "DESOPER: \2%s\2 as \2%s\2", u->nick, entity(u->myuser)->name); (void) logcommand_user(saslsvs, u, CMDLOG_LOGIN, "LOGOUT"); if (! (was_killed = ircd_on_logout(u, entity(u->myuser)->name))) { mowgli_node_t *n; MOWGLI_ITER_FOREACH(n, u->myuser->logins.head) { if (n->data == u) { (void) mowgli_node_delete(n, &u->myuser->logins); (void) mowgli_node_free(n); break; } } u->myuser = NULL; } } // If they were not killed above, log them in now if (! was_killed) { if (u->myuser != mu) { // If they're not logged in, or logging in to a different account, do a full login (void) myuser_login(saslsvs, u, mu, false); (void) logcommand_user(saslsvs, u, CMDLOG_LOGIN, "LOGIN (%s)", p->mechptr->name); } else { // Otherwise, just update login time ... mu->lastlogin = CURRTIME; (void) logcommand_user(saslsvs, u, CMDLOG_LOGIN, "REAUTHENTICATE (%s)", p->mechptr->name); } } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287', 'CWE-288'], 'message': 'saslserv/main: Track EID we're pending login to The existing model does not remember that we've sent a SVSLOGIN for a given SASL session, and simply assumes that if a client is introduced with a SASL session open, that session must have succeeded. The security of this approach requires ircd to implicitly abort SASL sessions on client registration. This also means that if a client successfully authenticates and then does something else its pending login is forgotten about, even though a SVSLOGIN has been sent for it, and the ircd is going to think it's logged in. This change removes the dependency on ircd's state machine by keeping explicit track of the pending login, i.e. the one we've most recently sent a SVSLOGIN for. The next commit will ensure that a client abort (even an implicit one) doesn't blow that information away.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* ctx) override { const Tensor& gradient = ctx->input(0); const Tensor& input = ctx->input(1); Tensor* input_backprop = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &input_backprop)); OP_REQUIRES( ctx, axis_ >= -1, errors::InvalidArgument("Axis must be at least -1. Found ", axis_)); OP_REQUIRES(ctx, (axis_ == -1 || axis_ < input.shape().dims()), errors::InvalidArgument( "Axis should be -1 or 0 or a positive value less than ", input.shape().dims(), "but given axis value was ", axis_)); OP_REQUIRES( ctx, input.IsSameSize(gradient), errors::InvalidArgument("gradient and input must be the same size")); const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_); const Tensor& input_min_tensor = ctx->input(2); OP_REQUIRES(ctx, input_min_tensor.dims() == 0 || input_min_tensor.dims() == 1, errors::InvalidArgument( "Input min tensor must have dimension 1. Recieved ", input_min_tensor.dims(), ".")); const Tensor& input_max_tensor = ctx->input(3); OP_REQUIRES(ctx, input_max_tensor.dims() == 0 || input_max_tensor.dims() == 1, errors::InvalidArgument( "Input max tensor must have dimension 1. Recieved ", input_max_tensor.dims(), ".")); if (axis_ != -1) { OP_REQUIRES( ctx, input_min_tensor.dim_size(0) == depth, errors::InvalidArgument("min has incorrect size, expected ", depth, " was ", input_min_tensor.dim_size(0))); OP_REQUIRES( ctx, input_max_tensor.dim_size(0) == depth, errors::InvalidArgument("max has incorrect size, expected ", depth, " was ", input_max_tensor.dim_size(0))); } TensorShape min_max_shape(input_min_tensor.shape()); Tensor* input_min_backprop; OP_REQUIRES_OK(ctx, ctx->allocate_output(1, min_max_shape, &input_min_backprop)); Tensor* input_max_backprop; OP_REQUIRES_OK(ctx, ctx->allocate_output(2, min_max_shape, &input_max_backprop)); if (axis_ == -1) { functor::QuantizeAndDequantizeOneScaleGradientFunctor<Device, T> f; f(ctx->eigen_device<Device>(), gradient.template flat<T>(), input.template flat<T>(), input_min_tensor.scalar<T>(), input_max_tensor.scalar<T>(), input_backprop->template flat<T>(), input_min_backprop->template scalar<T>(), input_max_backprop->template scalar<T>()); } else { functor::QuantizeAndDequantizePerChannelGradientFunctor<Device, T> f; f(ctx->eigen_device<Device>(), gradient.template flat_inner_outer_dims<T, 3>(axis_ - 1), input.template flat_inner_outer_dims<T, 3>(axis_ - 1), &input_min_tensor, &input_max_tensor, input_backprop->template flat_inner_outer_dims<T, 3>(axis_ - 1), input_min_backprop->template flat<T>(), input_max_backprop->template flat<T>()); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Fix tf.raw_ops.QuantizeAndDequantizeV4Grad vulnerability with invalid input_min or input_max. Check that argument is actually a scalar before treating it as such. PiperOrigin-RevId: 445198280'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int needs_empty_write(sector_t block, struct inode *inode) { int error; struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 }; bh_map.b_size = 1 << inode->i_blkbits; error = gfs2_block_map(inode, block, &bh_map, 0); if (unlikely(error)) return error; return !buffer_mapped(&bh_map); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <bmarzins@redhat.com> Signed-off-by: Steven Whitehouse <swhiteho@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* ctx) override { const Tensor* hypothesis_indices; const Tensor* hypothesis_values; const Tensor* hypothesis_shape; const Tensor* truth_indices; const Tensor* truth_values; const Tensor* truth_shape; OP_REQUIRES_OK(ctx, ctx->input("hypothesis_indices", &hypothesis_indices)); OP_REQUIRES_OK(ctx, ctx->input("hypothesis_values", &hypothesis_values)); OP_REQUIRES_OK(ctx, ctx->input("hypothesis_shape", &hypothesis_shape)); OP_REQUIRES_OK(ctx, ctx->input("truth_indices", &truth_indices)); OP_REQUIRES_OK(ctx, ctx->input("truth_values", &truth_values)); OP_REQUIRES_OK(ctx, ctx->input("truth_shape", &truth_shape)); OP_REQUIRES_OK( ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values, *hypothesis_shape, *truth_indices, *truth_values, *truth_shape)); TensorShape hypothesis_st_shape; OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape( hypothesis_shape->vec<int64_t>().data(), hypothesis_shape->NumElements(), &hypothesis_st_shape)); TensorShape truth_st_shape; OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape( truth_shape->vec<int64_t>().data(), truth_shape->NumElements(), &truth_st_shape)); // Assume indices are sorted in row-major order. std::vector<int64_t> sorted_order(truth_st_shape.dims()); std::iota(sorted_order.begin(), sorted_order.end(), 0); sparse::SparseTensor hypothesis; OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create( *hypothesis_indices, *hypothesis_values, hypothesis_st_shape, sorted_order, &hypothesis)); sparse::SparseTensor truth; OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create( *truth_indices, *truth_values, truth_st_shape, sorted_order, &truth)); // Group dims 0, 1, ..., RANK - 1. The very last dim is assumed // to store the variable length sequences. std::vector<int64_t> group_dims(truth_st_shape.dims() - 1); std::iota(group_dims.begin(), group_dims.end(), 0); TensorShape output_shape; for (int d = 0; d < static_cast<int>(group_dims.size()); ++d) { output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d), truth_st_shape.dim_size(d))); } const auto output_elements = output_shape.num_elements(); OP_REQUIRES( ctx, output_elements > 0, errors::InvalidArgument("Got output shape ", output_shape.DebugString(), " which has 0 elements")); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output("output", output_shape, &output)); auto output_t = output->flat<float>(); output_t.setZero(); std::vector<int64_t> output_strides(output_shape.dims()); output_strides[output_shape.dims() - 1] = 1; for (int d = output_shape.dims() - 2; d >= 0; --d) { output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1); } auto hypothesis_grouper = hypothesis.group(group_dims); auto truth_grouper = truth.group(group_dims); auto hypothesis_iter = hypothesis_grouper.begin(); auto truth_iter = truth_grouper.begin(); auto cmp = std::equal_to<T>(); while (hypothesis_iter != hypothesis_grouper.end() && truth_iter != truth_grouper.end()) { sparse::Group truth_i = *truth_iter; sparse::Group hypothesis_j = *hypothesis_iter; std::vector<int64_t> g_truth = truth_i.group(); std::vector<int64_t> g_hypothesis = hypothesis_j.group(); auto truth_seq = truth_i.values<T>(); auto hypothesis_seq = hypothesis_j.values<T>(); if (g_truth == g_hypothesis) { auto loc = std::inner_product(g_truth.begin(), g_truth.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require in writing to outside of " "the buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = gtl::LevenshteinDistance<T>(truth_seq, hypothesis_seq, cmp); if (normalize_) output_t(loc) /= truth_seq.size(); ++hypothesis_iter; ++truth_iter; } else if (g_truth > g_hypothesis) { // zero-length truth auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require in writing to outside of " "the buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = hypothesis_seq.size(); if (normalize_ && output_t(loc) != 0.0f) { output_t(loc) = std::numeric_limits<float>::infinity(); } ++hypothesis_iter; } else { // zero-length hypothesis auto loc = std::inner_product(g_truth.begin(), g_truth.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require in writing to outside of " "the buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = (normalize_) ? 1.0 : truth_seq.size(); ++truth_iter; } } while (hypothesis_iter != hypothesis_grouper.end()) { // zero-length truths sparse::Group hypothesis_j = *hypothesis_iter; std::vector<int64_t> g_hypothesis = hypothesis_j.group(); auto hypothesis_seq = hypothesis_j.values<T>(); auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require in writing to outside of the " "buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = hypothesis_seq.size(); if (normalize_ && output_t(loc) != 0.0f) { output_t(loc) = std::numeric_limits<float>::infinity(); } ++hypothesis_iter; } while (truth_iter != truth_grouper.end()) { // missing hypotheses sparse::Group truth_i = *truth_iter; std::vector<int64_t> g_truth = truth_i.group(); auto truth_seq = truth_i.values<T>(); auto loc = std::inner_product(g_truth.begin(), g_truth.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require in writing to outside of the " "buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = (normalize_) ? 1.0 : truth_seq.size(); ++truth_iter; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix tf.raw_ops.EditDistance vulnerability with negative indices. Check that indices are non-negative. Fix several identical code sites. Clean up grammar in error message. PiperOrigin-RevId: 445442017'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int Lua::handle_script_request(struct mg_connection *conn, const struct mg_request_info *request_info, char *script_path) { char buf[64], key[64], ifname[MAX_INTERFACE_NAME_LEN]; char *_cookies, user[64] = { '\0' }, outbuf[FILENAME_MAX]; AddressTree ptree; int rc; if(!L) return(-1); luaL_openlibs(L); /* Load base libraries */ lua_register_classes(L, true); /* Load custom classes */ lua_pushlightuserdata(L, (char*)conn); lua_setglobal(L, CONST_HTTP_CONN); /* Put the GET params into the environment */ lua_newtable(L); if(request_info->query_string != NULL) { char *query_string = strdup(request_info->query_string); if(query_string) { char *where; char *tok; // ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string); tok = strtok_r(query_string, "&", &where); while(tok != NULL) { /* key=val */ char *_equal = strchr(tok, '='); if(_equal) { char *equal; 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((equal = (char*)malloc(len+1)) != NULL) { char *decoded_buf; Utils::urlDecode(_equal, equal, len+1); if((decoded_buf = http_decode(equal)) != NULL) { FILE *fd; Utils::purifyHTTPparam(tok, true, false); Utils::purifyHTTPparam(decoded_buf, false, false); /* Now make sure that decoded_buf is not a file path */ 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); */ if(strcmp(tok, "csrf") == 0) { char rsp[32], user[64] = { '\0' }; mg_get_cookie(conn, "user", user, sizeof(user)); if((ntop->getRedis()->get(decoded_buf, rsp, sizeof(rsp)) == -1) || (strcmp(rsp, user) != 0)) { const char *msg = "The submitted form is expired. Please reload the page and try again"; ntop->getTrace()->traceEvent(TRACE_WARNING, "Invalid CSRF parameter specified [%s][%s][%s][%s]: page expired?", decoded_buf, rsp, user, tok); free(equal); return(send_error(conn, 500 /* Internal server error */, msg, PAGE_ERROR, query_string, msg)); } else ntop->getRedis()->delKey(decoded_buf); } lua_push_str_table_entry(L, tok, decoded_buf); free(decoded_buf); } free(equal); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } tok = strtok_r(NULL, "&", &where); } /* while */ free(query_string); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } lua_setglobal(L, "_GET"); /* Like in php */ /* _SERVER */ lua_newtable(L); lua_push_str_table_entry(L, "HTTP_REFERER", (char*)mg_get_header(conn, "Referer")); lua_push_str_table_entry(L, "HTTP_USER_AGENT", (char*)mg_get_header(conn, "User-Agent")); lua_push_str_table_entry(L, "SERVER_NAME", (char*)mg_get_header(conn, "Host")); lua_setglobal(L, "_SERVER"); /* Like in php */ /* Cookies */ lua_newtable(L); if((_cookies = (char*)mg_get_header(conn, "Cookie")) != NULL) { char *cookies = strdup(_cookies); char *tok, *where; // ntop->getTrace()->traceEvent(TRACE_WARNING, "=> '%s'", cookies); tok = strtok_r(cookies, "=", &where); while(tok != NULL) { char *val; while(tok[0] == ' ') tok++; if((val = strtok_r(NULL, ";", &where)) != NULL) { lua_push_str_table_entry(L, tok, val); // ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, val); } else break; tok = strtok_r(NULL, "=", &where); } free(cookies); } lua_setglobal(L, "_COOKIE"); /* Like in php */ /* Put the _SESSION params into the environment */ lua_newtable(L); mg_get_cookie(conn, "user", user, sizeof(user)); lua_push_str_table_entry(L, "user", user); mg_get_cookie(conn, "session", buf, sizeof(buf)); lua_push_str_table_entry(L, "session", buf); // now it's time to set the interface. setInterface(user); lua_setglobal(L, "_SESSION"); /* Like in php */ if(user[0] != '\0') { char val[255]; lua_pushlightuserdata(L, user); lua_setglobal(L, "user"); snprintf(key, sizeof(key), "ntopng.user.%s.allowed_nets", user); if((ntop->getRedis()->get(key, val, sizeof(val)) != -1) && (val[0] != '\0')) { ptree.addAddresses(val); lua_pushlightuserdata(L, &ptree); lua_setglobal(L, CONST_ALLOWED_NETS); // ntop->getTrace()->traceEvent(TRACE_WARNING, "SET %p", ptree); } snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user); if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user) && !ntop->getRedis()->get(key, ifname, sizeof(ifname))) { lua_pushlightuserdata(L, ifname); lua_setglobal(L, CONST_ALLOWED_IFNAME); } } #ifndef NTOPNG_PRO rc = luaL_dofile(L, script_path); #else if(ntop->getPro()->has_valid_license()) rc = __ntop_lua_handlefile(L, script_path, true); else rc = luaL_dofile(L, script_path); #endif if(rc != 0) { const char *err = lua_tostring(L, -1); ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err); return(send_error(conn, 500 /* Internal server error */, "Internal server error", PAGE_ERROR, script_path, err)); } return(CONST_LUA_OK); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-352'], 'message': 'Check for presence of crsf in admin scripts'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_TCHECK2(tptr[0], 5); ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; ND_TCHECK2(tptr[0], 3); tlen = len; while (tlen >= 3) { type = *tptr; length = EXTRACT_16BITS(tptr+1); ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length - 3); switch (type) { case BGP_AIGP_TLV: ND_TCHECK2(tptr[3], 8); ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr+3))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr+3,"\n\t ", length-3); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12994/BGP: Move a test inside a loop. The loop can be executed more than once (that's kinda the whole point of a loop), so the check has to be made each time through the loop, not just once before the loop is executed. Do some additional length checks while we're at it. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr, unsigned long, data) { struct task_struct *child; long ret; if (request == PTRACE_TRACEME) { ret = ptrace_traceme(); if (!ret) arch_ptrace_attach(current); goto out; } child = ptrace_get_task_struct(pid); if (IS_ERR(child)) { ret = PTR_ERR(child); goto out; } if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) { ret = ptrace_attach(child, request, addr, data); /* * Some architectures need to do book-keeping after * a ptrace attach. */ if (!ret) arch_ptrace_attach(child); goto out_put_task_struct; } ret = ptrace_check_attach(child, request == PTRACE_KILL || request == PTRACE_INTERRUPT); if (ret < 0) goto out_put_task_struct; ret = arch_ptrace(child, request, addr, data); out_put_task_struct: put_task_struct(child); out: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-362'], 'message': 'ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL putreg() assumes that the tracee is not running and pt_regs_access() can safely play with its stack. However a killed tracee can return from ptrace_stop() to the low-level asm code and do RESTORE_REST, this means that debugger can actually read/modify the kernel stack until the tracee does SAVE_REST again. set_task_blockstep() can race with SIGKILL too and in some sense this race is even worse, the very fact the tracee can be woken up breaks the logic. As Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace() call, this ensures that nobody can ever wakeup the tracee while the debugger looks at it. Not only this fixes the mentioned problems, we can do some cleanups/simplifications in arch_ptrace() paths. Probably ptrace_unfreeze_traced() needs more callers, for example it makes sense to make the tracee killable for oom-killer before access_process_vm(). While at it, add the comment into may_ptrace_stop() to explain why ptrace_stop() still can't rely on SIGKILL and signal_pending_state(). Reported-by: Salman Qazi <sqazi@google.com> Reported-by: Suleiman Souhlal <suleiman@google.com> Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Oleg Nesterov <oleg@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mpls_print(netdissect_options *ndo, const u_char *bp, u_int length) { const u_char *p; uint32_t label_entry; uint16_t label_stack_depth = 0; enum mpls_packet_type pt = PT_UNKNOWN; p = bp; ND_PRINT((ndo, "MPLS")); do { ND_TCHECK2(*p, sizeof(label_entry)); if (length < sizeof(label_entry)) { ND_PRINT((ndo, "[|MPLS], length %u", length)); return; } label_entry = EXTRACT_32BITS(p); ND_PRINT((ndo, "%s(label %u", (label_stack_depth && ndo->ndo_vflag) ? "\n\t" : " ", MPLS_LABEL(label_entry))); label_stack_depth++; if (ndo->ndo_vflag && MPLS_LABEL(label_entry) < sizeof(mpls_labelname) / sizeof(mpls_labelname[0])) ND_PRINT((ndo, " (%s)", mpls_labelname[MPLS_LABEL(label_entry)])); ND_PRINT((ndo, ", exp %u", MPLS_EXP(label_entry))); if (MPLS_STACK(label_entry)) ND_PRINT((ndo, ", [S]")); ND_PRINT((ndo, ", ttl %u)", MPLS_TTL(label_entry))); p += sizeof(label_entry); length -= sizeof(label_entry); } while (!MPLS_STACK(label_entry)); /* * Try to figure out the packet type. */ switch (MPLS_LABEL(label_entry)) { case 0: /* IPv4 explicit NULL label */ case 3: /* IPv4 implicit NULL label */ pt = PT_IPV4; break; case 2: /* IPv6 explicit NULL label */ pt = PT_IPV6; break; default: /* * Generally there's no indication of protocol in MPLS label * encoding. * * However, draft-hsmit-isis-aal5mux-00.txt describes a * technique for encapsulating IS-IS and IP traffic on the * same ATM virtual circuit; you look at the first payload * byte to determine the network layer protocol, based on * the fact that * * 1) the first byte of an IP header is 0x45-0x4f * for IPv4 and 0x60-0x6f for IPv6; * * 2) the first byte of an OSI CLNP packet is 0x81, * the first byte of an OSI ES-IS packet is 0x82, * and the first byte of an OSI IS-IS packet is * 0x83; * * so the network layer protocol can be inferred from the * first byte of the packet, if the protocol is one of the * ones listed above. * * Cisco sends control-plane traffic MPLS-encapsulated in * this fashion. */ ND_TCHECK(*p); if (length < 1) { /* nothing to print */ return; } switch(*p) { case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: pt = PT_IPV4; break; case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: pt = PT_IPV6; break; case 0x81: case 0x82: case 0x83: pt = PT_OSI; break; default: /* ok bail out - we did not figure out what it is*/ break; } } /* * Print the payload. */ if (pt == PT_UNKNOWN) { if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, length); return; } ND_PRINT((ndo, ndo->ndo_vflag ? "\n\t" : " ")); switch (pt) { case PT_IPV4: ip_print(ndo, p, length); break; case PT_IPV6: ip6_print(ndo, p, length); break; case PT_OSI: isoclns_print(ndo, p, length, length); break; default: break; } return; trunc: ND_PRINT((ndo, "[|MPLS]")); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s).'</s>